Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

CS-114 Fundamentals of Programming

Control Structures – Repetition Structures

Dr Ayesha Zeb
Email: ayesha.zeb@ceme.nust.edu.pk
Lecture Contents

• Repetition Structures
– While Loop
– For Loop
– Do-While Loop
Repetition Structures
• Repetition structures specify that actions should be
repeated while some condition remains true
– while
– for
– do while
while Loop
• while loop executes a set of
statements as long as the condition
specified at the beginning is true.
• The condition is evaluated at the
beginning of the loop
– If it is true, the loop will execute
– If it is false, the loop will not execute
even once
while Loop

Syntax:
while(condition)
{
statement1;

statement n;
}
while Loop
Example: Initialization Output:
1
int a=1; Condition 2
3
while(a<=3)
{
cout<<a<<endl;
a++;
Increment
}
• As long as the condition continues to be true (i.e as long
as a<=3), the statement within the loop will continue to be
executed over and over again.
Steps of Loop Execution
• Initialization occurs before the while statement.
• Loop entry occurs the moment the flow of control
reaches the first statement inside the loop body.
• Each time the body of the loop is executed, a pass
is made through the loop. This pass is called an
iteration.
• Before each iteration, the loop test is made at the
beginning of the loop.
• When the last iteration is complete, the flow of
control will be passed to the first statement after the
loop, which means the program has exited the
loop.
• The condition that causes the loop to exit is called
the exit condition.
Counter-Controlled Loops

// Loop 10 times (1, 2, ... 10)


loopCount = 1;
while (loopCount <= 10)
{
.
The number of times
. the loop will execute
. depends on
“loopCount”
loopCount++;
}
What will be the Output?
int main()
{
int count=0, total=0;
while(count<10)
{
count++;
total= total + count;
cout<<"count =
"<<count<<"total="<<total<<endl;
}
cout<<count;
return 0;
}
for Loop
• For loop is a counter-controlled repetition
structure
– Number of times the loop runs is controlled by a
variable
– In each iteration, the variable is incremented (or
decremented) as a counter
– The loop runs till a certain condition remains true. As
soon as the condition becomes false, the program
exits the loop
Variable
initialization

Condition

Loop Body

Variable
increment
for Loop

Syntax

• for ( initialization ; condition ; increment )


statement1;

• for ( initialization ; condition ; increment )


{statement1;
statement2;
statement3;
}
For Loop
Declaration + Condition
Initialization Increment

for ( int i = 1; i <= 10; i++ )


{ cout << i << " ";
}
1. Run the initialization statement.
2. Check the condition.
3. If condition is true, run the
loop.
Output: 4. After 1st iteration, perform
increment.
1 2 3 4 5 6 7 8 9 10 5. Check the condition, and if its
still true run the loop again..
And so on..
For Loop Header
for Loop

• If the control variable is declared while being initialized it


can be used only in the body of the for statement,
Declaration +
Initialization

for ( int i = 1; i <= 10; i++ )

– the control variable will be unknown outside the for


statement.
for Loop

• If the control variable is declared while being initialized it


can be used only in the body of the for statement,
for ( int i = 1; i <= 10; i++ )

– the control variable will be unknown outside the for


statement.
for Loop

• Similarly if a variable is declared inside the body of the loop, it


will also be unknown outside the for statement.

for ( i = 1; i <= 10; i++ )


{
int a = 10;
}

– This is called variable's scope. The scope of a


variable specifies where it can be used in a program.
For Loop
Any of the components of FOR loop may be null
• for( ; i< 10 ; i ++) // no initialization
• for(i =0 ; ; i ++) // no condition
• for(i=0; i <10 ; ) // no increment
• for( ; i < 10 ; ) // no initialization and increment
• for(x=0;x+y<10;x++)
How many times will these loops run?

• for ( ; ; ) • for ( ; ; )
{ statement1; { statement1;
statement2; if(condition)
} break;
}
For Loop

Any of the components of FOR loop may be null


• for( ; i< 10 ; i ++) // no initialization
• for(i =0 ; ; i ++) → Infinite (or forever) loop
• for(i=0; i <10 ; ) // no increment
• for( ; i < 10 ; ) // no initialization and increment
• for(x=0;x+y<10;x++)
How many times will these loops run?
• for ( ; ; ) • for ( ; ; )
{ statement1; { statement1;
statement2; if(condition)
} break;
}
For Loop

Any of the components of FOR loop may be null


• for( ; i< 10 ; i ++) // no initialization
• for(i =0 ; ; i ++) → Infinite (or forever) loop
• for(i=0; i <10 ; ) → Infinite (or forever) loop
• for( ; i < 10 ; ) // no initialization and increment
• for(x=0;x+y<10;x++)
How many times will these loops run?

• for ( ; ; ) • for ( ; ; )
{ statement1; { statement1;
statement2; if(condition)
} break;
}
Think-Pair-Share Activity
• Vary the control variable from 1 to 100 in increments of 1.
• Vary the control variable from 100 down to 1 in increments of -
1 (that is, decrements of 1).
• Vary the control variable from 7 to 77 in steps of 7.
• Vary the control variable from 20 down to 2 in steps of -2.
• Vary the control variable over the following sequence of
values: 2, 5, 8, 11, 14, 17, 20.
• Vary the control variable over the following sequence of
values: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0.
Class Activity
• Vary the control variable from 1 to 100 in increments of 1.
• for ( int i = 1; i <= 100; i++ )
• Vary the control variable from 100 down to 1 in increments of -1 (that is,
decrements of 1).

• Vary the control variable from 7 to 77 in steps of 7.

• Vary the control variable from 20 down to 2 in steps of -2.



• Vary the control variable over the following sequence of values: 2, 5, 8, 11,
14, 17, 20.

• Vary the control variable over the following sequence of values: 99, 88, 77,
66, 55, 44, 33, 22, 11, 0.
• Vary the control variable from 1 to 100 in increments of 1.
• for ( int i = 1; i <= 100; i++ )
• Vary the control variable from 100 down to 1 in increments of -1 (that is,
decrements of 1).
• for ( int i = 100; i >= 1; i-- )
• Vary the control variable from 7 to 77 in steps of 7.

• Vary the control variable from 20 down to 2 in steps of -2.



• Vary the control variable over the following sequence of values: 2, 5, 8,
11, 14, 17, 20.

• Vary the control variable over the following sequence of values: 99, 88,
77, 66, 55, 44, 33, 22, 11, 0.
• Vary the control variable from 1 to 100 in increments of 1.
• for ( int i = 1; i <= 100; i++ )
• Vary the control variable from 100 down to 1 in increments of -1 (that is,
decrements of 1).
• for ( int i = 100; i >= 1; i-- )
• Vary the control variable from 7 to 77 in steps of 7.
• for ( int i = 7; i <= 77; i += 7 )
• Vary the control variable from 20 down to 2 in steps of -2.

• Vary the control variable over the following sequence of values: 2, 5, 8,
11, 14, 17, 20.

• Vary the control variable over the following sequence of values: 99, 88,
77, 66, 55, 44, 33, 22, 11, 0.
• Vary the control variable from 1 to 100 in increments of 1.
• for ( int i = 1; i <= 100; i++ )
• Vary the control variable from 100 down to 1 in increments of -1 (that is,
decrements of 1).
• for ( int i = 100; i >= 1; i-- )
• Vary the control variable from 7 to 77 in steps of 7.
• for ( int i = 7; i <= 77; i += 7 )
• Vary the control variable from 20 down to 2 in steps of -2.
• for ( int i = 20; i >= 2; i -= 2 )
• Vary the control variable over the following sequence of values: 2, 5, 8,
11, 14, 17, 20.

• Vary the control variable over the following sequence of values: 99, 88,
77, 66, 55, 44, 33, 22, 11, 0.
• Vary the control variable from 1 to 100 in increments of 1.
• for ( int i = 1; i <= 100; i++ )
• Vary the control variable from 100 down to 1 in increments of -1 (that is,
decrements of 1).
• for ( int i = 100; i >= 1; i-- )
• Vary the control variable from 7 to 77 in steps of 7.
• for ( int i = 7; i <= 77; i += 7 )
• Vary the control variable from 20 down to 2 in steps of -2.
• for ( int i = 20; i >= 2; i -= 2 )
• Vary the control variable over the following sequence of values: 2, 5, 8,
11, 14, 17, 20.
• for ( int i = 2; i <= 20; i += 3 )
• Vary the control variable over the following sequence of values: 99, 88,
77, 66, 55, 44, 33, 22, 11, 0.
• Vary the control variable from 1 to 100 in increments of 1.
• for ( int i = 1; i <= 100; i++ )
• Vary the control variable from 100 down to 1 in increments of -1 (that is,
decrements of 1).
• for ( int i = 100; i >= 1; i-- )
• Vary the control variable from 7 to 77 in steps of 7.
• for ( int i = 7; i <= 77; i += 7 )
• Vary the control variable from 20 down to 2 in steps of -2.
• for ( int i = 20; i >= 2; i -= 2 )
• Vary the control variable over the following sequence of values: 2, 5, 8,
11, 14, 17, 20.
• for ( int i = 2; i <= 20; i += 3 )
• Vary the control variable over the following sequence of values: 99, 88,
77, 66, 55, 44, 33, 22, 11, 0.
• for ( int i = 99; i >= 0; i -= 11 )
What is this program doing?

int main() cout <<"\nType in a letter


{ from 'a' to 'e':";
int j; cin >>ch;
char ch='a'; }
for (j=0; j<5; j++) cout <<"\nThat's it!\n";
{ }
cout <<"\nType in a cout <<"Game's over!\n";
letter from 'a' to 'e':"; return 0;
cin >>ch; }
while( ch!= 'd')
{
cout <<"\nsorry "<<ch
<<" is incorrect.\n";
cout <<"Try again.\n";
Nested For Loop

• Using one looping construct inside another.


• Used when for one repetition of a process, many
repetitions of another process are needed.
• Some applications are
– to print patterns,
– find sum of a repeating series, etc.
Nested For Loop

• Eg. Pattern:
1
12
123
1234
Nested For Loop

• Eg. Pattern:
1
12
123
1234
• Logic:
– 4 levels ->
Nested For Loop

• Eg. Pattern:
1
12
123
1234
• Logic:
– 4 levels -> outer loop will run how many times?
Nested For Loop

• Eg. Pattern:
1
12
123
1234
• Logic:
– 4 levels → outer loop will run FOUR times! 0<i<4
Nested For Loop

• Eg. Pattern:
1
12
123
1234
• Logic:
– 4 levels → outer loop will run FOUR times! 0<i<4
→ Inner loop will run how many times?
int main()
{
for(int i=1;i<=4;i++)
{
for(int j=1;j<=i; j++)
{
cout<<j;
}
cout<<endl;
}
}
int main()
{
for(int i=4;i>0;i--)
{
for(int j=0;j<i; j++)
{
cout<<“*”;
}
cout<<endl;
}
}
Nested For Loop

• The outer loop runs the number of times the pattern has
to be repeated (in the above case 4 times). Thus it can
run from 1 to 4, from 4 to 1, from 2 to 6 etc.
• The inner loop depends on the values being displayed,
and often has to be related to the outer loop.
Nested For Loop

Syntax:
for(x=0;x<3;x++)
for(y=0;y<3;y++)
for(z=0;z<5;z++)
{ statement1;
statement2;
statement3;
}
Try Me!!

• What will be the output of this program?


for(x=1;x<=10;x++)
Output:
{for(y=1;y<=10;y++)
{z = x * y; 1 2 3 … … … … 10
cout <<z<<" "; 2 4 6 … … … … 20
3 6 9 … … … … 30
} . . .
cout <<endl; . . .
} . . .
10 20 30… … … … 100
Nested For Loop

• Total number of iterations in nested loops


• Total number of iterations =
x(max) * y(max)
In the previous example
• Total number of iterations = 10 x 10 =100
Using break to terminate a loop
#include <iostream>
using namespace std;
int main(){
int last_no,sum=0, current_no=1;
cout << "Enter a Positive Number: ";
cin >> last_no;
cout << "0";
while (true){
if (current_no > last_no)
break; // terminates the loop immediately
sum = sum + current_no;
cout<<"+"<<current_no;
current_no++;
}
cout << " = " << sum <<endl;
return 0;
}
Using break to terminate a loop
// prints all the Fibonacci numbers up to an input limit:
#include <iostream>
using namespace std;
int main(){
long bound;
cout << "Enter a positive integer: "; cin >> bound;
cout << "Fibonacci numbers < " << bound << " = 0,1";
long f0=0,f1=1;
while (true){
long f2 = f0 + f1;
if (f2 > bound)
break; // terminates the loop immediately
cout << "," << f2;
f0 = f1; f1 = f2;
}
cout<<endl;
return 0;
}
Using do…while loop
#include <iostream>
using namespace std;
int main()
{
unsigned char choice=0;
do
{
cout<<"\n Do U want exit [y,n]:";
cin >>choice;
}
while (choice!='y' && (choice!='Y'));

cout << "\n Bye Bye \n" ;


return 0;
}
Using do…while loop
#include <iostream>
using namespace std;
int main(){
long dividend, divisor;
char ch;
do // start of do loop
{ // do some processing
cout << "Enter dividend: "; cin >> dividend;
cout << "Enter divisor: "; cin >> divisor;
cout << "Quotient is " << dividend / divisor;
cout << ", remainder is " << dividend % divisor;
cout << "\n Do another? (y/n): "; //do it again?
cin >> ch;
}
while( ch != 'n' ); // loop condition
return 0;
}
Using continue and break
// Using Writing in Reverse
#include <iostream>
using namespace std;
int main(){
int n;
for (;;){
cout << "Enter int: "; cin >> n;
if (n%2 == 0)
continue; // Stay in Loop
if (n%3 == 0)
break; // Come out of loop
cout << "\n I m in loop \n";
}
cout << "\n I m outside of loop \n";
return 0;
}
Acknowledgement/References
• Slides contents taken from Ma’am Fatima Faruq

• Deital and Deital, “C++ How to Program”, Latest Edition

• Stroustrup, “Programming – Principles and Practice


Using C++”, Latest Edition

You might also like