[go: up one dir, main page]

0% found this document useful (0 votes)
23 views52 pages

Chapter 2 - C++ Basics-1

Chapter two introduces the basics of C++ programming, including its history, key features, and the development cycle of a C++ program. It covers essential concepts such as writing, compiling, and linking code, as well as fundamental elements like variables, data types, and operators. The chapter also provides examples of simple C++ programs and explains the significance of keywords, comments, and variable declarations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views52 pages

Chapter 2 - C++ Basics-1

Chapter two introduces the basics of C++ programming, including its history, key features, and the development cycle of a C++ program. It covers essential concepts such as writing, compiling, and linking code, as well as fundamental elements like variables, data types, and operators. The chapter also provides examples of simple C++ programs and explains the significance of keywords, comments, and variable declarations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Chapter two: C++ Basics

2. Introduction to C++ programming


2.1. History of C++
C++ as the name implies, is essentially based on the C programming language. The C++ programming
language was invented by Bjarne Stroustroup in 1979.The initial version was called “C with Classes”.
That name is did not work well, and replaced with C++.The first commercial implementation was
released in 1985.The C++ language standards are now handled by the American National Standards
Institute (ANSI) and the International Standards Organizations (ISO).
2.2. What is C++?
The C programming is developed first, C++ was developed later. The main difference between the two
languages is that C++ is supports object orientation. However, C++ supports many improvements
over C. Example, C++ handles strings better than C and has a more robust exception handling. C
code will compile fine in most C++ compilers, but the reverse is not true. C++ code will not
necessarily compile in a C compiler.
Code is the series of programming commands that a programmer writes.
2.3. First C++ program
A computer program is a sequence of instructions that tell the computer what to do.
The complete development cycle in C++ is: Write the program, compile the source code, link the
program, and run it.
Writing a Program
To write a source code, your compiler may have its own built-in text editor, or you may be using a
commercial text editor or word processor that can produce text files. Many commercial word
processors, such as WordPerfect, Word, and dozens of others, also offer a method for saving simple
text files.
The files you create with your editor are called source files, and for C++ they typically are named with
the extension .CPP.
Compiling
To turn your source code into a program, you use a compiler. How you invoke your compiler, and
how you tell it where to find your source code, will vary from compiler to compiler. In Borland's
Turbo C++ you can choose the compile option in the menu. Other compilers may do things slightly
differently. After your source code is compiled, an object file is produced. This file is often named

-1- 2025
with the extension .OBJ. This is still not an executable program, however. To turn this into an
executable program, you must run your linker.
An interpreter is a program that reads code and essentially compiles and executes (interprets) your
program as it is run. One advantage of interpreters is that they are much easier to write than compilers,
because they can be written in a high-level language themselves.
Linking is the process of taking all the object files for a program and combining them into a single
executable. C++ programs are typically created by linking together one or more OBJ files with one or
more libraries. A library is a collection of linkable files that were supplied with your compiler, that
you purchased separately, or that you created and compiled. All C++ compilers come with a library of
useful functions (or procedures) and classes that you can include in your program. Function is a
sequence of statements designed to do a particular job, such as adding two numbers or printing to the
screen. A class is a collection of data and related functions.
2.1. Showing Sample program
Any meaningful program written in C++ has to contain a number of components: the main function;
some variable declarations; and some executable statements. For example, the following is a very basic
C++ program:
1: #include <iostream.h>
2: int main()
3: {
4: cout << "Hello World!\n";
5: return 0;
6: }
Line 1 is a special type of statement called a preprocessor directive.
Preprocessor directives tell the compiler to perform a special task. In this case, we are telling the
compiler that we would like to use the iostream library.
The iostream library contains code that tells the compiler what cout and endl do.
Line 2 declares the main () function is mandatory. Every program must have a main () function.
Lines 3 and 6 tell the compiler which lines are part of the main function. Everything between the
opening curly brace on line 3 and the closing curly brace on line 6 is considered part of the main ()
function.
Line 4 is our first statement (you can tell it’s a statement because it ends with a semicolon). As you
learned in the explanation for line 1, cout and endl live inside the iostream library. cout is a special
object that represents the console output/screen. The << symbol is an operator called the output

-2- 2025
operator. cout understands that anything sent to it via the << operator should be printed on the screen.
Endl is a special symbol that moves the cursor to the next line.
Line 7 is a new type of statement, called a return statement. When an executable program finish
running, it sends a value to the operating system that indicates whether it was run successfully or not.
Statements and expressions
The most common type of instruction in a program is the statement. A statement in C++ is the
smallest independent unit in the language. In human language, it is analogous to a sentence. We write
sentences in order to convey an idea. In C++, we write statements in order to convey to the compiler
that we want to perform a task. Statements in C++ are terminated by a semicolon.
There are many different kinds of statements in C++. The following are some of the most common
types of simple statements:
1 int x;
2 x=5;
3 cout<<x;
int x is a declaration statement. It tells the compiler that x is a variable. All variables in a program
must be declared before they are used.
x = 5 is an assignment statement. It assigns a value (5) to a variable (x).
cout << x; is an output statement. It outputs the value of x.
An expression is a mathematical entity that evaluates to a value. For example, in math, the expression
2+3 evaluates to the value 5. Expressions can involve values (such as 2), variables (such as x),
operators (such as +).
For example, the statement x = 2 + 3; is a valid assignment statement. The expression 2+3 evaluates
to the value of 5. This value of 5 is then assigned to x.
2.2. Keywords, Variables, Constants, Operators and Basic Data Types
2.2.1. Keywords (reserved words)
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. The
following are some of the reserved words of C++.
asm auto bool break case catch
const_cast class const char continue default
dynamic_cast do double delete else enum
explicit extern false float for friend

-3- 2025
goto if inline int long mutable
namespace new operator private protected public
reinterpret_cast register return short signed sizeof
static_cast static struct switch template this
throw true try typedef typeid typename
union unsigned using virtual void volatile
wchar_t
Notice that main is not a reserved word. However, this is a fairly technical distinction, and for practical
purposes you are advised to treat main, cin, and cout as if they were reserved as well.
2.2.2 Comments
A comment is a line (or multiple lines) of text that are inserted into the source code to explain what the
code is doing. Program comments are totally ignored by the compiler and are only intended for human
readers. C++ provides two types of comment delimiters:
The // symbol begins a C++ single-line comment, which tells the compiler to ignore
everything to the end of the line.
For example:
cout<<”Hello world”; // to display Hello world to the screen
The /* and */ pair of symbols denotes a multi-line comment. Everything in between the
symbols is ignored.
2.2.3 Variables
A variable in C++ is a name for a piece of memory that can be used to store information. Variables are
used for holding data values so that they can be utilized in various computations in a program. All
variables have two important attributes:
 A type, which is, established when the variable is defined (e.g., integer, float, character). Once
defined, the type of a C++ variable cannot be changed.
 A value, which can be changed by assigning a new value to the variable. The kind of values a
variable can assume depends on its type. For example, an integer variable can only take integer
values (e.g., 2, 100, -12) not real numbers like 0.123.
Variable Declaration
Declaring a variable means defining (creating) a variable. You create or define a variable by stating its
type, followed by one or more spaces, followed by the variable name and a semicolon. The variable
name can be virtually any combination of letters, but cannot contain spaces and the first character must
-4- 2025
be a letter or an underscore. Variable names cannot also be the same as keywords used by C++. Legal
variable names include x, J23qrsnf, and myAge. Good variable names tell you what the variables are
for; using good names makes it easier to understand the flow of your program. The following
statement defines an integer variable called myAge:
int myAge;
IMPORTANT- Variables must be declared before used!
A point worth mentioning again here is that C++ is case-sensitive. In other words, uppercase and
lowercase letters are considered to be different. A variable named age is different from Age, which is
different from AGE.
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
However keep in mind that you cannot mix types in one definition statement.
Assigning Values to Your Variables
You assign a value to a variable by using the assignment operator (=). Thus, you would assign 5 to
Width by writing
int Width;
Width = 5;
You can combine these steps and initialize Width when you define it by writing
intWidth= 5;
Just as you can define more than one variable at a time, you can initialize more than one variable at
creation. For example:
// create two int variables and initialize them
int width = 5, length = 7;
This example initializes the integer variable width to the value 5 and the length variable to the value 7.
It is possible to even mix definitions and initializations:
int myAge = 39, yourAge, hisAge = 40;
This example creates three type int variables, and it initializes the first and third.
2.2.4 Basic Data Types
Several data types are built into C++. The varieties of data types allow programmers to select the type
appropriate to the needs of the applications being developed. The data types supported by C++ can be

-5- 2025
classified as basic (fundamental) data types, user defined data types, derived data types and empty data
types. However, the discussion here will focus only on the basic data types.
Basic (fundamental) data types in C++ can be conveniently divided into numeric and character types.
Numeric variables can further be divided into integer variables and floating-point variables. Integer
variables will hold only integers whereas floating number variables can accommodate real numbers.
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.
The data types used in C++ programs are described in Table 1.1. The values that can be stored are
determined by the size of the variable types.
Table C++ data types and their ranges
Type Size Values
unsigned short int 2 bytes 0 to 65,535
short int(signed short int) 2 bytes -32,768 to 32,767
unsigned long int 4 bytes 0 to 4,294,967,295
long int(signed long int) 4 bytes -2,147,483,648 to 2,147,483,647
int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
signed int 2 bytes -32,768 to 32,767
char 1 byte 256-character values
float 4 bytes 3.4e-38 to 3.4e38
double 8 bytes 1.7e-308 to 1.7e308
long double 10 bytes 1.2e-4932 to 1.2e4932
2.2.5 Signed and Unsigned
As shown above, 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.
Example: A demonstration of the use of variables.
-6- 2025
2: #include <iostream.h>
3:
4: int main()
5: {
6: unsigned short int Width = 5, Length;
7: Length = 10;
8:
9: // create an unsigned short and initialize with result
10: // of multiplying Width by Length
11: unsigned short int Area = Width * Length;
12:
13: cout << "Width:" << Width << "\n";
14: cout << "Length: " << Length << endl;
15: cout << "Area: " << Area << endl;
16: return 0;
17: }
Output: Width:5
Length: 10
Area: 50
Line 2 includes the required include statement for the iostream's library so that cout will work. Line 4
begins the program.
On line 6, Width is defined as an unsigned short integer, and its value is initialized to 5. Another
unsigned short integer, Length, is also defined, but it is not initialized. On line 7, the value 10 is
assigned to Length.
On line 11, an unsigned short integer, Area, is defined, and it is initialized with the value obtained by
multiplying Width times Length. On lines 13-15, the values of the variables are printed to the screen.
Note that the special word endl creates a new line.
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? When an unsigned integer reaches its maximum value, it
wraps around and starts over, much as a car odometer might. 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
1: #include <iostream.h>
2: int main()
3: {

-7- 2025
4: unsigned short int smallNumber;
5: smallNumber = 65535;
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: }
Output: small number:65535
small number:0
small number:1
A signed integer is different from an unsigned integer, in that half of the values you can represent are
negative. Instead of picturing a traditional car odometer, you might picture one that rotates up for
positive numbers and down for negative numbers. One mile from 0 is either 1 or -1. When you run out
of positive numbers, you run right into the largest negative numbers and then count back down to 0.
The whole idea here is putting a number that is above the range of the variable can create unpredictable
problem.
Example: A demonstration of adding too large a number to a signed integer.
1: #include <iostream.h>
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: }
Output: small number:32767
small number:-32768
small number:-32767
IMPORTANT – To any variable, do not assign a value that is beyond its range!
2.2.6 Characters
Character variables (type char) are typically 1 byte, enough to hold 256 values. A char can be
interpreted as a small number (0-255) or as a member of the ASCII set. ASCII stands for the American
-8- 2025
Standard Code for Information Interchange. The ASCII character set and its ISO (International
Standards Organization) equivalent are a way to encode all the letters, numerals, and punctuation
marks.
In the ASCII code, the lowercase letter "a" is assigned the value 97. All the lower- and uppercase
letters, all the numerals, and all the punctuation marks are assigned values between 1 and 128. Another
128 marks and symbols are reserved for use by the computer maker, although the IBM extended
character set has become something of a standard.
2.2.7 Characters and Numbers
When you put a character, for example, `a', into a char variable, what is really there is just a number
between 0 and 255. The compiler knows, however, how to translate back and forth between characters
(represented by a single quotation mark and then a letter, numeral, or punctuation mark, followed by a
closing single quotation mark) and one of the ASCII values.
The value/letter relationship is arbitrary; there is no particular reason that the lowercase "a" is assigned
the value 97. As long as everyone (your keyboard, compiler, and screen) agrees, there is no problem. It
is important to realize, however, that there is a big difference between the value 5 and the character `5'.
The latter is actually valued at 53, much as the letter `a' is valued at 97.
2.3 Operators
C++ provides operators for composing arithmetic, relational, logical, bitwise, and conditional
expressions. It also provides operators which produce useful side-effects, such as assignment,
increment, and decrement.
2.3.3 Assignment Operators
The assignment operator is used for storing a value at some memory location (typically denoted by a
variable). Its left operand should be an lvalue, and its right operand may be an arbitrary expression.
The latter is evaluated and the outcome is stored in the location denoted by the lvalue.
The only kind of lvalue we have seen so far is a variable. The assignment operator has a number of
variants, obtained by combining it with the arithmetic and bitwise operators.
Operator Example Equivalent To

= n = 25
+= n += 25 n = n + 25
-= n -= 25 n = n - 25
*= n *= 25 n = n * 25
/= n /= 25 n = n / 25

-9- 2025
%= n %= 25 n = n % 25
An assignment operation is itself an expression whose value is the value stored in its left operand. An
assignment operation can therefore be used as the right operand of another assignment operation. Any
number of assignments can be concatenated in this fashion to form one expression. For example:
int m, n, p;
m = n = p = 100; // means: n = (m = (p = 100));
m = (n = p = 100) + 2; // means: m = (n = (p = 100)) + 2;
2.3.4 Arithmetic Operators
C++ provides five basic arithmetic operators. These are summarized in table below
Operator Name Example
+ Addition 12 + 4.9 // gives 16.9
- Subtraction 3.98 - 4 // gives -0.02
* Multiplication 2 * 3.4 // gives 6.8
/ Division 9 / 2.0 // gives 4.5
% Remainder 13 % 3 //gives 1
Except for remainder (%) all other arithmetic operators can accept a mix of integer and real operands.
Generally, if both operands are integers, then the result will be an integer. However, if one or both of
the operands are reals then the result will be a real (or double to be exact).
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 (i.e., the result is always rounded down). For example:
9 /2 //gives4,not4.5!
-9/ 2 //gives-5,not-4!
Unintended integer divisions are a common source of programming errors. To obtain a real division
when both operands are integers, you should cast one of the operands to be real:
int cost= 100;
int volume= 80;
double unitPrice= cost/(double)volume; //gives1.25
The remainder operator (%) expects integers for both of its operands. It returns the remainder of
integer-dividing the operands. For example 13%3 is calculated by integer dividing 13 by 3 to give an
outcome of 4 and a remainder of 1; the result is therefore 1.
It is possible for the outcome of an arithmetic operation to be too large for storing in a designated
variable. This situation is called an overflow. The outcome of an overflow is machine-dependent and
therefore undefined. For example:
- 10 - 2025
unsigned char k = 10 * 92; // overflow: 920 > 255
It is illegal to divide a number by zero. This results in a run-time division-by-zero failure, which
typically causes the program to terminate.
There are also a number of predefined library functions, which perform arithmetic operations. As with
input & output statements, if you want to use these you must put a #include statement at the start of
your program. Some of the more common library functions are summarised below.

Header Parameter Result


Function Type(s)
Result
File Type
<stdlib.h> abs(i) int int Absolute value of i
<math.h> cos(x) float float Cosine of x (x is in radians)
<math.h> fabs(x) float float Absolute value of x
<math.h> pow(x, y) float float x raised to the power of y
<math.h> sin(x) float float Sine of x (x is in radians)
<math.h> sqrt(x) float float Square root of x
<math.h> tan(x) float float Tangent of x

2.3.5 Relational Operators


C++ provides six relational operators for comparing numeric quantities. These are summarized in table
below. Relational operators evaluate to 1 (representing the true outcome) or 0 (representing the false
outcome).
Operator Name Example
== Equality 5 == 5 // gives 1
!= Inequality 5 != 5 // gives 0
< Less Than 5 < 5.5 // gives 1
<= Less Than or Equal 5 <= 5 // gives 1
> Greater Than 5 > 5.5 // gives 0
>= Greater Than or Equal 6.3 >= 5 // gives 1
Relational operators
Note that the <= and >= operators are only supported in the form shown. In particular, =< and => are
both invalid and do not mean anything.

- 11 - 2025
The operands of a relational operator must evaluate to a number. Characters are valid operands since
they are represented by numeric values. For example (assuming ASCII coding):
'A' < 'F' // gives 1 (is like 65 < 70)
The relational operators should not be used for comparing strings, because this will result in the string
addresses being compared, not the string contents. For example, the expression "HELLO" < "BYE"
causes the address of "HELLO" to be compared to the address of "BYE". As these addresses are
determined by the compiler (in a machine-dependent manner), the outcome may be 0 or 1, and is
therefore undefined. C++ provides library functions (e.g., strcmp) for the lexicographic comparison of
string.
2.3.6 Logical Operators
C++ provides three logical operators for combining logical expression. These are summarized in the
table below. Like the relational operators, logical operators evaluate to 1 or 0.
Operator Name Example
! Logical Negation !(5 == 5) // gives 0
&& Logical And 5 < 6 && 6 < 6 // gives 1
|| Logical Or 5 < 6 || 6 < 5 // gives 1
Logical operators

Logical negation is a unary operator, which negates the logical value of its single operand. If its
operand is nonzero, it produces 0, and if it is 0 it produces 1.
Logical and produces 0 if one or both of its operands evaluate to 0. Otherwise, it produces 1. Logical
or produces 0 if both of its operands evaluate to 0. Otherwise, it produces 1.
Note that here we talk of zero and nonzero operands (not zero and 1). In general, any nonzero value
can be used to represent the logical true, whereas only zero represents the logical false. The following
are, therefore, all valid logical expressions:
!20 // gives 0
10 && 5 // gives 1
10 || 5.5 // gives 1
10 && 0 // gives 0
C++ does not have a built-in boolean type. It is customary to use the type int for this purpose instead.
For example:
int sorted = 0; // false
int balanced = 1; // true
- 12 - 2025
2.3.7 Bitwise Operators
C++ provides six bitwise operators for manipulating the individual bits in an integer quantity. These
are summarized in the table below.
Operator Name Example
~ Bitwise Negation ~'\011' // gives '\366'
& Bitwise And '\011' & '\027' // gives '\001'
| Bitwise Or '\011' | '\027' // gives '\037'
^ Bitwise Exclusive '\011' ^ '\027' // gives '\036'
Or
<< Bitwise Left Shift '\011' << 2 // gives '\044'
>> Bitwise Right Shift '\011' >> 2 // gives '\002'
Bitwise operators
Bitwise operators expect their operands to be integer quantities and treat them as bit sequences.
Bitwise negation is a unary operator which reverses the bits in its operands. Bitwise and compares the
corresponding bits of its operands and produces a 1 when both bits are 1, and 0 otherwise. Bitwise or
compares the corresponding bits of its operands and produces a 0 when both bits are 0, and 1 otherwise.
Bitwise exclusive or compares the corresponding bits of its operands and produces a 0 when both bits
are 1 or both bits are 0, and 1 otherwise.
Bitwise left shift operator and bitwise right shift operator both take a bit sequence as their left operand
and a positive integer quantity n as their right operand. The former produces a bit sequence equal to the
left operand but which has been shifted n bit positions to the left. The latter produces a bit sequence
equal to the left operand but which has been shifted n bit positions to the right. Vacated bits at either
end are set to 0.
Table 2.1 illustrates bit sequences for the sample operands and results in Table 2.Error! Bookmark
not defined.. To avoid worrying about the sign bit (which is machine dependent), it is common to
declare a bit sequence as an unsigned quantity:
unsignedcharx = '\011';
unsignedchary = '\027';
Table 2.1 How the bits are calculated.
Example Octal Value Bit Sequence
X 011 0 0 0 0 1 0 0 1
Y 027 0 0 0 1 0 1 1 1
~x 366 1 1 1 1 0 1 1 0

- 13 - 2025
x&y 001 0 0 0 0 0 0 0 1
x|y 037 0 0 0 1 1 1 1 1
x^y 036 0 0 0 1 1 1 1 0
x << 2 044 0 0 1 0 0 1 0 0
x >> 2 002 0 0 0 0 0 0 1 0
2.3.8 Increment/decrement Operators
The auto increment (++) and auto decrement (--) operators provide a convenient way of, respectively,
adding and subtracting 1 from a numeric variable. These are summarized in the following table. The
examples assume the following variable definition:
int k = 5;
Operator Name Example
++ Auto Increment (prefix) ++k + 10 // gives 16
++ Auto Increment (postfix) k++ + 10 // gives 15
-- Auto Decrement (prefix) --k + 10 // gives 14
-- Auto Decrement (postfix) k-- + 10 // gives 15
Increment and decrement operators
Both operators can be used in prefix and postfix form. The difference is significant. When used in
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. Both operators may be
applied to integer as well as real variables, although in practice real variables are rarely useful in this
form.
2.3.9 C++ Ternary Operator
In C++, the ternary or conditional operator ( ? : ) is the shortest form of writing conditional statements.
It can be used as an inline conditional statement in place of if-else to execute some conditional code.
Syntax of Ternary Operator ( ? : )
The syntax of the ternary (or conditional) operator is:
expression? statement_1: statement_2;
As the name suggests, the ternary operator works on three operands where
• expression: Condition to be evaluated.
• statement_1: Statement that will be executed if the expression evaluates to true.
• statement_2: Code to be executed if the expression evaluates to false.
// image
The above statement of the ternary operator is equivalent to the if-else statement given below:
- 14 - 2025
if ( condition ) {
statement1;
}
else {
statement2;
}
Example of Ternary Operator in C++
// C++ program to illustrate the use of ternary operator
#include <iostream>
using namespace std;

int main()
{
// creating a variable
int num, test = 40;
// assigning the value of num based on the value of test
// variable
num = test < 10 ? 10 : test + 10;
printf("Num - Test = %d", num - test);
return 0;
}
Output
Num - Test = 10
In the above code, we have used the ternary operator to assign the value of the variable num depending
upon the value of another variable named test.
Note: The ternary operator have third most lowest precedence, so we need to use the expressions such
that we can avoid errors due to improper operator precedence management.
2.4 Precedence of Operators
The order in which operators are evaluated in an expression is significant and is determined by
precedence rules. These rules divide the C++ operators into a number of precedence levels. Operators
in higher levels take precedence over operators in lower levels.

Level Operator Kind Order

- 15 - 2025
Highest :: Unary Both
() [] -> . Binary Left to Right
+ ++ ! * new sizeof() Unary Right to Left
- -- ~ & delete
->* .* Binary Left to Right
* / % Binary Left to Right
+ - Binary Left to Right
<< >> Binary Left to Right
< <= > >= Binary Left to Right
== != Binary Left to Right
& Binary Left to Right
^ Binary Left to Right
| Binary Left to Right
& Binary Left to Right
&
|| Binary Left to Right
?: Ternary Left to Right
= += *= ^= &= <<= Binary Right to Left
-= /= %= |= >>=
Lowest , Binary Left to Right

For example, in
a == b + c * d
c * d is evaluated first because * has a higher precedence than + and ==. The result is then added to b
because + has a higher precedence than ==, and then == is evaluated. Precedence rules can be
overridden using brackets. For example, rewriting the above expression as
a== (b+ c)* d
causes + to be evaluated before *.
Operators with the same precedence level are evaluated in the order specified by the last column of
Table 2.7. For example, in
a= b += c
the evaluation order is right to left, so first b += c is evaluated, followed by a = b.

- 16 - 2025
2.5 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 122 is z
(unsigned short) 3.14 // gives 3 as an unsigned short

As shown by these examples, the built-in type identifiers can be used as type operators. Type operators
are unary (i.e., take one operand) and appear inside brackets to the left of their operand. This is called
explicit type conversion. When the type name is just one word, an alternate notation may be used in
which the brackets appear around the operand:
int(3.14) // same as: (int) 3.14
In some cases, C++ also performs implicit type conversion. This happens when values of different
types are mixed in an expression. For example:

double d = 1; // d receives 1.0


int i = 10.5; // i receives 10
i = i + d; // means: i = int(double(i) + d)

In the last example, i + d involves mismatching types, so i is first converted to double (promoted) and
then added to d. The result is a double which does not match the type of i on the left side of the
assignment, so it is converted to int (demoted) before being assigned to i.
The above rules represent some simple but common cases for type conversion.

- 17 - 2025
CHAPTER THREE
SELECTION AND CONDITIONAL STATEMENTS
3.1 Introduction
A running program spends all of its time executing statements. The order in which statements are
executed is called flow control (or control flow). This term reflects the fact that the currently
executing statement has the control of the CPU, which when completed will be handed over (flow) to
another statement. Flow control in a program is typically sequential, from one statement to the next,
but may be diverted to other paths by branch statements. Flow control is an important consideration
because it determines what is executed during a run and what is not, therefore affecting the overall
outcome of the program.
Selection statements indicates that a decision (Based on some condition) needs to be made, followed
by an appropriate action derived from that decision.
3.2 If statement (Simple C++ selection Statement)

- 18 - 2025
Program control statements determine your program’s flow of execution. If statement is one of C++’s
conditional (selection) statements. The if statement checks whether the text expression inside
parenthesis ( ) is true or not. If the test expression is true, statement/s inside the body of if statement is
executed but if test is false, statement/s inside body of if is ignored.
Syntax of If statement
if (test expression)
{
statement/s to be executed if test expression is true;
}
Example: if(x<0)
{
cout<<”x is negative”;
}
In this expression we use C++ relational operators for comparisons.
if(x) {……} is equivalent if(x! =0) {…….}
if (! x) {…} is equivalent if(x==0) {……..}
Example: Write a C++ program to print the number entered by user only if the number entered
is negative.
#include <iostream.h>
int main(){
int num;
cout<<”Enter a number to check.\n"; //prompting a user to enter a value for variable x.
cin>>num; //input console
if(num<0) /* checking whether number is less than 0 or not. */
{
cout<<" Your number is “<<,num<<endl; //displaying value of number to the screen
cout<<”Your number is negative”<<endl;
}
/*If test condition is true, statement above will be executed, otherwise it will not be executed */
Cout<<"The if statement in C++ programming is so easy."<<endl;
return 0; // main function successfully terminated
}// end of main function
Output: if you entered negative number like -5

- 19 - 2025
You get the output like: Your number is -5
Your number is negative
If you entered positive number like 2
You get the output like: The if statement in C++ programming is so easy
C++ if...else statement
The if...else statement is used if the programmer wants to execute some statement/s when the test
expression is true and execute some other statement/s if the test expression is false.
if (test expression) {
statements to be executed if test expression is true;
}
else {
statements to be executed if test expression is false;
}
Example: if(x>0){
cout<<”x is positve”<<endl;
else{
cout<<”X is negative” ;}}
Example: Write a C++ program to check whether a number entered by user is positive or
negative.
#include<iostream.h>
int main(){
int x;
cout<<"Enter value for x"<<endl;
cin>>x;
if(x>0){
cout<<"x is positve"<<endl;
}
else{
cout<<"X is negative"<<endl;
}
return 0;
}

- 20 - 2025
Nested if...else statement (if...else if....else Statement)
The nested if...else statement is used when program requires more than one test expression.
The nested if...else statement has more than one test expression. If the first test expression is true, it
executes the code inside the braces { } just below it. But if the first test expression is false, it checks
the second test expression. If the second test expression is true, it executes the statement/s inside the
braces { } just below it. This process continues. If all the test expression are false, code/s inside else is
executed and the control of program jumps below the nested if...else.
if (test expression1){
statement/s to be executed if test expression1 is true;
}
else if (test expression2) {
statement/s to be executed if test expression1 is false and 2 is true;
}
else if (test expression 3) {
statement/s to be executed if text expression1 and 2 are false and 3 is true;
}
.
.
.
else {
statements to be executed if all test expressions are false;
}
Example: Write a C++ program to relate two integers entered by user using = or > or < sign.
#include <iostream.h>
int main(){
int numb1, numb2;
cout<<"Enter two integers to check\n";
cin>>numb1>>numb2;
if(numb1==numb2) //checking whether two integers are equal.
cout<<"Result: numm1 ==numb2 "<<numb1<<"=="<<numb2<<endl;
else if(numb1>numb2) //checking whether numb1 is greater than numb2.
cout<<"Result:numb1 > numb2 "<<numb1<<" > "<<numb2<<endl;
else

- 21 - 2025
cout<<"Result: numb2>numb1 "<<numb2<<" > "<<numb1<<endl;
return 0;
}
C++ Switch statement
In switch...case, expression is either an integer or a character. If the value of switch expression matches
any of the constant in case, the relevant codes are executed and control moves out of the switch...case
statement. If the expression doesn't match any of the constant in case, then the default statement is
executed.
Syntax of switch...case
switch (expression)
{
case constant1:
codes to be executed if expression equals to constant1;
break;
case constant2:
codes to be executed if expression equals to constant2;
break;
.
.
.
default:
codes to be executed if expression doesn't match to any cases;
}
Example: Program to print day of week using switch statement.
/*C++ Program to print day of week using switch statement. */

#include<iostream.h> /* Header Files*/


void main()
{
int day; /* variable declration */

cout<<"Enter Week day no ";


cin>>day;

- 22 - 2025
switch(day) /*test expression*/
{
case 1:
cout<<"Monday\n";
break;
case 2:
cout<<"Tuesday\n";
break;
case 3:
cout<<"Wednesday\n";
break;
case 4:
cout<<"Thursday\n";
break;
case 5:
cout<<"Friday\n";
break;
case 6:
cout<<"Saturday\n";
break;
case 7:
cout<<"Sunday\n";
break;
default:
cout<<"Wrong entry\n";
}}

Exaple2: Write a program that asks user an arithmetic operator ('+','-','*' or '/') and two
operands and perform the corresponding calculation on the operands.
/* C++ program to demonstrate the working of switch...case statement */
/* Program to create a simple calculator for addition, subtraction, multiplication and division */
# include <iostream.h>

- 23 - 2025
int main()
{
char Op;
float num1,num2;
cout<<"\nEnter operator either + or - or * or /\n ";
cin>>Op;
cout<<"\nEnter two operands: \n";
cin>>num1>>num2;
switch(Op) {
case '+':
cout<<"The sum of "<<num1<<" and "<<num2<<" is "<<(num1+num2)<<endl;
break;
case '-':
cout<<"The difference of "<<num1<<" and "<<num2<<" is "<< (num1-num2)<<endl;
break;
case '*':
cout<<"The product of "<<num1<<" and "<<num2<<" is "<< (num1*num2)<<endl;
break;
case '/':
cout<<"The quotient of "<<num1<<" and "<<num2<<" is "<<(num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
cout<<"\nError! Operator is not correct\n";
break;
}
return 0;
}
3.3 C++ Looping Statements
Loops cause program to execute the certain block of code repeatedly until test condition is false. Loops
are used in performing repetitive task in programming.
Consider these scenarios: You want to execute some code/s 100 times. You want to execute some
code/s certain number of times depending upon input from user. These types of task can be solved

- 24 - 2025
in programming using loops.
There are 3 types of loops in C programming:
1. For Loop
2. While Loop
3. Do…While Loop
3.3.1 The ‘for’ Statement
For loop is used execute certain code iteratively (repeatedly). The for statement (also called for loop) is
similar to the while statement, but has two additional components: an expression which is evaluated
only once before everything else, and an expression which is evaluated once at the end of each
iteration.
The general form of the for statement is:
for(initialization statement; test expression; increment/decrement statement)
{
code/s to be executed;
}
How for loop works in C++ programming?
The initialization statement is executed only once at the beginning of the for loop. Then the test
expression is checked by the program. If the test expression is false, for loop is terminated. But if
test expression is true then the code/s inside body of for loop is executed and then
increment/decrement statement is incremented/decremented. This process repeats until test
expression is false.
The most common use of for loops is for situations where a variable is incremented or decremented
with every iteration of the loop.
Example: sum = 0;
for (int i = 1; i <= n; ++i)
sum += i;
In this example, i is usually called the loop variable.
C++ allows the first expression in a for loop to be a variable definition. In the above loop, for example,
i can be defined inside the loop itself:
Contrary to what may appear, the scope for i is not the body of the loop, but the loop itself. Scope-wise,
the above is equivalent to:
int i;
for (i = 1; i <= n; ++i)

- 25 - 2025
sum += i;
Example: Write C++ a program to find the sum of first n natural numbers where n is entered by
user. Note: 1, 2, 3... are called natural numbers.
# include <iostream.h>
int main()
{
int n, sum = 0;
cout<<"Enter the value of n "<<endl;
cin>>n;
for (int i = 1; i <= n; ++i)
sum += i;
cout<<" Sum of 1 to "<<n<<" natural number is "<<sum<<endl;
return 0;
}
Output of the above program look like the below

Any of the three expressions in a for loop may be empty. For example, removing the first and the third
expression gives us something identical to a while loop:
for (; i != 0;) // is equivalent to: while (i != 0)
something; //something;
Removing all the expressions gives us an infinite loop. This loop's condition is assumed to be always
true:
for (;;) // infinite loop
something;
For loops with multiple loop variables are not unusual. In such cases, the comma operator is used to
separate their expressions:
for (i = 0, j = 0; i + j < n; ++i, ++j)
something;

- 26 - 2025
Because loops are statements, they can appear inside other loops. In other words, loops can be nested.
For example,
Example: for nested loop
# include <iostream.h>
int main()
{
for (int i = 1; i <= 3; ++i)
for (int j = 1; j <= 3; ++j)
cout << '(' << i << ',' << j << ")\n";

return 0;
}
Produces the product of the set {1, 2, and 3} with itself, giving the output:

3.3.2 The ‘while’ Statement


The while statement (also called while loop) provides a way of repeating a statement while a condition
holds. It is one of the three flavors of iteration in C++.
The while loop checks whether the test expression is true or not. If it is true, code/s inside the body of
while loop is executed, that is, code/s inside the braces { } are executed. Then again the test expression
is checked whether test expression is true or not. This process continues until the test expression
becomes false.
Syntax of while loop
while (test expression) {
statement/s to be executed.
}
/*C++ program to demonstrate the working of while loop*/
#include <iostream.h>

- 27 - 2025
int main(){
int number, factorial;
cout<<"Enter a number.\n";
cin>>number;
factorial=1;
while (number>0){ /* while loop continues until test condition number>0 is true */
factorial=factorial*number;
--number;
}
cout<<"Factorial is " <<factorial;
return 0;
}
3.3.3 do...while loop
In C++, do...while loop is very similar to while loop. Only difference between these two loops is that,
in while loops, test expression is checked at first but, in do...while loop code is executed at first then
the condition is checked. So, the code are executed at least once in do...while loops.
Syntax of do...while loops
do {
some code/s;
}
while (test expression);
At first codes inside body of do is executed. Then, the test expression is checked. If it is true, code/s
inside body of do are executed again and the process continues until test expression becomes false
(zero).
Notice, there is semicolon in the end of while (); in do...while loop.
Example:-Write a C program to add all the numbers entered by a user until user enters 0.
/*C++ program to demonstrate the working of do...while statement*/
#include <iostream.h>
int main(){
int sum=0,num;
do /* Codes inside the body of do...while loops are at least executed once. */
{
cout<<"Enter a number\n";

- 28 - 2025
cin>>num;
sum+=num;
}
while(num!=0);
cout<<"sum="<<sum;
return 0;
}
The break Statement
In C ++ programming, break is used in terminating the loop immediately after it is encountered. The
break statement is used with conditional if statement. The break statement can be used in terminating
all three loops for, while and do...while loops.
Syntax of break statement
break;
/*C++ that Prints only numbers from 1 to 5 */
#include<iostream.h>
int main()
{
int i; Output: 1 2 3 4 5

for(i=1;i<10;i++)
{
cout<<i<<" \t";
if(i==5)
break; /*exit the loop*/
}
cout<<"\n";
return 0;
}
The continue Statement
It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements
are used. Use Continue to skip any loop code and continue the loop. Just like break, continue is also
used with conditional if statement.
Syntax of continue Statement
continue;

- 29 - 2025
/*Example. To demonstrate the use of continue statement in C++*/
#include<iostream.h>
void main(){
int i;
for(i=0;i<=10;i++){
if(i==5)
continue;
cout<<i<<"\t"; /*dispalys 1 ,2,3,4,6,7,8,9. It skips 5 and continue excuting the next value*/
}}
The goto statement
In C++ programming, goto statement is used for altering the normal sequence of program execution by
transferring control to some other part of the program. The goto statement provides the lowest-level of
jumping
Syntax of goto statement
goto label;
.............
label:
statement;
In this syntax, label is an identifier. When, the control of program reaches to goto statement, the
control of the program will jump to the label: and executes the code/s after it.
/Example:* C++ program to demonstrate the working of goto statement.*/
#include <iostream.h>
int main(){
float num,average,sum;
int i,n;
cout<<"Maximum no. of inputs: ";
cin>>n;
for(i=1;i<=n;++i){
cout<<"Enter n: "<<i<<" ";
cin>>num;
if(num<0.0)
goto jump; /* control of the program jumps to label jump */
sum=sum+num;

- 30 - 2025
}
cout<<"Sum: "<<sum;
jump:
average=sum/(i-1);
cout<<"\nAverage:"<<average;
return 0;
}
The return Statement
The return statement enables a function to return a value to its caller. It has the general form:
return expression;
where expression denotes the value returned by the function. The type of this value should match the
return type of the function. For a function whose return type is void, expression should be empty:
return;
The only function we have discussed so far is main, whose return type is always int. The return value of
main is what the program returns to the operating system when it completes its execution. Under
UNIX, for example, it its conventional to return 0 from main when the program executes without errors.
Otherwise, a non-zero error code is returned. For example:
int main (void)
{
cout << "Hello World\n";
return 0;
}
When a function has a non-void return value (as in the above example), failing to return a value will
result in a compiler warning. The actual return value will be undefined in this case (i.e., it will be
whatever value which happens to be in its corresponding memory location at the time).

- 31 - 2025
Chapter Four: Arrays, Strings and Pointers
4.1 C++ Programming Arrays
An array is a sequence of data item of homogeneous value (same type). i.e. the same data type and the
same name. Array is series of variable of the same name and type that hold multiple values in a
contiguous memory. An individual element of an array is identified by its own unique index (or
subscript). An array can be thought of as a collection of numbered boxes each containing one data
item. The number associated with the box is the index of the item. To access a particular item, the
index of the box associated with the item is used to access the appropriate box. The index must be an
integer and indicates the position of the element in the array. Thus the elements of an array are ordered
by the index. Arrays are of two types:
1. One-dimensional arrays:
2. Multidimensional arrays:
4.1.1 Declaration of one-dimensional array
An array declaration is very similar to a variable declaration. First a type is given for the elements of
the array, then an identifier for the array and, within square brackets, the number of elements in the
array. The number of elements must be an integer. To declare an array, we follow the following
syntax.
data_type array_name[array_size];
For example:
int age[5];
in the above array: int is data type, age is array name,5 is array size.
4.1.1.2 Array elements
Values in an array are called elements (members). Size of array defines the number of elements in an
array. Each element of array can be accessed by index (subscript) and used by user according to the
need of program. Every array value starts with index 0.
Example: int age[5]; //declares array named age with five elements of type integer. The size of array
age is 5 times the size of int because there are 5 elements.
NOTE: The elements field within square brackets [], representing the number of elements in the array,
must be a constant expression, since arrays are blocks of static memory whose size must be determined
at compile time, before the program runs.
It is best to make the array size a constant and then, if required, the program can be changed to handle
a different size of array by changing the value of the constant,
const int size = 10;
- 32 - 2025
int age[size];
then if more records come to light it is easy to amend the program to cope with more values by
changing the value of NE. This works because the compiler knows the value of the constant NE at
compile time and can allocate an appropriate amount of space for the array. It would not work if an
ordinary variable was used for the size in the array declaration since at compile time the compiler
would not know a value for it.
4.1.1.3 Accessing Array Elements
Given the declaration above of a 10-element array the compiler reserves space for 10 consecutive
integer values and accesses these values using an index/subscript that takes values from 0 to 9. The
first element in an array in C++ always has the index 0, and if the array has n elements the last element
will have the index n-1. An array element is accessed by writing the identifier of the array followed by
the subscript in square brackets. Thus, to set the 5th element of the array above to 25 the following
assignment is used:
age[5] = 25;
4.1.1.4 Initialization of one-dimensional array:
Arrays can be initialized at declaration time as the following example.
Example: int age[5]={2,4,5,3,4};
The first element is at index age[0]=2.
The second element is at index age[1]=4.
The third element is at index age[2]=5.
The fourth element is at index age[3]=3.
The fifth element is at index age[4]=4.
So the index of an array is array_size-1
It is not necessary to define the size of arrays during initialization.
Example: int age[]={2,4,5,3,4};
The number of values between braces {} shall not be greater than the number of elements in the array
(array size). If declared with less, the remaining elements are set to their default values (which for
fundamental types, means they are filled with zeroes.
Example: int age[5]={2,5,8}; Look like this in memory
2 5 8 0 0
Example of Array in C ++ Programming that shows how to access array.
/*to demonstrate array using index*/ Output
The first element of an array is 2
#include<iostream.h>
The second t element of an array is 4
The third element of an array is 5
- 33 - 2025
The fourth element of an array is 3
The fifth element of an array is 4
int main(){
int age[]={2,4,5,3,4};
cout<<" The first element of an array is "<<age[0]<<endl;
cout<<"The second element of an array is "<< age[1]<<endl;
cout<<"The third element of an array is "<< age[2]<<endl;
cout<<"The fourth element of an array is "<<age[3]<<endl;
cout<<"The fifth element of an array is "<<age[4]<<endl;
return 0;
}
/* C++ program to find the sum marks of n students using arrays */
#include <iostream>
using namespace std;
int main(){
int n, i; // n is the number of student ,in other case it is the size of an array.
float marks[100],sum=0;
cout<<"Please enter number of students: ";
cin>>n;
cout<<"Please enter marks of "<< n<< " students: "; Output
for(int i=0;i<n;++i){ Please enter number of students: 3
Please enter marks of 3 students: 85.5 90 68
cin>>marks[i]; The Sum of 3students mark is: 243.5
sum+=marks[i];
}//end of for loop
cout<<" The Sum of "<<n<< "students mark is: "<<sum<<endl;
return 0;
}//end of main function
C++ Programming Multidimensional Arrays
Multidimensional array is arrays of arrays
Example: float a[2][3];
a is an array of two dimension, which is an example of multidimensional array. This array has 2 rows
and 3 columns.
Initialization of Multidimensional Arrays
int c[2][3]={{1,3,0}, {-1,5,9}};
OR

- 34 - 2025
int c[][3]={{1,3,0}, {-1,5,9}};
OR
int c[2][3]={1,3,0,-1,5,9};
Example of Multidimensional Array in C++
Write a C++ program to find sum of two matrix of order 2*2 using multidimensional arrays
where, elements of matrix are entered by user.
#include <iostream.h>
int main(){
float a[2][2], b[2][2], c[2][2];
int i,j;
cout<<"Enter the elements of 1st matrix\n"<<endl;
/* Reading two dimensional Array with the help of two for loop. If there was an array of 'n' dimension,
'n' numbers of loops are needed for inserting data to array.*/
for(int i=0;i<2;i++)
for(int j=0;j<2;j++){
cin>>a[i][j]);
}
cout<"Enter the elements of 2nd matrix\n"<<endl;
for(i=0;i<2;++i)
for(j=0;j<2;++j){
cin>>b[i][j]);
}
for(i=0;i<2;++i)
for(j=0;j<2;++j){
/* Writing the elements of multidimensional array using loop. */
c[i][j]=a[i][j]+b[i][j]; /* Sum of corresponding elements of two arrays. */
}
cout<<"\nSum Of Matrix is :";
for(i=0;i<2;++i)
for(j=0;j<2;++j){
cout<<c[i][j];
if(j==1) /* To display matrix sum in order. */
cout<<endl;

- 35 - 2025
}
return 0;
}

Array of character
In C++ programming, array of character is called strings. A string is terminated by null character "\0" .
For example: "C++ string tutorial"
Here, "C++ string tutorial" is a string. When, compiler encounters strings, it appends null character at
the end of string
Declaration of array of character
Strings are declared in C++ in similar manner as arrays. Only difference is that, strings are of char type.
char s[5];
Initialization of strings
In C++, string can be initialized in different number of ways.
char c[]="abcd";
OR,
char c[5]="abcd";
OR,
char c[]={'a','b','c','d','\0'};
OR;
char c[5]={'a','b','c','d','\0'};
Reading Strings from user.
Reading words from user.
char c[20];
cin>>c;
String variable c can only take a word. It is because when white space is encountered, the cin function
terminates.
/* C++ program to illustrate how to read string from user.*/
#include<iostream.h>
int main(){
Output
char name[20]; Please enter name:
cout<<"Please enter name: "<<endl; Lalise Adugna
Your name is Lalise
cin>>name;

- 36 - 2025
cout<<"Your name is ” <<name<<endl;
return 0;
}
Here, program will ignore Adugna because, cin function takes only string before the white space.
There are predefined functions getline in C++ language to read and display string respectively. The
getline function has three actual arguments, two of which are required. The required size argument
refers to number of characters entered and the required string_variable_name argument is the name of
the string variable in which to store the input. The optional delimiter character argument to indicate the
string. The getline function will continue to read the characters entered at the keyboard until it
encounters the delimiter character.
This getline function reads white space.
/*C++ program to read characters using getline function without delimiters*/
#include<iostream.h> Output
int main(){ Please enter your name:
Lalise Adugna
char name[30]; Your name is: Lalise Adugna
cout<<" Please enter your name: "<<endl;
cin. getline (name,20); //Function to read string from user.
cout<<”Your name is :”<<name<<endl;
return 0;
}
/*C++ program to read characters using getline function with delimiters*/
#include<iostream.h> Output
int main(){ Please enter your name:
Lalise Adugna
char name[30]; Your name is: Lalise Adugna
cout<<" Please enter your name: "<<endl; Chala
cin. getline (name,20,'\0'); //Function to read characters from user with delimiters.
cout<<"Your name is :"<<name<<endl;
return 0;
}
String data type
String data type is not one of the fundamental data types in C++. Rather, it was added to the C++
language through the use of class called string class. The instructions for creating a string object, which
can be either a string variable or a string named constant, are contained in the string file.

- 37 - 2025
For a program to use the string class, it must contain the #include<cstring.h> library. Memory locations
having string data types are initialized using string literal constants. String constants is zero or more
characters enclosed inside double quotations.
String declaration and initialization using string data type
Syntax
string variable_name=" initial value";
Example1: string name=" "; //creates string variable named name & initializes it to empty string (" ")
Example2: string playAgain=" Y"; //declares a string variable named playAgain & initializes it to
string Y.
Example3:const string company_name= "Ambo University ";//declares a string named constant
// company_name & initializes it to empty string Ambo
University.
String Manipulations in C++ Programming Using Library Functions
C++ supports a large number of string handling functions
Strings handling functions are defined under "string.h" header file, i.e, you have to include the code
below to run string handling functions.
#include<string.h>
strlen():returns the length of the string not including the null character.
/*Example of string manipulation function "strlen"*/
#include<iostream.h>
#include<string.h>
int main() {
char string1[30]="C++ programming";
int len=strlen(string1);//*returns the number of characters in the string including the white space*/
cout<<"The length of the string1 is : "<<len<<endl;
return 0; Output
} The length of the string1 is 15.
strcpy():copies string to another string.
/*Example of string manipulation function "strcpy*/
#include<iostream.h>
#include<string.h>
int main(){
char string1[20]="MANCHESTER UNITED";

- 38 - 2025
char string2[20];
strcpy(string2,string1);//copies the value string1 to string2
cout<<"string2 is "<<string2<<endl; Output
return 0; String2 is MANCHESTER UNITED
}
strcat(): Concatenates(joins) two strings.
/*Example of string manipulation function “strcat*/
#include <iostream.h>
#include<string.h>
int main(){ Output
char string1[20]="MANCHESTER"; The concatenated string is MANCHESTER UNITED
char string2[20]=" UNITED";
strcat(string1,string2);// appends the value of string2 to string1
cout<<"The concatenated string is: "<<string1<<endl;
return 0;
}
strcmp(): compares the contents of string1 and string2 and returns a value indicating their relationship.
Return negative value (-ve) if string1 is greater than string2
Return 1 if string1 is less than string2
Return 0 if string1 is equal to string2
/*Example of string manipulation function “strcmp*/
#include <iostream..h>
#include<string.h>. Output
int main(){ Return Value is: -8

char string1[20]= "MANCHESTER ";


char string2[20]= "UNITED";
cout<<"Return Value is:"<<strcmp( string1, string2));
return 0;
}
/*Example of string manipulation function “strcmp*/
#include <iostream.h>
#include<string.h>. Output
Return Value is: 8
int main(){

- 39 - 2025
char string1[20]= " UNITED ";
char string2[20]= " MANCHESTER ";
cout<<"Return Value is :"<<strcmp( string1, string2));
return 0;
}
/*Example of string manipulation function “strcmp*/
#include <iostream.h>
#include<string.h>. Output
int main(){ Return Value is: 0
char string1[20]= "MANCHESTER UNITED";
char string2[20]= "MANCHESTER UNITED";;
cout<<"Return Value is :"<<strcmp( string1, string2));
return 0;
}
toupper():convert the given string to upper case letters.
toupper(string1);
tolower(string1);
tolower():convert the given string to lower case letters.
#include<iostream.h>
#include<string.h> //defines/include strlen
#include<ctype.h> //defines/include tupper and to lower in our program
int main()
{
char s1[]="hello world ";
char s2[]="AMBO UNIVERSITY ";
char s3[20] ;
int len=strlen(s1); //asssign the length of string s1 to len variable
for(int i=0;i<len;i++)
{
s3[i]=toupper(s1[i]); //convert the string s1 to upper case letters
cout<<s3[i];
} //end of for loop
cout<<endl;

- 40 - 2025
cout<<endl;
int length=strlen(s2);//asssign the length of string s2 to length variable
for( int j=0;j<length;j++)
{
s3[j]=tolower(s2[j]); //convert the string s1 to lower case letters
cout<<s3[j];
}//end of for loop
return 0;
} //end of main function
Output

strrev(): Reverses the given string.


strrev(string1);
example:
#include<iostream.h>
#include<string.h> //defines/include strrev
int main()
{
char s1[]="Ambo University ";
cout<<strrev(s1);
return 0;
} //end of main function
Output of the above code is

Pointer in C++
Pointer is a powerful part of C++.

- 41 - 2025
Pointer is a special type of variable, one that literally points to an address in memory of another
variable.
Standard Variables are labels used to identify small segments of memory set aside to hold data of a
particular type.
Standard Variables: holds a value, the value stored at an address in memory.
A pointer simply points to the segment of memory occupied by another variable.
A pointer: holds the address of another variable.
Declaring standard variable
Example: int j;
This set aside 4 bytes of memory and you are referring to that 4 bytes by a variable j.
Declaring a pointer is almost the same.
You must add asterisk (*) symbol to denote that it is a pointer.
You place asterisk immediately after the data type or before the variable.
Ex: int* k; OR int *k; //both declaration are valid
The asterisk (*) is called reference operator. - Is a reference to an address in a memory or “the
address pointed at by”.
The ampersand (&) operator denotes an address in memory. “Address of” operator.
Ex:- int j;
int *k; j i h
k=&j;
k
note: the pointer k represents the address of j;
/*To demonstrate on pointer*/
#include<iostream.h> Output
int main() The value of j is 10
The address of j is 0x251f2438
{ The address of k is 0x251f2438
int j; The value of k is 10
int *k;
k=&j;
j=10;
cout<<"The value of j is "<<j<<endl;
cout<<"The address of j is "<<&j<<endl;//address of the standard variable
cout<<"The address of k is "<<k<<endl;//k ponts to the address of j

- 42 - 2025
cout<<"The value of k is "<<*k<<endl; //k ponts to value of j
return 0;
}
Note: Pointer are typed. Means you tell the compiler what type of variable your pointer is pointing.
Ex: char c=’a’;
int *p=&c;
This code will generate an error, because you cannot use an int pointer to point to a variable of type
char.You must use a pointer of the same data type as the variable it is pointing.

Initializing pointers
The most common way is to set the pointer equal to the address of some standard variable. You can set
the pointer to equal to 0. Which is called Null Pointer
Null Pointer: is a pointer NOT pointing anywhere. It cannot point to any address in a memory
Ex: float *x=0;
Pointer Operations
To conduct arithmetical operations on pointers is somewhat different than to conduct operations on
other data types. You can use only addition (+), subtraction (-), increment (++) and decrement (--).You
cannot use multiplication and division on pointer.
/*pointer operation increment*/ Output
#include<iostream.h> The address of each array values are
0x24672406
int main(){ 0x24672408
int i[5]; 0x2467240a
0x2467240c
int *p; 0x246720e
p=i;
cout<<"The address of each array values are"<<endl;
for(int j=0;j<5;j++){
i[j]=j;
p++;
cout<<p<<endl;
}
return 0;
}

- 43 - 2025
C++ allowed you to point the pointer beyond the bound s of the array.
Pointer to pointers
C++ allows the use of pointers that point to another pointers.
A pointer to a pointer is called multiple indirection.
To create a pointer to a pointer, we only need to add an asterisk (*) for each level of reference.
Ex: /*to demonstrate pointer to pointer */
#include<iostream.h> Output
The value of x is 0x24d72460
int main(){ The value of y is 0x24d72460
char x; The value of z is 0x24d72460
The address of x is 3
char *y;
The address of y is 3
char **z; The address of z is 3
x='a';
y=&x;
z=&y;
cout<<"The value of x is "<<x<<endl;
cout<<"The value of y is "<<*y<<endl;
cout<<"The value of z is "<<**z<<endl;
cout<<"The address of x is "<<&x<<endl;
cout<<"The address of y is "<<y<<endl;
cout<<"The address of z is "<<*z<<endl;
return 0;
};

- 44 - 2025
Chapter 5
Function in C++
Function is a block of code segment that performs specific task.fucntion helps us to break down large
problems into different modules. Function is a sequence of statements designed to do a particular job.
You already know that every program must have a function named main(). However, most programs
have many functions, and they all work analogously to main function.
C++ program will be executing statements sequentially inside one function when it encounters a
function call. A function call is an expression that tells the CPU to interrupt the current function and
execute another function. The CPU “puts a bookmark” at the current point of execution, and then calls
(executes) the function named in the function call. When the called function terminates, the CPU goes
back to the point it bookmarked, and resumes execution.
Function is a collection of codes that is identified by name, returns a value and passes a list.
Requirements to write a function
1. Valid name which identifies the function
2. Return type: identifies the return data type of the function
3. Parameter lists: augments passed to function
4. Prototype: declaring a function
Parts of function
1. Declaration of function
This part tells the compiler that later in the program there is a function list.
Function declaration contains

- 45 - 2025
 Function return type: tells the compiler the data type the function can return.

 Function name: -tells the compiler the name of the function which is use in the program.
 Arguments: tells the number of parameters the function pass.
Ex: int add (int a,int b);
Each function declaration ends with semicolon (;).
For the above function: retruntype is int, which it returns integer value, add is function name and a
&b are function parameters of integer variables.
A function can have none, one or more parameter.
Parameters and arguments use interchangeable
2. Defining of function: - it performs the main operation. It the heart and soul of the function.
3. Ex: int add(int a,int b){
return a+b;
}
The above function definition, perform the sum of a & b and returns their sum.
Function definition enclosed inside curly braces {}.
4. Calling of function: -calls the function to start executing the code.
Ex: add(5,6);
Their at least one function in our program that is main function with none argument.
Any program start execution in main function, so function call is done or called inside main function.
Example:
/*C++ program that adds two numbers using function*/
#include<iostream.h>
int add(int a,int b);//function declaration
int main()
{
cout<<"The sum is "<<add(6,8);//function calling
return 0;
}
/*Function definition*/
int add(int a,int b) Output
The sum is 8
{
return a=b;

- 46 - 2025
}\
Ex2.
/*C++ program that accepts base and height from user input and calculates the
1.area of the rectangle
2.perimeter of the rectangle of type float*/
#include<iostream.h>
//function declaration
float area(int b,int h);
float perimeter(int b,int h);
float accept(int b,int h);
int main()
{
int base,height;
cout<<"Enter the base of the rectangle"<<endl;
cin>>base;
cout<<"Enter the height of the rectangle"<<endl;
cin>>height;
//function calling
cout<<"The area of a rectangle is "<<area(base,height)<<endl;
cout<<"The perimeter of a rectangle is "<<perimeter(base,height)<<endl;
return 0;
} Output
/*Function definition*/ Enter the base of the rectangle
5
float area(int a,int b){ Enter the height of the rectangle
float area; 6
The area of a rectangle is 30
area=a*b; The perimeter of a rectangle is 22
return area;
}
float perimeter(int a,int b){
float perm;
perm=2*(a+b);
return perm;
}

- 47 - 2025
Default argument: -are arguments which is initialized during function declaration. When you call a
function without passing value for that variable, it will access the default value which is given during
declaration.
Ex: /*C++ program that return the product of three float numbers*/
#include<iostream.h>
//function declaration
float product(float b,float h,float c=2.5);
int main() Output
The product is 30
{
//function calling
cout<<"The product is "<<product(5,6)<<endl;

return 0;
}
/*Function definition*/
float product(float a,float b,float c){
float prod;
prod=a*b*c;
return prod;
}
In the above example we only pass values 5 and 6 to the function calling. But the function have three
arguments, so for the third argument it uses the default value which is 2.5.
Pass by value to the function
Pass by value is direct copy of the content of one variable value to another variable. The above given
example on function default argument is best example of pass by value.
Ex: /*C++ program of simple calculator*/
#include<iostream.h>
#include<iomanip.h> //to include setw function to our program
//function declaration
double add(double num1,double num2);
double sub (double num1,double num2);
double mult(double num1,double num2);
double div(double num1,double num2);

- 48 - 2025
int main()
{
double num1,num2;
num1=8;
num2=6;
cout<<"sum "<<setw(20)<<"Difference"<<setw(20)<<"Product"<<setw(20)<<"quotient "<<endl;
cout<<add(num1,num2)<<setw(20)<<sub(num1,num2)<<setw(20)<<mult(num1,num2)<<setw(20)<<
div(num1,num2)<<endl;
// setw used to set wide space between each word or output
return 0;
}
double add(double num1,double num2){
return num1+num2;
}
double sub(double num1,double num2) Output
{ Sum difference product quotient
14 2 48 1.33333
return num1-num2; 14
}
double mult(double num1,double num2)
{
return num1*num2;
}
double div(double num1,double num2)
{
return num1/num2;
}
Function overloading
Function overloading is a function with the same name, but different types and different number of
arguments.
Ex:
/*C++ program that calculates the square of different data types*/
#include<iostream.h>
int square(int num); //function declaration of type int Output
The square of a number is 6.25
- 49 - 2025
The square of a number is 25
double square (double num); //function declaration of type double
int main()
{ //function calling
cout<<"The square of a number is "<<square(2.5)<<endl;/*calls function(square) which is defined
using double data type.*/
cout<<"The square of a number is "<<square(5)<<endl; /*calls function (square)which is defined
using int data type.*/
return 0;
}
int square(int num){
int sqr;
sqr=num*num;
return sqr;
}
double square (double num){
double sqr;
sqr=num*num;
return sqr;
}
In the above example, two function having the same name (square) but they differ in data types. The
first function passes int type and the second passes double type.
Pass function by reference
When you pass reference, you cannot copy the content one variable to another variable. Instead you
can copy the address of one variable to another variable.
Ex: /*pass by refernce to a function*/
#include<iostream.h>
void number( int &num);
int main()
{
int num;
cout<<"Enter a number "<<endl;
cin>>num;
cout<<"Before change your number is "<<num<<endl; Output
Enter a number
- 50 - 3 2025
Before change your number is 3
Inside the number function your
number is 15
number(num);
return 0;
}
void number(int &num) {
num=num*5;
cout<<"Inside the number function your number is "<<num<<endl;
cout<<"After change your number is "<<num<<endl;
}
Math library functions: math libraries like sqrt(),sin(),cos(),tan(),pow are defined inside a library
called math.h. So to include or use the above listed libraries you must include the header file
#include<math.h> in your program.
Example:
#include<iostream.h>
#include<math.h> // defines math library functions
int main(){
double num1=4,num2=2;
cout<<"The square root of num1 is "<<sqrt(num1)<<endl; //sqrt define inside math.h
cout<<"The sine of num1 is "<<sin(num1)<<endl; //sin define inside math.h
cout<<"The cossine of num1 is "<<cos(num1)<<endl; //cos define inside math.h
cout<<"The tangent of num1 is "<<tan(num1)<<endl; //tan define inside math.h
cout<<"The 4 raised to the power of 2 is "<<pow(num1,num2)<<endl; //pow define inside math.h
return 0;
}
Ouput of the above program is as shown below:

- 51 - 2025
- 52 - 2025

You might also like