0% found this document useful (0 votes)
19 views61 pages

Unit 2 Part 1

The document provides an overview of the basics of C++ programming, including its character set, tokens, identifiers, keywords, data types, variables, literals, and operators. It emphasizes C++ as a superset of C, highlighting its object-oriented features and the rules for naming identifiers and variables. Additionally, it details various types of operators such as arithmetic, relational, logical, bitwise, assignment, and miscellaneous operators used in C++.

Uploaded by

soham patil
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)
19 views61 pages

Unit 2 Part 1

The document provides an overview of the basics of C++ programming, including its character set, tokens, identifiers, keywords, data types, variables, literals, and operators. It emphasizes C++ as a superset of C, highlighting its object-oriented features and the rules for naming identifiers and variables. Additionally, it details various types of operators such as arithmetic, relational, logical, bitwise, assignment, and miscellaneous operators used in C++.

Uploaded by

soham patil
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/ 61

Unit 2

Beginning with C++:


• Tokens
• Expressions
• Control Structures
• Array
• Functions
• Structures
• Unions and pointers
• String Manipulation
Notes prepared by Prof. Anushree K. Rewale 45
Basics of C++
• C++ is a superset of C language. It contains the syntax and features of C language. The object-
oriented feature in C++ is helpful in developing the large programs with clarity, extensibility
and easy to maintain the software after sale to customers. It is helpful to map the real-world
problem properly. C++ has replaced C programming language and is the basic building block of
current programming languages such as Java, C# and .Net etc.
• C++ Character Set
• Character set is a set of valid characters that a language can recognize. The character set of C++ is
consisting of letters, digits, and special characters. The C++ has the following character set:
Letters (Alphabets) A-Z, a-z
Digits 0-9
Special Characters #, <=, >=, @ ,+, -, *, /, ^, \, ( ), [ ], { }, =, !, < >. „, “, $, ;, :, % , &, ?, _

• There are 62 letters and digits character set in C++ (26 Capital Letters + 26 Small Letters + 10
Digits) as shown above. Further, C++ is a case sensitive language, i.e. the letter A and a, are distinct
in C++ object oriented programming language. There are 29, punctuation and special character set in
C++ and is used for various purposes during programming.
Notes prepared by Prof. Anushree K. Rewale 46
• White Spaces Characters
• A character that is used to produce blank space when printed in C++ is called white space character.
These are spaces, tabs, new-lines, and comments.
• Tokens
• A token is a group of characters that logically combine together. The programmer can write a
program by using tokens. C++ uses the following types of tokens:
• Keywords
• Identifiers
• Literals
• Punctuators
• Operators

Notes prepared by Prof. Anushree K. Rewale 47


• Identifier
• In C++ programming language, identifiers are the unique names assigned to variables, functions, classes,
structs, or other entities within the program. For example, int num = 11; (num is an identifier.)
• Rules to Name of an Identifier in C++
• We can use any word as an identifier as long as it follows the following rules:
• An identifier can consist of letters (A-Z or a-z), digits (0-9), and underscores (_). Special characters and spaces are not
allowed.
• An identifier can only begin with a letter or an underscore only.
• C++ has reserved keywords that cannot be used as identifiers since they have predefined meanings in the language.
For example, int cannot be used as an identifier as it has already some predefined meaning in C++. Attempting to use
these as identifiers will result in a compilation error.
• Identifier must be unique in its namespace.
• Additionally, C++ is a case-sensitive language so the identifier such as Num and num are treated as different.

Notes prepared by Prof. Anushree K. Rewale 48


• Keywords
• There are some reserved words in C++ which have predefined meaning to complier called keywords.
These are also known as reserved words and are always written or typed in lower cases. There are
following keywords in C++ object oriented language.
• List of Keywords:
asm case class void double extern friend
return inline switch try unsigned sizeof auto
else float goto delete operator public short
virtual static break char continue while enum
private register signed long this union struct
default new protected catch const volatile int
template typedef for if do

Notes prepared by Prof. Anushree K. Rewale 49


• Data Types in C++:
• Every name (identifier) in a C++ program has a type associated with it. This type determines what
operations can be applied to the name (that is, to the entity referred to by the name) and how such
operations are interpreted. For example, the declarations
• float x; //x is a floating-point variable
• int y = 7; //y is an integer variable with the initial value 7
• would make the example meaningful.
• Data types in Standard C++ are classified as shown in the diagram below.

Notes prepared by Prof. Anushree K. Rewale 50


Notes prepared by Prof. Anushree K. Rewale 51
• The following table shows the data 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.
Type Typical Bit Width Typical Range
char 1byte -127 to 127 or 0 to 255
unsigned char 1byte 0 to 255
signed char 1byte -127 to 127
int 4bytes -2147483648 to 2147483647
unsigned int 4bytes 0 to 4294967295
signed int 4bytes -2147483648 to 2147483647
short int 2bytes -32768 to 32767
unsigned short int 2bytes 0 to 65,535
signed short int 2bytes -32768 to 32767
long int 8bytes -9223372036854775808 to 9223372036854775807
signed long int 8bytes same as long int
unsigned long int 8bytes 0 to 18446744073709551615
float 4bytes 3.4E – 38 to 3.4E +38
double 8bytes 1.7E – 308 to 1.7E + 308
long double 12bytes Notes prepared by Prof. Anushree K.3.4E – 4932 to 1.1E + 4932
Rewale 52
• Variables
• Variables are used to give a name to a memory location that holds a value. Hence, a variable is also
an identifier. The names of variables are different which cannot be a keyword. Also, the value stored
in a variable can be modified during the execution of the program. The general form of variable
declaration is :
data type variable [list];
• Here list denotes more than one variable separated by commas;
• Example :
int a;
float b, c;
char p, q;
• The rule for writing variables are same as for writing identifiers as a variables is nothing but an
identifier. C++ allows you to declare variables anywhere in the program.

• Literals or Constants
• A number which does not charge its value during execution of a program is known as a constant or
literals. Any attempt to change the value of a constant will result in an error message. A keyword
const is added to the declaration of an identifier to make that identifier constant. A constant in C++
can be of any of the basic data types. Let us consider the following C++ expression:
const float Pi = 3.1215;
• The above declaration means that PiNotes
is prepared
a constant of float
by Prof. Anushree types having a value: 3.1415.
K. Rewale 53
• Operators in C++
• An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provide the following types of operators:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators

Notes prepared by Prof. Anushree K. Rewale 54


• Arithmetic Operators
• There are following arithmetic operators supported by C++ language.
• Assume variable A holds 10 and variable B holds 20, then –
Operator Description Example
+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200

/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after an integer division B % A will give 0

++ Increment operator, increases integer value by one A++ will give 11

-- Decrement operator, decreases integer value by one A-- will give 9

Notes prepared by Prof. Anushree K. Rewale 55


• Relational Operators
• There are following relational operators supported by C++ language
• Assume variable A holds 10 and variable B holds 20, then –
Operator Description Example
Checks if the values of two operands are equal or not, if yes
== then condition becomes true.
(A == B) is not true.

Checks if the values of two operands are equal or not, if


!= values are not equal then condition becomes true.
(A != B) is true.

Checks if the value of left operand is greater than the value


> of right operand, if yes then condition becomes true.
(A > B) is not true.

Checks if the value of left operand is less than the value


< of right operand, if yes then condition becomes true.
(A < B) is true.

Checks if the value of left operand is greater than or equal to


>= the value of right operand, if yes then condition becomes true.
(A >= B) is not true.

Checks if the value of left operand is less than or equal to the


<= value of right operand, if yes then condition becomes true.
(A <= B) is true.

Notes prepared by Prof. Anushree K. Rewale 56


• Logical Operators
• There are following logical operators supported by C++ language.
• Assume variable A holds 1 and variable B holds 0, then –
Operator Description Example
Called Logical AND operator. If both the operands are non-
&& zero, then condition becomes true.
(A && B) is false.

Called Logical OR Operator. If any of the two operands is


|| non-zero, then condition becomes true.
(A || B) is true.

Called Logical NOT Operator. Use to reverses the logical


! state of its operand. If a condition is true, then Logical NOT !(A && B) is true.
operator will make false.

Notes prepared by Prof. Anushree K. Rewale 57


• Bitwise Operators
• Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are
as follows –
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
• Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
---------------------
A & B = 0000 1100
A | B = 0011 1101
A ^ B = 0011 0001
~A = 1100 0011

Notes prepared by Prof. Anushree K. Rewale 58


• The Bitwise operators supported by C++ language are listed in the following table.
• Assume variable A holds 60 and variable B holds 13, then –
Operator Description Example
Binary AND Operator copies a bit to the result if it exists in (A & B) will give 12
& both operands. which is 0000 1100.
(A | B) will give 61
| Binary OR Operator copies a bit if it exists in either operand.
which is 0011 1101.
Binary XOR Operator copies the bit if it is set in one operand (A ^ B) will give 49
^ but not both. which is 0011 0001.
(~A ) will give -61 which
Binary Ones Complement Operator is unary and has the effect is 1100 0011 in 2’s
~ of ‘flipping’ bits. complement form due to
a signed binary number.
Binary Left Shift Operator. The left operands value is moved A << 2 will give 240
<< left by the number of bits specified by the right operand. which is 1111 0000.
Binary Right Shift Operator. The left operands value is moved A >> 2 will give 15
>> right by the number of bits specified by the right operand. which is 0000 1111.
Notes prepared by Prof. Anushree K. Rewale 59
• Assignment Operators
• There are following assignment operators supported by C++ language –
Operator Description Example
Simple assignment operator, Assigns values from right side C = A + B will assign
= operands to left side operand. value of A + B into C
Add AND assignment operator, It adds right operand to the C += A is equivalent to
+= left operand and assign the result to left operand. C=C+A
Subtract AND assignment operator, It subtracts right operand C -= A is equivalent to
-= from the left operand and assign the result to left operand. C =C-A
Multiply AND assignment operator It multiplies right operand C *= A is equivalent to
*= with the left operand and assign the result to left operand. C=C*A
Divide AND assignment operator It divides right operand C /= A is equivalent to
/= with the left operand and assign the result to left operand. C=C/A
Modulus AND assignment operator It takes modulus using C %= A is equivalent to
%= two operands and assign the result to left operand. C=C%A
C <<= 2 is same as
<<= Left shift AND assignment operator.
C = C<< 260
Notes prepared by Prof. Anushree K. Rewale
C >>= 2 is same as
>>= Right shift AND assignment operator.
C = C>> 2
C &= 2 is same as
&= Bitwise AND assignment operator.
C=C&2
C ^= 2 is same as
^= Bitwise exclusive OR and assignment operator.
C=C^2
C |= 2 is same as
|= Bitwise inclusive OR and assignment operator.
C=C|2

Notes prepared by Prof. Anushree K. Rewale 61


• Misc Operators
• The following table lists some other operators that C++ supports.
Operator Description
sizeof operator returns the size of a variable. For example, sizeof(a), where 'a' is integer,
sizeof
and will return 4.
Conditional operator (?). If Condition is true then it returns value of X otherwise returns
Condition ? X : Y
value of Y.
Comma operator causes a sequence of operations to be performed. The value of the
,
entire comma expression is the value of the last expression of the comma-separated list.
Member operators are used to reference individual members of classes, structures, and
. (dot) and -> (arrow)
unions
Casting operators convert one data type to another. For example, int(2.2000) would
Cast
return 2.
Pointer operator & returns the address of a variable. For example &a; will give actual
&
address of the variable.
Pointer operator * is pointer to a variable. For example *var; will pointer to a variable
*
var.

Notes prepared by Prof. Anushree K. Rewale 62


• Expressions:
• An expression is a formula in which operands are linked to each other by the use of operators to
compute a value. An operand can be a function reference, a variable, an array element or a constant.
• Let's see an example: a-b;
In the above expression, minus character (-) is an operator, and a, and b are the two operands.
• For example: x = 9/2 + a-b;
The entire above line is a statement, not an expression. The portion after the equal is an expression.

• Comments:
• A comment is text that the compiler ignores but that is useful for programmers. Comments can be
used to explain C++ code, and to make it more readable. The compiler treats them as white space.
• Comments can be singled-lined or multi-lined.
• Single-line Comments : In C++ Single line comments are represented as // double forward slash. It
applies comments to a single line only. The compiler ignores any text after // and it will not be executed.

• Multi-Line Comment : A multi-line comment can occupy many lines of code, it starts with /* and ends
with */, but it cannot be nested. Any text between /* and */ will be ignored by the compiler.

Notes prepared by Prof. Anushree K. Rewale 63


Notes prepared by Prof. Anushree K. Rewale 64
• Output Operator:
• The standard output device is the screen (Monitor). Outputting in C++ is done by using the object
followed by the “stream insertion” (<<). cout stands for console output.
• Example: cout<<"Hello World";
• The << operator inserts the data that follows it into the stream preceding it. The sentence in the
instruction is enclosed between double quotes ( " ), because it is constant string of characters.
• Example:
• cout<<"sum"; //prints sum word
• cout<<sum; //prints the content of the variable sum

• The iostream File:


• iostream stands for standard input-output stream. #include<iostream> is a keyword used to include
the iostream header file. The iostream header file contains all the functions used for reading and
writing operations like cin and cout. This statement is placed at the beginning of the C++ program,
before the "main" function, to make the "iostream" library available for use in the program. Streams
are an essential part of the C++ input/output library and provide a convenient and flexible way to
handle input and output operations in C++ programs.

Notes prepared by Prof. Anushree K. Rewale 65


• Namespace:
• Namespaces in C++ are used to organize too many classes so that it can be easy to handle the application.
• For accessing the class of a namespace, we need to use namespacename::classname. We can use using keyword
so that we don't have to use complete name all the time. In C++, global namespace is the root namespace. The
global::std will always refer to the namespace "std" of C++ Framework.

• Retun type of main():


• In C/C++ the default return type of the main function is int, i.e. main() will return an integer value by default.
The return value of the main tells the status of the execution of the program. The main() function returns 0 after
the successful execution of the program otherwise it returns a non-zero value.
• Using void main in C/C++ is considered non-standard and incorrect. void main() in C/C++ has no
defined(legit) usage, and it can behave unexpectedly or sometimes throw garbage results or an error.

• Input Operator:
• Usually the input device in a computer is the keyboard. C++ cin statement used to read input from
the standard input device which is usually a keyboard.
• The extraction operator(>>) is used along with the object cin for reading inputs. The extraction
operator extracts the data from the object cin which is entered using the keyboard.
• Example: cin>>a;
Notes prepared by Prof. Anushree K. Rewale 66
Control Structure in C++
• The execution of statements in a program by default is sequential. But sometimes there are such
situations where the problem statement and the program logic demands that the program execution or
flow be directed or branched to a particular set of statements rather than the other.
• Ex. Finding greater of 2 given numbers.
• This kind of situation involves decision making. C++ offers the following decision control structures:

Notes prepared by Prof. Anushree K. Rewale 67


• Sequence Structure
• This is the most simple and basic form of a control structure. It is simply the plain logic we
write; it only has simple linear instructions, no decision making, and no loop. The programs
we all wrote at the start of our programming journey were this control structure only. It
executes linearly line by line in a straight line manner.
• Selection Structure
• Sometimes in our program, we will need to write certain condition checks that this part of
code should only execute if a particular condition meets or another part of code should run.
• For example: The example we took at the start is that we have to write a program that will
validate if a user is eligible to drive or not based on two conditions:
• if the age is equal to or above 18
• if the user has their driving license
• Loop Structure
• Whenever in our program we see that a certain piece of code is being repeated repeatedly,
then we can enclose that in a loop structure and provide the condition that this code should
execute these specific number of times. Taking the above example, suppose we are asked to
write a program that will print "Hello World" 1000 times.
Notes prepared by Prof. Anushree K. Rewale 68
• if : Flowchart of if condition
• if statement is used for branching when a single condition is to
be checked. The condition enclosed in if statement decides the
sequence of execution of instruction. If the condition is true,
the statements inside if statement are executed, otherwise they
are skipped.
• Syntax:
if (condition)
{
// code to be executed if the condition is true
}
• Example
#include<iostream>
int main()
{
int a;
cout<<"enter the value of a: ";
cin>>a;
if(a==3) {
cout<<"A equals to 3";
}
return 0;
} Notes prepared by Prof. Anushree K. Rewale 69
• if – else: Flowchart of if – else condition
• if ... else statement is a two way branching statement. It
consists of two blocks of statements each enclosed inside
if block and else block respectively. If the condition
inside if statement is true, statements inside if block are
executed, otherwise statements inside else block are
executed. Else block is optional and it may be absent in a
program.
• Syntax:

if (condition)

//code to be executed if the condition is true

else

//code to be executed if the condition is false

} Notes prepared by Prof. Anushree K. Rewale 70


• Example:
# include <iostream>
int main()
{
int a, b;
a=10;
b=20;
if (a<b)
{
cout <<"a is less than b";
}
else
{
cout<< "b is less than a";
}
return 0;
}

Notes prepared by Prof. Anushree K. Rewale 71


• nested if – else:
• Nested if-else statements are those statements in which there is an if statement inside another if else. We use
nested if-else statements when we want to implement multilayer conditions(condition inside the condition
inside the condition and so on). C++ allows any number of nesting levels.
• Syntax:
if(condition1) if(condition1) if(condition1)
{
{ { if(condition2)
if(condition2) // Code to be executed {
// Code to be executed
{ } }
// Code to be executed else else
{
} { // Code to be executed
else if(condition2) }
{ { }
else
// Code to be executed // Code to be executed {
} } if(condition3)
{
} else // Code to be executed
else { }
else
{ // Code to be executed {
// code to be executed } // Code to be executed
} } }
}
Notes prepared by Prof. Anushree K. Rewale 72
Notes prepared by Prof. Anushree K. Rewale 73
• Example:
#include <include>
int main()
{
int i = 10;
if (i == 10)
{
if (i < 15)
{
printf("i is smaller than 15\n");
if (i < 12)
{
printf("i is smaller than 12 too\n");
}
}
}
else
{
printf("i is greater than 15");
}
return 0;
} Notes prepared by Prof. Anushree K. Rewale 74
• else – if Ladder:
• The if-else-if ladder statement is an extension to the if-else statement. It is used in the scenario where there are
multiple cases to be performed for different conditions. In if-else-if ladder statement, if a condition is true then the
statements defined in the if block will be executed, otherwise if some other condition is true then the statements
defined in the else-if block will be executed, at the last if none of the condition is true then the statements defined in
the else block will be executed. There are multiple else-if blocks possible.
• Syntax:
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
else
{
//code to be executed if all the conditions are false
} Notes prepared by Prof. Anushree K. Rewale 75
Notes prepared by Prof. Anushree K. Rewale 76
• Example:
#include<iostream>
int main() {
int number=0;
cout<<"enter a number: ";
cin>>number;
if(number==10) {
cout<<"number is equals to 10“;
}
else if(number==50) {
cout<<"number is equal to 50";
}
else if(number==100) {
cout<<"number is equal to 100";
}
else {
cout<<"number is not equal to 10, 50 or 100";
}
return 0;
} Notes prepared by Prof. Anushree K. Rewale 77
• Conditional 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.
• 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.

• The above statement of the ternary operator is equivalent to the if-else statement given below:
if ( condition ) {
statement1;
}
else {
statement2;
}
Notes prepared by Prof. Anushree K. Rewale 78
• Example of Ternary Operator in C++
#include <iostream>
using namespace std;
int main()
{
int num, test = 40;
num = test < 10 ? 10 : test + 10;
cout<<"Num – Test : "<< num - test;
return 0;
}

Notes prepared by Prof. Anushree K. Rewale 79


• Switch Statement:
• Switch case in C++ are control statements that can be used instead of if-else statements. The switch
also helps us avoid the complex if-else ladder and makes the code easier to understand and modify
for further use.
• A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each case.
• Syntax:
switch (expression)
{
case constant1:
// code to be executed if
// expression is equal to constant1;
break;

case constant2:
// code to be executed if
// expression is equal to constant2;
break;
.
.
.
default:
// code to be executed if
// expression doesn't match any constant
} Notes prepared by Prof. Anushree K. Rewale 80
• How does the switch statement work?
• The expression is evaluated once and compared with the values of each case
label.
• If there is a match, the corresponding code after the matching label is executed. For
example, if the value of the variable is equal to constant2, the code after case constant2:
is executed until the break statement is encountered.

• If there is no match, the code after default: is executed.

Notes prepared by Prof. Anushree K. Rewale 81


• Flowchart of Switch Statement

Notes prepared by Prof. Anushree K. Rewale 82


• Example:
#include <iostream>
using namespace std;
int main() {
int choice;
cout << "Choose an option:" << endl;
cout << "1. Print 'Hello'" << endl;
cout << "2. Print 'Goodbye'" << endl;
cout << "3. Print 'See you later'" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Hello!" << endl;
break;
case 2:
cout << "Goodbye!" << endl;
Notes prepared by Prof. Anushree K. Rewale

break;
case 3:
cout << "See you later!" << endl;
break;
default:
cout << "Invalid choice!" << endl;
break;
}
return 0;
83

}
Looping Structure in C++
• In Programming, sometimes there is a need to perform some operation more than once or (say)
n number of times. Loops come into use when we need to repeatedly execute a block of
statements. Looping structure allows to execute a statement or group of statements multiple
times.
• For example: Suppose we want to print “Hello World” 10 times. This can be done in two ways
as shown below:
• Manual Method: Manually we have to write cout for the C++ statement 10 times. Let’s say you
have to write it 20 times (it would surely take more time to write 20 statements) now imagine you
have to write it 100 times, it would be really hectic to re-write the same statement again and again.
So, here loops have their role.

• Using Loops: In Loop, the statement needs to be written only once and the loop will be executed 10
times as shown below. In computer programming, a loop is a sequence of instructions that is
repeated until a certain condition is reached. In other words, C++ Loops are used to execute the same
block of code a specified number of times or while a specified condition is true.
• In C++ there are mainly three different kinds of loops:
• for Loop
• while Loop
• do – while Loop Notes prepared by Prof. Anushree K. Rewale 84
Manual Method Looping Method

#include <iostream> #include <iostream>


using namespace std; using namespace std;
int main() int main()
{ {
cout << "Hello World\n"; for (int i = 1; i <= 10; i++)
cout << "Hello World\n"; {
cout << "Hello World\n"; cout << "Hello World\n";
cout << "Hello World\n"; }
cout << "Hello World\n";
cout << "Hello World\n"; return 0;
cout << "Hello World\n"; }
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
return 0;
}
Notes prepared by Prof. Anushree K. Rewale 85
• for Loop:
• Loop is an entry-controlled loop, meaning that the condition specified by us is verified before entering
the loop block. It is a repetition control structure. The loop written by us is run a specified number of
times.
• To control the loop, we use a loop variable in For loop. This variable is first initialized to some value,
then we perform the check on this variable, comparing it to the counter variable, and finally, we update
the loop variable.
• Syntax:
for(initialization expression ; test expression ; update expression)
{
// statements to execute in the loop body
}

• Initialization Expression: Here we initialize the loop variable to a particular value. For example, int
i=1;
• Test Expression: Here, we write the test condition. If the condition is met and returns true, we execute
the loop body and update the loop variable. Otherwise, we exit the For loop. An example for test
expression is i <= 5;
• Update Expression: Once the body of the loop has been executed, we increment or decrement the
value of the loop variable in the update
Notes expression. For K.example,
prepared by Prof. Anushree Rewale i++; 86
• Flowchart of for Loop:

Notes prepared by Prof. Anushree K. Rewale 87


• Example:
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; i++)
{
cout << " Good morning \n";
}
return 0;
}

Notes prepared by Prof. Anushree K. Rewale 88


• while Loop:
• While the loop is also an entry controlled loop, we verify the condition specified before running the loop. The
difference is that we use For loops when we know the number of times the body of the loop needs to run,
whereas we use while loops in circumstances when beforehand we do not know the precise number of times
the body of the loop needs to run. The execution of the loop is terminated based on the test condition.

• Syntax:

while (test_expression)

// statements to execute in the loop body

update_expression;

The syntax of the loops differs only in the placement of the three expression statements.

Notes prepared by Prof. Anushree K. Rewale 89


• Flowchart of while Loop:

Notes prepared by Prof. Anushree K. Rewale 90


• Let us look at an example of while loop:
#include <iostream>
using namespace std;
int main()
{
int i = 0; // initialization expression
while (i < 5) // test expression
{
cout << "Good morning\n";
i++; // update expression
}
return 0;
}

Notes prepared by Prof. Anushree K. Rewale 91


• do – while Loop:
• Do while loop is an exit controlled loop meaning the test condition is verified after the execution of the loop, at
the end of the body of the loop. Hence, the body executes at least once, regardless of the test condition,
whether it is true or false. In a while loop, the condition is tested beforehand, whereas in a do loop, the
condition is verified at the finish of the loop’s body.
• Syntax:
initialization expression;
do
{
// statements to execute in the loop body
update_expression;
} while (test_expression);
In do while loop, we end the body of the loop with a semicolon, whereas the other two loops do not have any
semicolon to end the body of their loops. Notes prepared by Prof. Anushree K. Rewale 92
• Flowchart of do – while Loop:

Notes prepared by Prof. Anushree K. Rewale 93


• Example:
#include <iostream>
using namespace std;
int main()
{
int i = 2; // initialization expression
do
{
cout << " Good morning\n";
i++; // update expression
} while (i < 1); // test expression
return 0;
} Notes prepared by Prof. Anushree K. Rewale 94
• Nested Loop:
• A loop within another loop is called a nested loop. Let's take an example,
• Suppose we want to loop through each day of a week for 3 weeks. To achieve this, we can create a loop to iterate
three times (3 weeks). And inside the loop, we can create another loop to iterate 7 times (7 days). This is how we can
use nested loops.
• Example:
#include <iostream>
using namespace std;
int main()
{
int weeks = 3, days_in_week = 7;
for (int i = 1; i <= weeks; ++i)
{
cout << "Week: " << i << endl;
for (int j = 1; j <= days_in_week; ++j)
{
cout << " Day: " << j << endl;
}
}
return 0;
} Notes prepared by Prof. Anushree K. Rewale 95
• Example: Displaying a Pattern
// C++ program to display a pattern with 5 rows and 3 columns
#include <iostream>
using namespace std;
int main()
{
int rows = 5;
int columns = 3;
for (int i = 1; i <= rows; ++i)
{
for (int j = 1; j <= columns; ++j)
{
cout << "* ";
}
cout << endl;
}

return 0;
}
Notes prepared by Prof. Anushree K. Rewale 96
• Jump Statement in C++:
• In C, jump statements control the program's flow by transferring execution to various code sections, which is
essential for managing loops, switch cases, and functions. They include types like goto, break, and continue.

• Break Statement:
• If the condition is true, the loop is terminated with the break command. When the condition is met, the loop is
broken and the remainder of the loop is skipped. Break statements are used in conjunction with decision-
making statements such as if, if-else, or switch statements in a for loop, which can be a for loop, while loop, or
do-while loop. It causes the loop to stop executing future iterations.
• The diagram below will give you more clarity on how the break statement works.
• The switch case consists of a conditional statement. According to that conditional statement, it has cases. The
break statement is present inside every case.

• Syntax:
//specific condition
break; Notes prepared by Prof. Anushree K. Rewale 97
• Flowchart

Notes prepared by Prof. Anushree K. Rewale 98


• Example:
#include<iostream>
Using namespace std;
int main()
{
for(a =1 ; a <= 10 ; a++) // run loop unless the value is 10
{
if (a == 3) // if the value is 3
{
break; //break the loop
}
cout<<"Print = "<< a;
}
printf("Outside loop"); //print statement outside the loop
return 0;
} Notes prepared by Prof. Anushree K. Rewale 99
• Continue Statement:
• Continue in jump statement in C skips the specific iteration in the loop. It is similar to the break
statement, but instead of terminating the whole loop, it skips the current iteration and continues from
the next iteration in the same loop. It brings the control of a program to the beginning of the loop.

• Using the continue statement in the nested loop skips the inner loop's iteration only and doesn't affect
the outer loop.

• Syntax:

continue; Notes prepared by Prof. Anushree K. Rewale 100


• Flowchart of continue statement:

Notes prepared by Prof. Anushree K. Rewale 101


• Example:
#include<iostream>
Using namespace std;
int main()
{
for(a =1 ; a <= 10 ; a++) // run loop unless the value is 10
{
if (a == 3) // if the value is 3
{
continue; //break the loop
}
cout<<"Print = "<< a;
}
printf("Outside loop"); //print statement outside the loop
return 0;
} Notes prepared by Prof. Anushree K. Rewale 102
• goto Statement:
• Goto statement is somewhat similar to the continue statement in the jump statement in C, but the continue
statement can only be used in loops, whereas Goto can be used anywhere in the program, but what the continue
statement does it skips the current iteration of the loop and goes to the next iteration, but in the goto statement
we can specify where the program control should go after skipping.
• The concept of label is used in this statement to tell the program control where to go. The jump in the program
that goto take is within the same function.
• Below is the diagram; the label is XYZ, and it will be more clear when we'll see the syntax.

• Syntax:
goto label;
.
.
label:
--code--
--code-- Notes prepared by Prof. Anushree K. Rewale 103
• Flowchart of goto Statement:

Notes prepared by Prof. Anushree K. Rewale 104


• Example:
#include<iostream>
using namespace std;
int main()
{
int a;
cout<<"\nEnter a Positive int: ";
cin>>a;
if (a % 2 == 0) //logic of even no
goto Even; //goto statement 1
else
goto Odd; //goto statement 2

Even: // label 1
cout<<"Number is Even\n");
exit(0);

Odd: //label2
cout<<"Number is Odd\n";
return 0;
} Notes prepared by Prof. Anushree K. Rewale 105

You might also like