SlideShare a Scribd company logo
CONTROL
STRUCTURES-2
AFTER THIS LESSON, LEARNERS
WILL BE ABLE TO:
• Understand the concept and usage of selection and iteration statements.
• Know various types of control structures available in C++.
• Analyze the problem, decide and evaluate conditions.
• To analyze and choose an appropriate combination of constructs to solve a
particular problem
• Write code that employ decision structures, including those that employ
sequences of decision and nested decisions.
• Design simple applications having iterative nature.
FLOW OF CONTROL
AND CONTROL STRUCTURES
The order in which a set of statements are executed in a program is
known as its flow of control
Generally the flow of control is sequential.
 However at times it is required to change this sequential flow so
that only a particular statement or group of statements are
executed.
This is achieved by control structures .
Control structures are statements that upon execution
alter or control the sequence of execution of statements in
a program.
TYPES OF CONTROL STRUCTURES
These can be categorized into the following categories:
Selection Control
Statements
• if
• if.....else
• switch.....case
Iterative Control
Structures
• for loop
• while loop
• do.....while loop
Jump Statements
• break
• continue
• go to
REPETITIVE( ITERATIVE) CONTROL
STRUCTURES OR LOOP
• A loop is a control structure that causes a statement or a set of statements (or code ) to be
repeated again and again while a condition is true.
• The piece of code or set of statements is repeated a certain no. of times till the condition
becomes false, following which control is transferred to the statements following the loops.
• In C++, there are three loop structures:-
• For loop
• While loop
• Do loop ( do..while loop)
PARTS OF A LOOP
• Each loop consists of 3 expressions, the initialization expression, the test
expression and the update expression , and a Loop Control Variable ( or expression
)
• The value of the loop control variable determines the number of times a loop is
executed.
• The three expressions are formed using the loop control variable.
• Examples of the expressions:
Initialization
• int i=0;
• int x=2;
Test
• i < 9;
• x < 4;
Update
• i ++;
• x--;
THE FOR LOOP
The for loop is the easiest to understand and is the most commonly used loop structure
in C++. The structure of the loop is as follows:
for( initialization expression; test expression; update expression)
{
Statement 1;
Statement 2;
Loop body
Statement n;
}
THE FOR LOOP –
STRUCTURE DEFINED
The three expressions usually involve the loop control variable.
The initialization expression initializes the loop variable with some legal
value.
The test expression determines whether or not the loop is to be
continued. It is actually the condition that is checked and depending upon its
value (true or false) the loop is executed or terminated.
The update expression is used to change the value of the loop variable for
further iteration.
for( initialization expression; test expression; update expression)
FLOWCHART : THE FOR LOOP
EXAMPLE :
PROGRAM TO PRINT NUMBERS FROM 1 TO 5
#include <iostream.h>
void main()
{
Initialization conditional update
Expression expression expression
for ( int i=1 ; i<=5 ; i++)
cout<< i <<”n”; loop body
}
Output:
1
2
3
4
5
The loop control variable is i . The loop given above will execute five times. This can be
verified by the number of times the value of i is displayed.
WORKING OF FOR LOOP:
STEP 1
#include <iostream.h>
void main()
{
for ( int i=1 ; i<=5 ; i++)
cout<< i <<”n”;
}
1
WORKING OF FOR LOOP:
STEP 2
#include <iostream.h>
void main()
{
for ( int i=1 ; i<=5 ; i++)
cout<< i <<”n”;
}
2
WORKING OF FOR LOOP:
STEP 3
#include <iostream.h>
void main()
{
for ( int i=1 ; i<=5 ; i++)
cout<< i <<”n”;
}
3
WORKING OF FOR LOOP:
STEP 4
#include <iostream.h>
void main()
{
for ( int i=1 ; i<=5 ; i++)
cout<< i <<”n”;
} 4
WORKING OF FOR LOOP:
BACK TO STEP 2
#include <iostream.h>
void main()
{
for ( int i=1 ; i<=5 ; i++)
cout<< i <<”n”;
}
2
WORKING OF FOR LOOP :
THE LOOP FORMATION
#include <iostream.h>
void main()
{
for ( int i=1 ; i<=5 ; i++)
cout<< i <<”n”;
}
3
4
2
1
WORKING OF FOR LOOP :
THE LOOP FORMATION
#include <iostream.h>
void main()
{
for ( int i=1 ; i<=5 ; i++)
cout<< i <<”n”;
} 3
4
2
1
Step 2 : Test
statement
Step 3 : Loop
body
Step 4 : Update
statement
EXPLANATION
In the above program, we use a for loop to print numbers from 1 to 5. Let us see how this works:
WORKING OF FOR LOOP
1. First, the variable I is initialized with value 1. This happens only once.
2. Next the value of the variable is checked. If it is less than or equal to 5, the control
is passed to the body of the loop. If the condition is not satisfied, the control comes
out of the loop.
3. The body of the loop which contains a cout statement is executed. The value of I is
displayed along with a new line character.
4. Next, the value of i (loop variable) is incremented.
5. Now, control comes back to the step 2, where again the value of i is checked. If it is less
than or equal to 5, the body of the loop ( step 3) is executed, which prints the value of i.
Now, step 4 is carried out, which increments i and so on.
6. The process continues till the value of i becomes 6. When I becomes 6 at step 4, control
is transferred to step 2. Here the value of i is tested, the condition yields false and so the loop is
terminated
MORE EXAMPLES TO DEMONSTRATE
WORKING OF FOR LOOP
for ( int k = 6; x > 0; k -- )
cout << k << “t”;
6 5 4 3 2 1
The variable k(loop control variable) is first
initialized with 6. It is then tested for k > 0,
then the body of the loop is executed which
displays the value of k. Next the value of k is
decremented. Thus numbers in reverse order
from 6 to 1.
for ( int x = 1; x <= 9; x ++)
cout<< 5*x<<“ ” ;
5 10 15 20 25 30 35 40 45
The above code fragment displays
the first nine multiples of 5.
MORE EXAMPLES TO DEMONSTRATE
WORKING OF FOR LOOP
for ( int i = 2; i <= 20; i += 2 )
cout << i << “ ”;
4 6 8 10 12 14 16 18 20
This code displays all the even numbers
from 2 to 20. Note the expression i+=2.
This increments the value of i by 2
int k = 15;
for ( int p = 1; p <= 5; p++ )
{cout<<
k<<“x”<<p<<”=”<<k*p;cout<<
15 X 1 = 15
15 X 2 = 30
15 X 3 = 45
15 X 4 = 60 15 X 5 = 75
The above code fragment displays
the first nine multiples of 5.
EXAMPLE PROGRAM:
WAP TO DISPLAY MULTIPLICATION TABLE
OF A NUMBER
#include<iostream.h>
void main()
{int x, n;
cout<<“nEnter the number “;
cin>>x;
cout<<“nEnter the limit ”;
cin>>n;
for(int i=1; i<=n; i++)
cout<<x<<“ X ”<<i<<“ = “<<x* i<<“n”;
}
S
Declare x,n
Enter x, n
i<n ? Display x*i Increment i
S
Y
EXPLANATION
• Two variables are declared to store the number whose multiplication table is to be
displayed and to store the limit.
int x, n : x for number, n for limit
• The for loop is formed with 1 as the initial value and n as the last.
for(int i=1; i<=n; i++)
• The cout statement displays the number , x, then the multiplication symbol (X), the
value of i (varies from 1 to n), the = sign and then the product of multiplication (x*i)
cout<<x<<“ X ”<<i<<“ = “<<x* i<<“n”;
DRY RUN
• memory diagram of variables
• x n working
• 4 X 1 = 4
i x * i
4 5
1
4
Output
4 X 1 = 4
DRY RUN
• memory diagram of variables
• x n working
• 4 X 2 = 8
i x * i
4 5
2
8
Output
4 X 1 = 4
4 X 2 = 8
DRY RUN
• memory diagram of variables
• x n working
• 4 X 3 = 12
i x * i
4 5
3
12
Output
4 X 1 = 4
4 X 2 = 8
4 X 3 = 12
DRY RUN
• memory diagram of variables
• x n working
• 4 X 4 = 16
i x * i
4 5
4
16
Output
4 X 1 = 4
4 X 2 = 8
4 X 3 = 12
4 X 4 = 16
EXAMPLE PROGRAM:
DISPLAY THE SUM OF THE SERIES
1+X+X2+X3+….XN
#include<iostream.h>
void main()
{int x, n, sum=0;
cout<<“nenter the value of x “;
cin>>x;
cout<<“n enter the value of n”;
cin>>n;
for(int i=1; i<=n; i++)
sum+=pow(x,i);
cout << “nsum of series is ”<<1+sum;
}
S
Declare x,n,sum
Sum=0
Enter x, n
i<n ? Sum=sum +i Increment i
S
Y
NHere sum is an accumulator variable. It accumulates
and stores the numbers from 1 to the value of n
PROGRAM TO CALCULATE
FACTORIAL OF A NUMBER
#include<iostream.h>
void main()
{int x, fact=1;
cout<<“nEnter the number :“;
cin>>x;
for(int i=x; i>0; i- -)
fact= fact * I;;
cout << “nFactorial is:”<< fact;
”<<1+sum;
}
Output
Enter the number : 4
Factorial is:24
VARIATIONS IN FOR LOOP
Variation Loop example Output Explanation
Multiple initialization,
update, test
expressions
for( int i=0, j=2 ; i< j ; i++ , j- -)
cout<<i*j<<“ n”;
0
1
There are two initializations and updates here.
The loop runs till i<j. when I becomes 2 and j
becomes 0 loop breaks.
Placement of
Expressions
int i=0;
for( ; i<5; )
{cout<<i++;
cout<<“ “;
}
0 1 2 3 4 The initialization statement is above the loop
and update inside the loop. This is allowed but
we must write the semicolon in the respective
places.
Empty loop for(int x=0; x<9;x++) ;
cout<<x<<“ ”;
9 This loop will execute till the value of x becomes
9. The semicolon prevents control from entering
loop body. Thus the cout is executed only after
loop terminates which displays the final value of
x(9).
Infinite loop int a = 0;
for( ; ; )
cout<< a ++<<” ” ;
0 1 2 3 4
….
The above for loop does not have a test
expression, therefore the value of a keeps on
incrementing which is displayed after each pass .
As there is no test expression the loop never
breaks.
update
initialization
WHILE LOOP
While loop is usually used when we do not know how many times we need to
execute the loop.
It repeats a statement or a set of statements on the basis of a condition.
 If the condition is true, the statements in the loop are repeated again.
 If the condition is false, the loop is terminated.
unlike the for loop the syntax of while loop does not require to place the
initialization, test and update expressions in any order.
The syntax requires a condition or test expression as a part of it. The other two
statements can be placed according to logic.
SYNTAX OF WHILE LOOP
while having one statement in
loop body
while having multiple statements in
loop body
while(condition)
Statement;
while ( condition )
{
statement block;
}
FLOWCHART: WHILE LOOP
condition
false
true
WHILE LOOP DETAILED SYNTAX
while ( i<9 )
{
statement 1;
statement 2;
…..
….
}
Test expression/ condition
No semicolon
No semicolon
Loop body
 The test expression is any valid conditional
statement formed by using variables,
constants and operators including arithmetic
and relational operators.
 We can also combine two conditions using
logical operators.
 There can be single or multiple statements in
Loop body.
 These can be any valid c++ statement.
WORKING OF WHILE LOOP
while ( i< 9 )
{
statement(s);
}
WORKING OF WHILE LOOP
When condition
is false while ( i< 9 )
{
statement(s);
}
WHILE LOOP EXAMPLE
• In order to be able to run the
loop properly we need the
initialization as well as an update
statement also.
• So we place the initialization
statement before the loop and
the update statement inside the
loop.
Initialization expression
int i= 2;
while( i< 9 )
{
cout<< i<<“n”;
i++;
}update expression
output
2
3
4
5
6
7
8
WORKING OF WHILE LOOP
int i= 2;
while( i< 9 )
{
cout<< i<<“n”;
i++;
}
1
Initialization
WORKING OF WHILE LOOP
int i= 2;
while( i< 9 )
{
cout<< i<<“n”;
i++;
}
2
Test Expression
WORKING OF WHILE LOOP
int i= 2;
while( i< 9 )
{
cout<< i<<“n”;
i++;
}
3
Loop body
WORKING OF WHILE LOOP
int i= 2;
while( i< 9 )
{
cout<< i<<“n”;
i++;
}
4
Update
WORKING OF WHILE LOOP
int i= 2;
while( i< 9 )
{
cout<< i<<“n”;
i++;
}
Control transferred
to test expression
WORKING OF WHILE LOOP
int i= 2;
while( i< 9 )
{
cout<< i<<“n”;
i++;
}
1
2
3
4
1. Loop control variable(i) is initialized
2. The test expression is evaluated
3. Loop body is executed if it is true
4. Loop control variable is updated
and control is transferred back to
test expression.
If test expression evaluates to true
loop is executed otherwise control
is transferred to statement following
the loop
SOME POINTS TO NOTE
• While loop is usually used when we do not know how many times we need to
execute it. Such loops are known as sentinel controlled loops and do not require a
counter.
• The loop control variable acquires its value from user input and not by assignment/
initialization.
• The updating takes place within the loop and depends on user input .
• The number of times the loop executes also depends on the user input
A PROGRAM TO COUNT THE
NUMBER OF DIGITS IN A NUMBER
#include <iostream.h>
void main()
{ int no, count=0;
cout<<“n Enter the number :”;
cin>>no; // user input : loop control variable (LCV)
while(no!=0) // condition is formed using the LCV
{ count ++; // counter
no/=10; // the update statement , changing value of LCV
}
cout<<“ n Number of digits is:”<<count;
}
Enter the number :
4578
Number of digits is : 4
Output
DRY RUN
•
memory diagram of variables
• count no working
Pass 1 count ++
Pass 2 no=no/10
Pass 3
Pass 4
Loop
terminates
1 4578
2
3
4
457
45
4
0
1
2
1 2
WORKING
Pass no Condition (no!=0) Count ++ Update (no/=10) Output
1 4568 4568 != 0 True 1 no=4568/10
 no=456
Number of digits is : 4
2 456 456 != 0 True 2 no=456/10
no=45
3 45 45 != 0 True 3 no=45/10
no=4
4 4 4 != 0 True 4 no=4/10
N0
0 != 0 False loop terminates
DO WHILE LOOP
• The do….. while loop is a control structure in which the loop is first executed and
then the test expression is evaluated.
• This loop is also known as an exit controlled loop as the test expression/condition is
checked at the end of the loop i.e. after the loop body is executed.
• This ensures that the loop executes at least once even if the condition is false.
SYNTAX AND FLOWCHART OF
DO WHILE LOOP
do
{
statement;
} while ( condition );
WORKING OF DO WHILE LOOP
int x = 0; initialization of loop
control variable
do
{
cout << x++;
cout << “n”;
}while (x < 6);
loop body
Loop condition
 The loop control variable is x, which is initialized
to 0.
 The loop body is then executed which displays
and then increments the value of x.
 After this the loop condition is tested.
 If the condition is false, the loop is terminated,
otherwise loop continues.
 When the value of x becomes 6, the condition
becomes false and the loop is terminated
WORKING OF DO WHILE LOOP
In a do loop the loop will execute at least once even if the condition is false.
int x = 8;
do
{
cout << x++;
cout <<”n”;
}while(x < 8);
Output
8
 The value of x is 8 which contradicts the
condition ( x < 8 ).
 But since there is no check the loop body is
executed, which displays the value of x and
increments it.
 After the increment x becomes 9; the condition is
checked in the end which is false and the loop is
terminated.
 Thus we can see that the loop executes at least
once even if the condition is false.
DO LOOP: WORKING
int x = 8;
do
{
cout << x<<“n”;
x++;
} while(x < 8);
1
Initialization
int x = 8;
do
{
cout << x<<“n”;
x++;
} while(x < 8);
2
Loop Body
WORKING OF DO LOOP
int x = 8;
do
{
cout << x<<“n”;
x++;
} while(x < 8);
3
Update
WORKING OF DO LOOP
int x = 8;
do
{
cout << x<<“n”;
x++;
} while(x < 8); 4
Test Expression
WORKING OF DO LOOP
int x = 8;
do
{
cout << x<<“n”;
x++;
} while(x < 8);
Control transferred
to loop body if condition
is true
WORKING OF DO LOOP
WORKING OF DO LOOP
int x = 8;
do
{
cout << x<<“n”;
x++;
} while(x < 8);
1
2
3
4
1. Loop control variable(x) is initialized
2. Loop body is executed
3. Loop control variable is updated
4. The test expression is evaluated
If test expression evaluates to true
loop is executed otherwise control
is transferred to statement following
the loop
PROGRAM TO CHECK WHETHER A
NUMBER IS A PALINDROME
#include <iostream.h>
void main()
{
long int number, d, numrev, storednum;
numrev=0; // declare a variable to accumulate reversed number
cout<<”Enter the number”;
cin>>number; // Enter number to check (LCV)
storednum=number; // store a copy of the original number as the value will change in the
loop
do
{
d= number % 2; // extract the last digit
numrev=numrev*10 + d; // accumulate the digit in reverse
number=number/10; // shorten the number (update LCV)
}while(number !=0);
if(numrev=storednum) // numrev will contain the reversed number, compare with
cout<<”n It is a Palindrome”; // original number, if they are equal, it is a palindrome
else
cout<< “n It is not a Palindrome”;
}
SAMPLE RUNS OF THE PROGRAM
Sample run 1 :
Enter the number : 99099
It is a palindrome
Sample run 2:
Enter the number : 1818
It is not a palindrome
ENTRY CONTROLLED AND EXIT
CONTROLLED LOOPS
The for and while loop are entry controlled loops whereas the do while is an exit
controlled loop.
Entry Controlled Loop Exit Controlled Loop
Condition is checked before the loop body. Condition is checked after the loop body.
If the condition is false, loop will not be
executed at all
If the condition is false, even then the loop is
executed at least once
while(condition)
Loop body
do
loop body
while(condition);
Loop Entry point
Loop Exit point
EXAMPLE OF ENTRY CONTROLLED
LOOP VS EXIT CONTROLLED LOOP
While loop Do while loop
int i = 15;
while ( i < 6 )
{
cout<< i--<<”n”;
}
int i = 15;
do
{
cout<< i--<<”n”;
} while ( i < 6 );
Output Output
No output 15
Explanation Explanation
The loop body will not be
entered(executed) since condition is false
and checked before the body.
The loop body will be entered(executed) and
then the condition will be checked. Since it is
false, loop will terminate.
loop will not be executed even once as the
condition is false
loop will be executed at least once even if the
condition is false
WHICH LOOP TO USE WHEN
• All the loops are interchangeable. We can replace any loop with another. But there
are some situations which can determine the choice:
We use the for loop when we know exactly how any times the statements are to be
repeated.
 If we do not know, exactly how any times the statements are to be repeated then
we use while loop.
 the for loop is used when we do not know exactly how any times the statements
are to be repeated but you need to execute the loop at least once.
JUMP STATEMENTS
C++ provides us with some jump statements that forcibly transfer flow of control
according to a given condition.
There are three jump statements and a function which we shall study
• break
• continue
• goto
• exit()
THE BREAK STATEMENT
The break statement causes a loop to exit ie, it terminates the loop as soon
as it is encountered. The control is transferred outside the loop.
The break statement can be used with any of the loops- for loop, while loop
or do….. while loop.
Syntax:
break;
Usage :
for(int i=0; i<15; i++)
{ if ( i % 11 ==0)
break;
cout<<i<<“n”;
}
EXAMPLE AND FLOWCHART
Code Output & Explanation
int i = 0;
while( i < 15 )
{
if( i = = 6 )
break;
cout << i << “n”;
i = i + 2;
}
cout << “outside of
loop”;
}
Output
0
2
4
Outside of loop
Explanation
The loop runs only till the
values of I becomes 6. When I
is 6 the loop terminates and
control is transferred to the
statement outside the loop.
i= =
6 ?
S
Initialize i
i<15 ?
Display i
Increment i
S
F
T
T
F
THE CONTINUE STATEMENT
The continue statement is used to skip the current iteration (or pass ) of a loop.
This statement is valid only in loops.
When it is encountered it skips the rest of the statements in the loop body and
causes the next iteration of the loop.
Syntax:
continue;
Usage
for(int i=0; i<15; i++)
{ if ( i % 11 ==0)
continue;
cout<<i<<“n”;
}
code Output and explanation
int i=1;
while(i<6)
{
if(i%2= =0)
continue;
cout<<i++<<”n”;
}
cout<<”n out of loop”;
1
3
5
out of loop
Explanation
The loop will not display any
even numbers as whenever
the value of i is even, the
continue is executed and
control is transferred to the
update statement.
S
Initialize i
i< 6
?
Display i
S
i %
2==0
?
Increment i
T
T
F
F
EXAMPLE AND FLOWCHART
THE GOTO STATEMENT
The goto statement is used to transfer control from one part of the program
to some other part.
The syntax of goto is:
goto label;
 Where label is any valid C++ identifier which is used to label the part of
the program where the control is to be transferred
EXAMPLE AND EXPLANATION
#include<iostream.h>
void main()
{
int n = 6;
int k;
cout<< “ Enter a number”;
cin>> k;
if(n > k)
goto path1;
else
cout<<n<<”is not more than”<< k;
path1:
cout<<”The larger number is”<< n;
}
Output
Enter a number 3
The larger number is 6
We can see from the code that the
goto statement simply transfer
control to some other part of the
program.
Here n is 6.
Suppose we enter 3 into k, then the
if condition (n > k) becomes true
and the goto is executed which is
goto path1
Control is transferred to the
statement labelled path1 where
cout is executed
WHY WE SHOULD NOT USE GOTO?
• It is best to avoid using goto as it leads to the program complexity. Programs
having goto are hard to debug and follow.
• It is bad programming practice to use goto as it may lead to system failure.

More Related Content

What's hot

Queue data structure
Queue data structureQueue data structure
Queue data structure
anooppjoseph
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
Indu Sharma Bhardwaj
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
Kuppusamy P
 
file handling c++
file handling c++file handling c++
file handling c++Guddu Spy
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++
Vishesh Jha
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
RubaNagarajan
 
Queue in Data Structure
Queue in Data Structure Queue in Data Structure
Queue in Data Structure
Janki Shah
 
Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C Programming
Qazi Shahzad Ali
 
C# Loops
C# LoopsC# Loops
C# Loops
Hock Leng PUAH
 
Decision making and branching in c programming
Decision making and branching in c programmingDecision making and branching in c programming
Decision making and branching in c programming
Priyansh Thakar
 
Queue AS an ADT (Abstract Data Type)
Queue AS an ADT (Abstract Data Type)Queue AS an ADT (Abstract Data Type)
Queue AS an ADT (Abstract Data Type)
Self-Employed
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
RaginiJain21
 
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KRLoops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
Krishna Raj
 
String Library Functions
String Library FunctionsString Library Functions
String Library Functions
Nayan Sharma
 
visual basic v6 introduction
visual basic v6 introductionvisual basic v6 introduction
visual basic v6 introductionbloodyedge03
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Language
satvirsandhu9
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
10. switch case
10. switch case10. switch case
10. switch case
Way2itech
 
Stacks
StacksStacks
Stacks
sweta dargad
 
Stack data structure in Data Structure using C
Stack data structure in Data Structure using C Stack data structure in Data Structure using C
Stack data structure in Data Structure using C
Meghaj Mallick
 

What's hot (20)

Queue data structure
Queue data structureQueue data structure
Queue data structure
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
file handling c++
file handling c++file handling c++
file handling c++
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
 
Queue in Data Structure
Queue in Data Structure Queue in Data Structure
Queue in Data Structure
 
Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C Programming
 
C# Loops
C# LoopsC# Loops
C# Loops
 
Decision making and branching in c programming
Decision making and branching in c programmingDecision making and branching in c programming
Decision making and branching in c programming
 
Queue AS an ADT (Abstract Data Type)
Queue AS an ADT (Abstract Data Type)Queue AS an ADT (Abstract Data Type)
Queue AS an ADT (Abstract Data Type)
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KRLoops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
 
String Library Functions
String Library FunctionsString Library Functions
String Library Functions
 
visual basic v6 introduction
visual basic v6 introductionvisual basic v6 introduction
visual basic v6 introduction
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Language
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
10. switch case
10. switch case10. switch case
10. switch case
 
Stacks
StacksStacks
Stacks
 
Stack data structure in Data Structure using C
Stack data structure in Data Structure using C Stack data structure in Data Structure using C
Stack data structure in Data Structure using C
 

Similar to Iterative control structures, looping, types of loops, loop working

Loops c++
Loops c++Loops c++
Loops c++
Shivani Singh
 
Iteration
IterationIteration
Iteration
Liam Dunphy
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2rohassanie
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
Ahmad Idrees
 
4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf
ShifatiRabbi
 
04a intro while
04a intro while04a intro while
04a intro whilehasfaa1017
 
C++ control structure
C++ control structureC++ control structure
C++ control structurebluejayjunior
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
JayBhavsar68
 
Ch6 Loops
Ch6 LoopsCh6 Loops
Ch6 Loops
SzeChingChen
 
06.Loops
06.Loops06.Loops
06.Loops
Intro C# Book
 
Nested loops
Nested loopsNested loops
Nested loops
Neeru Mittal
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.ppt
sanjay
 
C++ loop
C++ loop C++ loop
C++ loop
Khelan Ameen
 
Lec7 - Loops updated.pptx
Lec7 - Loops updated.pptxLec7 - Loops updated.pptx
Lec7 - Loops updated.pptx
NaumanRasheed11
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6Vince Vo
 
Chp4_C++_Control Structures-Part2_Iteration.pptx
Chp4_C++_Control Structures-Part2_Iteration.pptxChp4_C++_Control Structures-Part2_Iteration.pptx
Chp4_C++_Control Structures-Part2_Iteration.pptx
ssuser10ed71
 
Csc1100 lecture05 ch05
Csc1100 lecture05 ch05Csc1100 lecture05 ch05
Csc1100 lecture05 ch05IIUM
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
msharshitha03s
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
PRN USM
 

Similar to Iterative control structures, looping, types of loops, loop working (20)

Loops c++
Loops c++Loops c++
Loops c++
 
Iteration
IterationIteration
Iteration
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf
 
04a intro while
04a intro while04a intro while
04a intro while
 
C++ control structure
C++ control structureC++ control structure
C++ control structure
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
 
Ch6 Loops
Ch6 LoopsCh6 Loops
Ch6 Loops
 
06.Loops
06.Loops06.Loops
06.Loops
 
Nested loops
Nested loopsNested loops
Nested loops
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.ppt
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
C++ loop
C++ loop C++ loop
C++ loop
 
Lec7 - Loops updated.pptx
Lec7 - Loops updated.pptxLec7 - Loops updated.pptx
Lec7 - Loops updated.pptx
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
 
Chp4_C++_Control Structures-Part2_Iteration.pptx
Chp4_C++_Control Structures-Part2_Iteration.pptxChp4_C++_Control Structures-Part2_Iteration.pptx
Chp4_C++_Control Structures-Part2_Iteration.pptx
 
Csc1100 lecture05 ch05
Csc1100 lecture05 ch05Csc1100 lecture05 ch05
Csc1100 lecture05 ch05
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 

More from Neeru Mittal

Machine Learning
Machine LearningMachine Learning
Machine Learning
Neeru Mittal
 
Introduction to AI and its domains.pptx
Introduction to AI and its domains.pptxIntroduction to AI and its domains.pptx
Introduction to AI and its domains.pptx
Neeru Mittal
 
Brain Storming techniques in Python
Brain Storming techniques in PythonBrain Storming techniques in Python
Brain Storming techniques in Python
Neeru Mittal
 
Data Analysis with Python Pandas
Data Analysis with Python PandasData Analysis with Python Pandas
Data Analysis with Python Pandas
Neeru Mittal
 
Python Tips and Tricks
Python Tips and TricksPython Tips and Tricks
Python Tips and Tricks
Neeru Mittal
 
Python and CSV Connectivity
Python and CSV ConnectivityPython and CSV Connectivity
Python and CSV Connectivity
Neeru Mittal
 
Working of while loop
Working of while loopWorking of while loop
Working of while loop
Neeru Mittal
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++
Neeru Mittal
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
Neeru Mittal
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
Neeru Mittal
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
Neeru Mittal
 
Arrays
ArraysArrays
Arrays
Neeru Mittal
 
Variables in C++, data types in c++
Variables in C++, data types in c++Variables in C++, data types in c++
Variables in C++, data types in c++
Neeru Mittal
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
Neeru Mittal
 
Introduction to programming
Introduction to programmingIntroduction to programming
Introduction to programming
Neeru Mittal
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
Neeru Mittal
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
Neeru Mittal
 

More from Neeru Mittal (17)

Machine Learning
Machine LearningMachine Learning
Machine Learning
 
Introduction to AI and its domains.pptx
Introduction to AI and its domains.pptxIntroduction to AI and its domains.pptx
Introduction to AI and its domains.pptx
 
Brain Storming techniques in Python
Brain Storming techniques in PythonBrain Storming techniques in Python
Brain Storming techniques in Python
 
Data Analysis with Python Pandas
Data Analysis with Python PandasData Analysis with Python Pandas
Data Analysis with Python Pandas
 
Python Tips and Tricks
Python Tips and TricksPython Tips and Tricks
Python Tips and Tricks
 
Python and CSV Connectivity
Python and CSV ConnectivityPython and CSV Connectivity
Python and CSV Connectivity
 
Working of while loop
Working of while loopWorking of while loop
Working of while loop
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 
Arrays
ArraysArrays
Arrays
 
Variables in C++, data types in c++
Variables in C++, data types in c++Variables in C++, data types in c++
Variables in C++, data types in c++
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 
Introduction to programming
Introduction to programmingIntroduction to programming
Introduction to programming
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
 

Recently uploaded

How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 

Recently uploaded (20)

How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 

Iterative control structures, looping, types of loops, loop working

  • 2. AFTER THIS LESSON, LEARNERS WILL BE ABLE TO: • Understand the concept and usage of selection and iteration statements. • Know various types of control structures available in C++. • Analyze the problem, decide and evaluate conditions. • To analyze and choose an appropriate combination of constructs to solve a particular problem • Write code that employ decision structures, including those that employ sequences of decision and nested decisions. • Design simple applications having iterative nature.
  • 3. FLOW OF CONTROL AND CONTROL STRUCTURES The order in which a set of statements are executed in a program is known as its flow of control Generally the flow of control is sequential.  However at times it is required to change this sequential flow so that only a particular statement or group of statements are executed. This is achieved by control structures . Control structures are statements that upon execution alter or control the sequence of execution of statements in a program.
  • 4. TYPES OF CONTROL STRUCTURES These can be categorized into the following categories: Selection Control Statements • if • if.....else • switch.....case Iterative Control Structures • for loop • while loop • do.....while loop Jump Statements • break • continue • go to
  • 5. REPETITIVE( ITERATIVE) CONTROL STRUCTURES OR LOOP • A loop is a control structure that causes a statement or a set of statements (or code ) to be repeated again and again while a condition is true. • The piece of code or set of statements is repeated a certain no. of times till the condition becomes false, following which control is transferred to the statements following the loops. • In C++, there are three loop structures:- • For loop • While loop • Do loop ( do..while loop)
  • 6. PARTS OF A LOOP • Each loop consists of 3 expressions, the initialization expression, the test expression and the update expression , and a Loop Control Variable ( or expression ) • The value of the loop control variable determines the number of times a loop is executed. • The three expressions are formed using the loop control variable. • Examples of the expressions: Initialization • int i=0; • int x=2; Test • i < 9; • x < 4; Update • i ++; • x--;
  • 7. THE FOR LOOP The for loop is the easiest to understand and is the most commonly used loop structure in C++. The structure of the loop is as follows: for( initialization expression; test expression; update expression) { Statement 1; Statement 2; Loop body Statement n; }
  • 8. THE FOR LOOP – STRUCTURE DEFINED The three expressions usually involve the loop control variable. The initialization expression initializes the loop variable with some legal value. The test expression determines whether or not the loop is to be continued. It is actually the condition that is checked and depending upon its value (true or false) the loop is executed or terminated. The update expression is used to change the value of the loop variable for further iteration. for( initialization expression; test expression; update expression)
  • 9. FLOWCHART : THE FOR LOOP
  • 10. EXAMPLE : PROGRAM TO PRINT NUMBERS FROM 1 TO 5 #include <iostream.h> void main() { Initialization conditional update Expression expression expression for ( int i=1 ; i<=5 ; i++) cout<< i <<”n”; loop body } Output: 1 2 3 4 5 The loop control variable is i . The loop given above will execute five times. This can be verified by the number of times the value of i is displayed.
  • 11. WORKING OF FOR LOOP: STEP 1 #include <iostream.h> void main() { for ( int i=1 ; i<=5 ; i++) cout<< i <<”n”; } 1
  • 12. WORKING OF FOR LOOP: STEP 2 #include <iostream.h> void main() { for ( int i=1 ; i<=5 ; i++) cout<< i <<”n”; } 2
  • 13. WORKING OF FOR LOOP: STEP 3 #include <iostream.h> void main() { for ( int i=1 ; i<=5 ; i++) cout<< i <<”n”; } 3
  • 14. WORKING OF FOR LOOP: STEP 4 #include <iostream.h> void main() { for ( int i=1 ; i<=5 ; i++) cout<< i <<”n”; } 4
  • 15. WORKING OF FOR LOOP: BACK TO STEP 2 #include <iostream.h> void main() { for ( int i=1 ; i<=5 ; i++) cout<< i <<”n”; } 2
  • 16. WORKING OF FOR LOOP : THE LOOP FORMATION #include <iostream.h> void main() { for ( int i=1 ; i<=5 ; i++) cout<< i <<”n”; } 3 4 2 1
  • 17. WORKING OF FOR LOOP : THE LOOP FORMATION #include <iostream.h> void main() { for ( int i=1 ; i<=5 ; i++) cout<< i <<”n”; } 3 4 2 1 Step 2 : Test statement Step 3 : Loop body Step 4 : Update statement
  • 18. EXPLANATION In the above program, we use a for loop to print numbers from 1 to 5. Let us see how this works: WORKING OF FOR LOOP 1. First, the variable I is initialized with value 1. This happens only once. 2. Next the value of the variable is checked. If it is less than or equal to 5, the control is passed to the body of the loop. If the condition is not satisfied, the control comes out of the loop. 3. The body of the loop which contains a cout statement is executed. The value of I is displayed along with a new line character. 4. Next, the value of i (loop variable) is incremented. 5. Now, control comes back to the step 2, where again the value of i is checked. If it is less than or equal to 5, the body of the loop ( step 3) is executed, which prints the value of i. Now, step 4 is carried out, which increments i and so on. 6. The process continues till the value of i becomes 6. When I becomes 6 at step 4, control is transferred to step 2. Here the value of i is tested, the condition yields false and so the loop is terminated
  • 19. MORE EXAMPLES TO DEMONSTRATE WORKING OF FOR LOOP for ( int k = 6; x > 0; k -- ) cout << k << “t”; 6 5 4 3 2 1 The variable k(loop control variable) is first initialized with 6. It is then tested for k > 0, then the body of the loop is executed which displays the value of k. Next the value of k is decremented. Thus numbers in reverse order from 6 to 1. for ( int x = 1; x <= 9; x ++) cout<< 5*x<<“ ” ; 5 10 15 20 25 30 35 40 45 The above code fragment displays the first nine multiples of 5.
  • 20. MORE EXAMPLES TO DEMONSTRATE WORKING OF FOR LOOP for ( int i = 2; i <= 20; i += 2 ) cout << i << “ ”; 4 6 8 10 12 14 16 18 20 This code displays all the even numbers from 2 to 20. Note the expression i+=2. This increments the value of i by 2 int k = 15; for ( int p = 1; p <= 5; p++ ) {cout<< k<<“x”<<p<<”=”<<k*p;cout<< 15 X 1 = 15 15 X 2 = 30 15 X 3 = 45 15 X 4 = 60 15 X 5 = 75 The above code fragment displays the first nine multiples of 5.
  • 21. EXAMPLE PROGRAM: WAP TO DISPLAY MULTIPLICATION TABLE OF A NUMBER #include<iostream.h> void main() {int x, n; cout<<“nEnter the number “; cin>>x; cout<<“nEnter the limit ”; cin>>n; for(int i=1; i<=n; i++) cout<<x<<“ X ”<<i<<“ = “<<x* i<<“n”; } S Declare x,n Enter x, n i<n ? Display x*i Increment i S Y
  • 22. EXPLANATION • Two variables are declared to store the number whose multiplication table is to be displayed and to store the limit. int x, n : x for number, n for limit • The for loop is formed with 1 as the initial value and n as the last. for(int i=1; i<=n; i++) • The cout statement displays the number , x, then the multiplication symbol (X), the value of i (varies from 1 to n), the = sign and then the product of multiplication (x*i) cout<<x<<“ X ”<<i<<“ = “<<x* i<<“n”;
  • 23. DRY RUN • memory diagram of variables • x n working • 4 X 1 = 4 i x * i 4 5 1 4 Output 4 X 1 = 4
  • 24. DRY RUN • memory diagram of variables • x n working • 4 X 2 = 8 i x * i 4 5 2 8 Output 4 X 1 = 4 4 X 2 = 8
  • 25. DRY RUN • memory diagram of variables • x n working • 4 X 3 = 12 i x * i 4 5 3 12 Output 4 X 1 = 4 4 X 2 = 8 4 X 3 = 12
  • 26. DRY RUN • memory diagram of variables • x n working • 4 X 4 = 16 i x * i 4 5 4 16 Output 4 X 1 = 4 4 X 2 = 8 4 X 3 = 12 4 X 4 = 16
  • 27. EXAMPLE PROGRAM: DISPLAY THE SUM OF THE SERIES 1+X+X2+X3+….XN #include<iostream.h> void main() {int x, n, sum=0; cout<<“nenter the value of x “; cin>>x; cout<<“n enter the value of n”; cin>>n; for(int i=1; i<=n; i++) sum+=pow(x,i); cout << “nsum of series is ”<<1+sum; } S Declare x,n,sum Sum=0 Enter x, n i<n ? Sum=sum +i Increment i S Y NHere sum is an accumulator variable. It accumulates and stores the numbers from 1 to the value of n
  • 28. PROGRAM TO CALCULATE FACTORIAL OF A NUMBER #include<iostream.h> void main() {int x, fact=1; cout<<“nEnter the number :“; cin>>x; for(int i=x; i>0; i- -) fact= fact * I;; cout << “nFactorial is:”<< fact; ”<<1+sum; } Output Enter the number : 4 Factorial is:24
  • 29. VARIATIONS IN FOR LOOP Variation Loop example Output Explanation Multiple initialization, update, test expressions for( int i=0, j=2 ; i< j ; i++ , j- -) cout<<i*j<<“ n”; 0 1 There are two initializations and updates here. The loop runs till i<j. when I becomes 2 and j becomes 0 loop breaks. Placement of Expressions int i=0; for( ; i<5; ) {cout<<i++; cout<<“ “; } 0 1 2 3 4 The initialization statement is above the loop and update inside the loop. This is allowed but we must write the semicolon in the respective places. Empty loop for(int x=0; x<9;x++) ; cout<<x<<“ ”; 9 This loop will execute till the value of x becomes 9. The semicolon prevents control from entering loop body. Thus the cout is executed only after loop terminates which displays the final value of x(9). Infinite loop int a = 0; for( ; ; ) cout<< a ++<<” ” ; 0 1 2 3 4 …. The above for loop does not have a test expression, therefore the value of a keeps on incrementing which is displayed after each pass . As there is no test expression the loop never breaks. update initialization
  • 30. WHILE LOOP While loop is usually used when we do not know how many times we need to execute the loop. It repeats a statement or a set of statements on the basis of a condition.  If the condition is true, the statements in the loop are repeated again.  If the condition is false, the loop is terminated. unlike the for loop the syntax of while loop does not require to place the initialization, test and update expressions in any order. The syntax requires a condition or test expression as a part of it. The other two statements can be placed according to logic.
  • 31. SYNTAX OF WHILE LOOP while having one statement in loop body while having multiple statements in loop body while(condition) Statement; while ( condition ) { statement block; }
  • 33. WHILE LOOP DETAILED SYNTAX while ( i<9 ) { statement 1; statement 2; ….. …. } Test expression/ condition No semicolon No semicolon Loop body  The test expression is any valid conditional statement formed by using variables, constants and operators including arithmetic and relational operators.  We can also combine two conditions using logical operators.  There can be single or multiple statements in Loop body.  These can be any valid c++ statement.
  • 34. WORKING OF WHILE LOOP while ( i< 9 ) { statement(s); }
  • 35. WORKING OF WHILE LOOP When condition is false while ( i< 9 ) { statement(s); }
  • 36. WHILE LOOP EXAMPLE • In order to be able to run the loop properly we need the initialization as well as an update statement also. • So we place the initialization statement before the loop and the update statement inside the loop. Initialization expression int i= 2; while( i< 9 ) { cout<< i<<“n”; i++; }update expression output 2 3 4 5 6 7 8
  • 37. WORKING OF WHILE LOOP int i= 2; while( i< 9 ) { cout<< i<<“n”; i++; } 1 Initialization
  • 38. WORKING OF WHILE LOOP int i= 2; while( i< 9 ) { cout<< i<<“n”; i++; } 2 Test Expression
  • 39. WORKING OF WHILE LOOP int i= 2; while( i< 9 ) { cout<< i<<“n”; i++; } 3 Loop body
  • 40. WORKING OF WHILE LOOP int i= 2; while( i< 9 ) { cout<< i<<“n”; i++; } 4 Update
  • 41. WORKING OF WHILE LOOP int i= 2; while( i< 9 ) { cout<< i<<“n”; i++; } Control transferred to test expression
  • 42. WORKING OF WHILE LOOP int i= 2; while( i< 9 ) { cout<< i<<“n”; i++; } 1 2 3 4 1. Loop control variable(i) is initialized 2. The test expression is evaluated 3. Loop body is executed if it is true 4. Loop control variable is updated and control is transferred back to test expression. If test expression evaluates to true loop is executed otherwise control is transferred to statement following the loop
  • 43. SOME POINTS TO NOTE • While loop is usually used when we do not know how many times we need to execute it. Such loops are known as sentinel controlled loops and do not require a counter. • The loop control variable acquires its value from user input and not by assignment/ initialization. • The updating takes place within the loop and depends on user input . • The number of times the loop executes also depends on the user input
  • 44. A PROGRAM TO COUNT THE NUMBER OF DIGITS IN A NUMBER #include <iostream.h> void main() { int no, count=0; cout<<“n Enter the number :”; cin>>no; // user input : loop control variable (LCV) while(no!=0) // condition is formed using the LCV { count ++; // counter no/=10; // the update statement , changing value of LCV } cout<<“ n Number of digits is:”<<count; } Enter the number : 4578 Number of digits is : 4 Output
  • 45. DRY RUN • memory diagram of variables • count no working Pass 1 count ++ Pass 2 no=no/10 Pass 3 Pass 4 Loop terminates 1 4578 2 3 4 457 45 4 0 1 2 1 2
  • 46. WORKING Pass no Condition (no!=0) Count ++ Update (no/=10) Output 1 4568 4568 != 0 True 1 no=4568/10  no=456 Number of digits is : 4 2 456 456 != 0 True 2 no=456/10 no=45 3 45 45 != 0 True 3 no=45/10 no=4 4 4 4 != 0 True 4 no=4/10 N0 0 != 0 False loop terminates
  • 47. DO WHILE LOOP • The do….. while loop is a control structure in which the loop is first executed and then the test expression is evaluated. • This loop is also known as an exit controlled loop as the test expression/condition is checked at the end of the loop i.e. after the loop body is executed. • This ensures that the loop executes at least once even if the condition is false.
  • 48. SYNTAX AND FLOWCHART OF DO WHILE LOOP do { statement; } while ( condition );
  • 49. WORKING OF DO WHILE LOOP int x = 0; initialization of loop control variable do { cout << x++; cout << “n”; }while (x < 6); loop body Loop condition  The loop control variable is x, which is initialized to 0.  The loop body is then executed which displays and then increments the value of x.  After this the loop condition is tested.  If the condition is false, the loop is terminated, otherwise loop continues.  When the value of x becomes 6, the condition becomes false and the loop is terminated
  • 50. WORKING OF DO WHILE LOOP In a do loop the loop will execute at least once even if the condition is false. int x = 8; do { cout << x++; cout <<”n”; }while(x < 8); Output 8  The value of x is 8 which contradicts the condition ( x < 8 ).  But since there is no check the loop body is executed, which displays the value of x and increments it.  After the increment x becomes 9; the condition is checked in the end which is false and the loop is terminated.  Thus we can see that the loop executes at least once even if the condition is false.
  • 51. DO LOOP: WORKING int x = 8; do { cout << x<<“n”; x++; } while(x < 8); 1 Initialization
  • 52. int x = 8; do { cout << x<<“n”; x++; } while(x < 8); 2 Loop Body WORKING OF DO LOOP
  • 53. int x = 8; do { cout << x<<“n”; x++; } while(x < 8); 3 Update WORKING OF DO LOOP
  • 54. int x = 8; do { cout << x<<“n”; x++; } while(x < 8); 4 Test Expression WORKING OF DO LOOP
  • 55. int x = 8; do { cout << x<<“n”; x++; } while(x < 8); Control transferred to loop body if condition is true WORKING OF DO LOOP
  • 56. WORKING OF DO LOOP int x = 8; do { cout << x<<“n”; x++; } while(x < 8); 1 2 3 4 1. Loop control variable(x) is initialized 2. Loop body is executed 3. Loop control variable is updated 4. The test expression is evaluated If test expression evaluates to true loop is executed otherwise control is transferred to statement following the loop
  • 57. PROGRAM TO CHECK WHETHER A NUMBER IS A PALINDROME #include <iostream.h> void main() { long int number, d, numrev, storednum; numrev=0; // declare a variable to accumulate reversed number cout<<”Enter the number”; cin>>number; // Enter number to check (LCV) storednum=number; // store a copy of the original number as the value will change in the loop do { d= number % 2; // extract the last digit numrev=numrev*10 + d; // accumulate the digit in reverse number=number/10; // shorten the number (update LCV) }while(number !=0); if(numrev=storednum) // numrev will contain the reversed number, compare with cout<<”n It is a Palindrome”; // original number, if they are equal, it is a palindrome else cout<< “n It is not a Palindrome”; }
  • 58. SAMPLE RUNS OF THE PROGRAM Sample run 1 : Enter the number : 99099 It is a palindrome Sample run 2: Enter the number : 1818 It is not a palindrome
  • 59. ENTRY CONTROLLED AND EXIT CONTROLLED LOOPS The for and while loop are entry controlled loops whereas the do while is an exit controlled loop. Entry Controlled Loop Exit Controlled Loop Condition is checked before the loop body. Condition is checked after the loop body. If the condition is false, loop will not be executed at all If the condition is false, even then the loop is executed at least once while(condition) Loop body do loop body while(condition); Loop Entry point Loop Exit point
  • 60. EXAMPLE OF ENTRY CONTROLLED LOOP VS EXIT CONTROLLED LOOP While loop Do while loop int i = 15; while ( i < 6 ) { cout<< i--<<”n”; } int i = 15; do { cout<< i--<<”n”; } while ( i < 6 ); Output Output No output 15 Explanation Explanation The loop body will not be entered(executed) since condition is false and checked before the body. The loop body will be entered(executed) and then the condition will be checked. Since it is false, loop will terminate. loop will not be executed even once as the condition is false loop will be executed at least once even if the condition is false
  • 61. WHICH LOOP TO USE WHEN • All the loops are interchangeable. We can replace any loop with another. But there are some situations which can determine the choice: We use the for loop when we know exactly how any times the statements are to be repeated.  If we do not know, exactly how any times the statements are to be repeated then we use while loop.  the for loop is used when we do not know exactly how any times the statements are to be repeated but you need to execute the loop at least once.
  • 62. JUMP STATEMENTS C++ provides us with some jump statements that forcibly transfer flow of control according to a given condition. There are three jump statements and a function which we shall study • break • continue • goto • exit()
  • 63. THE BREAK STATEMENT The break statement causes a loop to exit ie, it terminates the loop as soon as it is encountered. The control is transferred outside the loop. The break statement can be used with any of the loops- for loop, while loop or do….. while loop. Syntax: break; Usage : for(int i=0; i<15; i++) { if ( i % 11 ==0) break; cout<<i<<“n”; }
  • 64. EXAMPLE AND FLOWCHART Code Output & Explanation int i = 0; while( i < 15 ) { if( i = = 6 ) break; cout << i << “n”; i = i + 2; } cout << “outside of loop”; } Output 0 2 4 Outside of loop Explanation The loop runs only till the values of I becomes 6. When I is 6 the loop terminates and control is transferred to the statement outside the loop. i= = 6 ? S Initialize i i<15 ? Display i Increment i S F T T F
  • 65. THE CONTINUE STATEMENT The continue statement is used to skip the current iteration (or pass ) of a loop. This statement is valid only in loops. When it is encountered it skips the rest of the statements in the loop body and causes the next iteration of the loop. Syntax: continue; Usage for(int i=0; i<15; i++) { if ( i % 11 ==0) continue; cout<<i<<“n”; }
  • 66. code Output and explanation int i=1; while(i<6) { if(i%2= =0) continue; cout<<i++<<”n”; } cout<<”n out of loop”; 1 3 5 out of loop Explanation The loop will not display any even numbers as whenever the value of i is even, the continue is executed and control is transferred to the update statement. S Initialize i i< 6 ? Display i S i % 2==0 ? Increment i T T F F EXAMPLE AND FLOWCHART
  • 67. THE GOTO STATEMENT The goto statement is used to transfer control from one part of the program to some other part. The syntax of goto is: goto label;  Where label is any valid C++ identifier which is used to label the part of the program where the control is to be transferred
  • 68. EXAMPLE AND EXPLANATION #include<iostream.h> void main() { int n = 6; int k; cout<< “ Enter a number”; cin>> k; if(n > k) goto path1; else cout<<n<<”is not more than”<< k; path1: cout<<”The larger number is”<< n; } Output Enter a number 3 The larger number is 6 We can see from the code that the goto statement simply transfer control to some other part of the program. Here n is 6. Suppose we enter 3 into k, then the if condition (n > k) becomes true and the goto is executed which is goto path1 Control is transferred to the statement labelled path1 where cout is executed
  • 69. WHY WE SHOULD NOT USE GOTO? • It is best to avoid using goto as it leads to the program complexity. Programs having goto are hard to debug and follow. • It is bad programming practice to use goto as it may lead to system failure.