Today's Lecture Outline: - Loops - While Loop
Today's Lecture Outline: - Loops - While Loop
• Loops
– while loop
1
Loops in C/C++
• Three major loops structures in C/C++
– while loop
– for loop
– do while
2
Loop in general
• Loop has a termination point finite loop
– Loop execution stops when the loop
condition becomes false
• Loop has a counter that counts number of
iterations of that loop
• Loop has a statement or a set of statements
that are executed until the loop condition
become false
3
Repetition - Example
• Formula 1 car race
• There is a path/track
• Each car has to complete a
certain no of rounds say 10
• In each round, when a car cross
the finish line
– the condition is check whether
the car has completed total no
of round or not.
4
General form while loop
5
The while loop
Condition
Set of
statements Loop counter
6
A while loop program
main( )
{ Memory
int count = 0;
51 0
int total = 0; count 2
34
while(count < 5)
{ total 3
1
0
6
total = total + count; 10
cout<< count<< total; 0
count = count +1;
}
}
Program Output
count = 0, total = 0
count = 1, total = 1
count = 2, total = 3
count = 3, total = 6
count = 4, total = 10 7
Points to remember
• Loop body will keep on executing until the
loop condition become false
• When loop condition become false, the first
statement after the while block will be
executed
• Condition can be a single or compound
8
Cont.
• Statement within loop body can be single line
or block of statement.
• In case of single line parentheses are optional
10
Cont.
• Loop counter can be decremented
11
Cont.
• It is not necessary that a loop counter must
only be int. it can be float or char
12
Pre and post increment operator
• Pre increment/ decrement
– ++x; is same as x = x + 1;
– or – –x is same as x = x – 1;
• Post increment/ decrement
– x++; is same as x = x + 1;
– or x-- is same as x = x – 1;
13
Difference between pre and post operators
x = 1; y = x;
y = x ++; x = x + 1;
cout<<x<<y;
output
x = 2, y = 1
x = 1; x = x + 1;
y = ++ x; y = x;
cout<<x<<y;
output
x = 2, y = 2
14
Other operator
i = i + 1;
• += is a compound assignment operator
• j = j + 10 can also be written as j += 10
• Other compound assignment operators are -=, *=, / =, %=.
15
Example program
First comparison i < 10 is
performed then value of
i is incremented
16