Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
32 views

Chapter Two

Uploaded by

wubie derebe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Chapter Two

Uploaded by

wubie derebe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

4/13/2023

Basic Computer Programming

Chapter Two

C++ Basics

1.1. Introduction to C++


OVERVIEW
▪ C++programming language developed by Bjarne Stroustrup in 1979 at Bell Labs. C++
runs on a variety of platforms, such as Windows, Mac OS, and the various versions of
UNIX.

▪ C++ is regarded as a middle-level language, as it comprises a combination of both


high-level and low-level language features. It is a superset of C, and that virtually
any legal C program is a legal C++ program.

▪ C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form


programming language that supports procedural, object-oriented, and generic
programming. 2

1
4/13/2023

Cont’d….
▪ C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New
Jersey, as an enhancement to the C language and originally named C with Classes but later it
was renamed C++ in 1983.

▪ C++ is a superset of C, and that virtually any legal C program is a legal C++ program.

▪ The most important facilities that C++ adds on C language are C++ fully supports
object-oriented programming, including the four pillars of object-oriented development:
❖ Encapsulation
❖Data hiding
❖Inheritance
❖Polymorphism
❖Addition of namespaces and STL (Standard Template Library) and Many new keywords.

• The C++ programming language became popular soon after it was officially
launched.

• C++ allows procedural programming as well as object oriented programming.

SOME LIST OF FIELDS OF APPLICATIONS OF C++


• Operating Systems and component in windows XP and other OS components.
(ii) Software for e-commerce.

(iii) Customer service software such as electronic ticketing, car and flight reservations, etc.

(iv) Telecommunication services.

(v) 2-D and 3-D animations and games….etc

2
4/13/2023

COMPILERS FOR PROGRAMMING WITH C++


For execution of programs written in C++ you need to load a compiler software on your computer.
Compiler - a computer program that translates a high-level language to an object program.

• Some of the free compilers for


windows are given below.
• (i) Borland C++
• (ii) Dev-C++
• (iii) Quincy
• (iv) Microsoft Visual Studio
• (V) Code Block
• And more

The C++ STANDARD LIBRARY


• It is a rich collection of programs on classes, functions and template classes and
template functions which are helpful in program writing and in its execution.
• Every program requires applications of several functions of C++ Standard Library.
Standard C++ consists of three important parts:
• The core language giving all the building blocks including variables, data types and
literals, etc.
• The C++ Standard Library giving a rich set of functions manipulating files, strings,
etc.
• The Standard Template Library (STL) giving a rich set of methods manipulating
data structures, etc. 6

3
4/13/2023

• These functions are included in the program by including the header files
which contain these functions

• There are a number of files called header files and functions in C++ Standard
Library which help in the execution of the programs.

• Therefore, every program has to include the header files which are required
by the program.

• C++ program should necessarily contain the header file <iostream> which
stands for input and output stream used to take input with the help of
“cin>>” function and display the output using “cout<<” function.
7

• Basically, header files are of 2 types:


1.Standard library header files: These are the pre-existing header
files already available in the C/C++ compiler.
• C++ Header File
• #include<stdio. h> (Standard input-output header) ...
• #include<string. h> (String header) ...
• #include<conio. h> (Console input-output header) ...
• #include<stdlib. h> (Standard library header) ...
• #include<math. h> (Math header ) ...
• #include<ctype. h>(Character type header) ...
• #include<time. h>(Time header) ...
• #include<assert.
• User-defined header files: Header files starting #define can be
designed by the user.
8

4
4/13/2023

Structure of C++ Program


A typical program in C++ may comprise a list of statements involving
variables, constants, operators ,keyword, rules/special syntax and
functions.
C++ is a case sensitive language. E.g. A != a
Keywords have special meanings for the compiler and are used to
control and execute the program.
The keywords as well as names of files and functions in C++ Standard
Library are in general defined in lower case.
9

▪ Note that C++ provides the flexibility of writing a program with or without a class
and its member functions definitions.
▪ A simple C++ program (without a class) includes comments, headers, namespace,
main() and input/output statements.
The parts of a C++ Program
#include <iostream>
1. Using namespace std;
2. int main ()
3. {
4. cout << "Hello World\n";
5. return 0;
6. }

Any C++ program file should be saved with file name extension .cpp
10

5
4/13/2023

▪ The first line of the program is #include <iostream.h> in which the symbol
# is a pre-processor directive.

▪ It is a signal for pre-processor which runs before the compiler.

▪ The statement directs the compiler to include the header file<iostream.h> (input/output
stream) from C++ Standard Library in this program.

▪ The cin is used along with extraction operator(>>) for input and cout is used along with
insertion operator(<<) for output.

▪ The name of a header file when included in a program is enclosed between a pair of
angular brackets < >

▪ Only one header file is written in one line.


11

int main( )

▪ The third line of the above program (int main()) indicates the beginning of the
program.

▪ In C++ the parentheses ( ) are used to indicate that the identifier or name on its
left is a function.

▪ Here main () is also a function.

▪ Every program in C++ must have only one main() function.

▪ The word int stands for integer.

▪ In the present case the last line of the program reads return 0;

▪ If the above program runs successfully, it will return 0 to the system.


12

6
4/13/2023

Cont’d..
• the body of program enclosed in the curly braces{}.
• These braces generally contain expressions, statements and operators with a purpose to
carry out some action on the data presented to the program.
• Expressions are the conditions if fulfilled the statement following the expression is carried
out.
• In the program sample you will observe that all the statements in a C++ program end with
a semicolon ;
• The forth line is a statement. A statement is a computation step which may produce a
value.
• This brace ( } ) marks the end of the body of main.
13

Pg Putting Comments on C++ programs


• A comment is a piece of descriptive text which explains some aspect of a program.

• Program comments are text totally ignored by the compiler and are only intended to inform the
reader how the source code is working at any particular point in the program.

• C++ provides two types of comment delimiters:

• Single Line Comment: Anything after // {double forward slash} (until the end of the line on which it
appears) is considered a comment. Eg:

• cout<<var1; //this line prints the value of var1

• Multiple Line Comment: Anything enclosed by the pair /* and */ is considered a comment. Eg:
/*this is a kind of comment where
Multiple lines can be enclosed in
one C++ program */
14

7
4/13/2023

Compiler Errors vs. Runtime Errors


• Runtime Error is an error that occurs during the execution of a program.

• In contrast, compile-time errors occur while a program is being compiled.

• What can go wrong are run-time errors:

• Division by zero

• Dereferencing a null pointer

• Running out of memory

• What can go wrong at compile time?

• Syntax errors

• Type checking errors


15

C++Tokens and Basic Data types


• The smallest individual units in a program are known as tokens.

• C++ has the following tokens: Variables, Identifiers, Keywords, Constants, function,
Strings, and operators.
• A variable is an identifier that denotes a storage location used to store a data value. A
variable can be defined anywhere in the program. All variables have three important
properties:
• Data Type: a type which is established when the variable is defined. (e.g. integer, real,
character etc).
• Data type describes the property of the data and the size of the reserved memory.
• Name: a name which will be used to refer to the value in the variable. A unique identifier
for the reserved memory location
• Value: a value which can be changed by assigning a new value to the variable.
16

8
4/13/2023

Variables
• A variable is a name given to a memory location. It is the basic unit of storage in a
program.
• The value stored in a variable can be changed during program execution.
• A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
• In C++, all the variables must be declared before use.
Declaration of variables

• All variables can be declared before they are used.

• Variables can be created in a process known as declaration.

• syntax: Datatype Variable_Name;

• The name of a variable sometimes is called an identifie.


17

• Certain words are reserved by C++ for specific purposes and cannot be used as
identifiers.

• These are called reserved words or keywords and are summarized in the following
table.

Reserved/Key words have a unique meaning within a C++ program.

 These symbols, the reserved words, must not be used for any other purposes.

 All reserved words are in lower-case letters.

18

9
4/13/2023

Reserved words or keywords


reserved word is a word that cannot be used as an identifier, such as the name of a
variable, function, or label – it is "reserved from use".

19

Data types
• The data type specify the size, and type of values that can be stored.

• For instance, C++ looks the number 2 and 2.5 differently.

• The former is stored as integer requiring 4 bytes of memory space, whereas


the later stored as a double type and requires 8 bytes memory location.

• Every variable in C++ has a data type.

• Data type specifies the size and type of values that can be stored.

• The data types in C++ can be put into two categories:


• pre-defined or primitive data types and user-defined data types.
20

10
4/13/2023

Built-in data types( Primitive Data Types):


• C++ offers the programmer a rich assortment of built-in as well as user defined data
types. Following table lists down seven basic C++ data types.
Type Keyword

Boolean bool

Character char

Integer int

Floating point float

Double floating point double

Valueless void

Wide character wchar_t


21

➢ Both the numeric data types offer modifiers that are used to vary the nature of the data
to be stored. The modifiers used can be short, long, signed and unsigned.

➢ Several of the basic types can be modified using one or more of these type modifiers −

• signed
• unsigned

• short

• long
• The following table shows the variable type, how much memory it takes to store the
value in memory, and what is maximum and minimum value which can be stored in such
type of variables.

22

11
4/13/2023

23

24

12
4/13/2023

Signed and Unsigned


➢ Integer types come in two varieties: signed and unsigned.
➢The idea here is that sometimes you need negative numbers, and sometimes
you don't. Integers (short and long) without the word "unsigned" are assumed to
be signed.
➢Signed integers are either negative or positive. Unsigned integers are always
positive.
➢Because you have the same number of bytes for both signed and unsigned
integers, the largest number you can store in an unsigned integer is twice as big
as the largest positive number you can store in a signed integer.
➢An unsigned short integer can handle numbers from 0 to 65,535. Half the
numbers represented by a signed short are negative, thus a signed short can
only represent numbers from -32,768 to 32,767.
25

Wrapping around integer values


▪ The fact that unsigned long integers have a limit to the values they can hold is only rarely
a problem, but what happens if you do run out of room?
▪ The following example shows what happens if you try to put too large a value into a
short integer.
Example: A demonstration of putting too large a value in a variable
#include
int main()
{
unsigned short int smallNumber;
smallNumber = 65535;
cout << "Small number:" << smallNumber << endl;
smallNumber++;
cout << "Small number:" << smallNumber << endl;
smallNumber++;
cout << "Small number:" << smallNumber << endl;
return 0;
}
26

13
4/13/2023

Example: A demonstration of adding too large a number to a signed integer.


1: #include
2: int main()
3: {
4: short int smallNumber;
5: smallNumber = 32767;
6: cout << "Small number:" << smallNumber << endl;
7: smallNumber++;
8: cout << "Small number:" << smallNumber << endl;
9: smallNumber++;
10: cout << "Small number:" << smallNumber << endl;
11: return 0;
12: }

27

Identifiers
▪ Identifiers refer to a unique combination of letters and digits, either short or descriptive,
that are used to identify a variable, method, class or any other object in a programming
language uniquely.
▪ The identifiers in C++ can have identifiers with any length of characters.
▪ These characters can be alphanumeric i.e. can contain letters, digits and underscores and
whitespaces and special characters such as @,#,!etc are not allowed.
▪ These identifiers must start with a letter or an underscore and are case sensitive thus
keywords must not be used as an identifier.
• Identifiers are used to represent various objects such as:-
1.Constants
2.Variables
3.Functions
4.Labels
5.Defined Data Types
28

14
4/13/2023

Rules for Declaring an Identifier


• Let us understand some rules to declare them otherwise the compiler will throw
an error.
• Rule 1: It can be a combination of letters, digits or underscore, no special
characters such as #,$,! @ are allowed in identifiers name.
• Rule 2: The first character can be either letter or underscores(_). This means if
we use digit as the first character in the name of an identifier such as 1num, it
will not be treated as a valid name thus an error will be thrown by the compiler.
• Rule 3: These are case sensitive, which means NUM1 and num1 are not the
same identifiers.
• Rule 4: A keyword cannot be used as an identifier. C++ library has a list of
keywords used for different purposes such as if, else, long, int, float, goto, etc.
These variables cannot be used as an identifier name because there is a reserved
meaning for this word defined in the C++ library.
29

✓Valid Identifier

Invalid Identifiers:

30

15
4/13/2023

Initializing Variables
• When a variable is assigned a value at the time of declaration, it is called variable initialization.

• This is identical with declaring a variable and then assigning a value to the variable
immediately after declaration.

• Direct initialization:

• Syntax: DataType variable_name = value;

Datatype var_name;

var_name=value;

• from keyboard or user:

Datatype var_name;

cin>> var_name;
31

Creating More Than One Variable at a Time:


▪ You can create more than one variable of the same type in one statement by
writing the type and then the variable names, separated by commas.
For example:
int myAge, myWeight; // two int variables
long area, width, length; // three longs
As you can see, myAge and myWeight are each declared as integer
variables.
The second line declares three individual long variables named area, width,
and length.
▪ Note: However keep in mind that you cannot mix types in one definition
statement.
32

16
4/13/2023

Scope of Variables:
Scope of a variable is the boundary or block in a program where a
variable can be accessed.
The boundary or block is identified by the left and right French brackets
{}.
Global variables: are variables that can be referred/accessed anywhere
in the code, within any function, as long as it is declared first. A variable
declared before any function immediately after the include statements
are global variables.
Local Variables: the scope of the local variable is limited to the code
level or block within which they are declared.

33

Special Printing characters/Escape Characters


• Char in C++ are represented as any value inside a single quote.
• E.g.: ‘x’, ‘A’, ‘5’, ‘a’, etc.

• When the compiler finds such values (characters), it translates back the value
to the ASCII values. E.g. ‘a’ has a value 97 in ASCII.
• Special Printing characters.
• In C++, there are some special characters used for formatting.

34

17
4/13/2023

35

Expressions and Statements


▪ An expression is a combination of operators, constants, and variables arranged as per the
rules of the language.

▪ an expression is a computation which yields a value. It can also be viewed as any


statement that evaluates to a value (returns a value).

• In C++, a statement controls the sequence of execution, evaluates an expression, or does


nothing (the null statement).

• All C++ statements end with a semicolon.

• E.g: x = a + b;

36

18
4/13/2023

Operators
• An operator is a symbol that makes the machine to take an action.

• Different Operators act on one or more operands and can also have different
kinds of operators.

• C++ provides several categories of operators, including the following:

• Assignment operator, Arithmetic operator ,Relational operator ,Logical operator


• Increment/decrement operator ,Conditional operator

• Comma operator, The size of operator, casting operators, bitwise operator etc.

37

Assignment Operators
• The assignment operator causes the operand on the left side of the assignment statement
to have its value changed to the value on the right side of the statement.

• Syntax: Operand1=Operand2;

• Operand1 is always a variable

• Operand2 can be one or combination of.


• A literal constant: Eg: x=12;
• A variable: Eg: x=y;
• An expression: Eg: x=y+2;

38

19
4/13/2023

Arithmetic Operators((+, -, *, /, %))


▪ Except for remainder or modulo (%), all other arithmetic operators can accept a mix of
integers and real operands.

▪ Generally, if both operands are integers then, the result will be an integer.

▪ However, if one or both operands are real then the result will be real.

▪ When both operands of the division operator (/) are integers, then the division is
performed as an integer division and not the normal division we are used to.

▪ Integer division always results in an integer outcome.

▪ Division of integer by integer will not round off to the next integer

39

• Integer division always results in an integer outcome (i.e., the


result is always rounded down).
 For example:
9/2 // gives 4, not 4.5!
-9 / 2 // gives -4, not -4.5!

40

20
4/13/2023

Relational Operators
▪ Relational operators evaluate to 1 (representing the true outcome) or 0 (representing the
false outcome). ‘A’ < ‘F’ would return true or 1. it is like (65 < 70)

41

Logical Operators
• The relational operators, logical operators evaluate to 1 or 0.

• N.B. In general, any non-zero value can be used to represent the logical true, whereas
only zero represents the logical false.

42

21
4/13/2023

Increment/ Decrement Operators


• The auto increment (++) and auto decrement (--) operators provide a convenient way
of, respectively, adding and subtracting 1 from a numeric variable.
int k = 5;

43

• Both operators can be used in prefix and postfix form.


• When used in the prefix form, the operator is first applied and the outcome
is then used in the expression.
• When used in the postfix form, the expression is evaluated first and then the
operator applied.

44

22
4/13/2023

Bitwise Operators
In C++, bitwise operators perform operations on integer data at the individual bit-level. These
operations include testing, setting, or shifting the actual bits
Example:
a&b; Operator Description
a|b; & Bitwise AND Operator
Here is a list of 6 bitwise | Bitwise OR Operator
operators included in C++
^ Bitwise XOR Operator

~ Bitwise Complement Operator

<< Bitwise Shift Left Operator

>> Bitwise Shift Right Operator

45

46

23
4/13/2023

47

48

24
4/13/2023

C++ Shift Operators

There are two shift operators in C++ programming:


Right shift operator >>
Left shift operator <<
C++ Right Shift Operator
The right shift operator shifts all bits towards the right by a certain
number of specified bits. It is denoted by >>.

When we shift any number to the right, the least significant bits are
discarded, while the most significant bits are replaced by zeroes.
49

Simple Type conversion


✓A value in any of the built-in types we have see so far can be converted (type-cast) to
any of the other types.

For example:

➢(int) 3.14 // converts 3.14 to an int to give 3

➢(long) 3.14 // converts 3.14 to a long to give 3L

➢(double) 2 // converts 2 to a double to give 2.0

➢(char) 122 // converts 122 to a char whose code is z

➢(unsigned short) 3.14 // gives 3 as an unsigned short

50

25
4/13/2023

Conditional Operator (?:)


• The conditional operator takes three operands

• Syntax: operand1 ? operand2: operand3

• First operand1 is a relational expression and will be evaluated.

• If the result of the evaluation is non zero (which means true), then operand2 will be the
final result. Otherwise, operand3 is the final result.

• E.g.: General Example Z=(X<Y? X : Y) This expression means that if X is less than Y the
value of X will be assigned to Z otherwise (if X>=Y) the value of Y will be assigned to Z.

• E.g.: int m=1,n=2,min; min = (m < n ? m : n); The value stored in min is 1.

• E.g.: (7 = = 5 ? 4: 3) returns 3 since 7 is not equal to 5 51

The sizeof() Operator


•This operator is used for calculating the size of any data item or type.
• It takes a single operand (e.g. 100) and returns the size of the specified entity
in bytes. The outcome is totally machined dependent.

• E.g.: a = sizeof(char)

• b = sizeof(int)

• c = sizeof(1.55)

52

26
4/13/2023

Operator precedence
• The order in which operators are evaluated in an expression is significant and
is determined by precedence rules.

• Operators in higher levels take precedence over operators in lower levels.

• Precedence Table:

53

54

27
4/13/2023

1. Write a C++ program that outputs the following text on screen: Hint use endl or
‘\n’
Oh what

a happy day!

Oh yes,

2. Write a C++ program to prompt the user to input her/his name and print this
name on the screen, as shown below.

The text from keyboard can be read by using cin>> and to display the text on the
screen you can use cout<<Hello Programmers!.

55

3. Write a C++ program to print the following lines:


You are number 1.
You are too young to study programming.
4. Write a C++ program to prompt the user to input 3 integer values and print these
values in forward and reversed order, as shown below.
Please enter your 3 numbers: 12 45 78
Your numbers forward:
12
45
78
Your numbers reversed:
78
45
12

56

28
4/13/2023

5. Write a C++ program that two defines variables for floating-point


numbers and initializes them with the values 123.456 and 76.543 Then
display the sum and the difference of these two numbers on screen.

6. The sizeof operator can be used to determine the number of bytes


occupied in memory by a variable of a certain type. For example,
sizeof(short) is equivalent to 2. Write a C++ program that displays the
memory space required by each fundamental type on screen.

57

7. The following program contains several errors:


#include <stream>
int main
{
cout << "If this text",
cout >> " appears on your display, ";
cout << " endl;"
cout << 'you can pat yourself on '
<< " the back!" << endl.
return 0;
)
Resolve the errors and run the program to test your changes.

58

29
4/13/2023

End

59

30

You might also like