Control Structures
Control Structures
Quiz
• Make flowchart and pseudocode for the following problem:
• Take input from user and check whether the number entered by user
is positive, negative or zero. Display the result.
Writing Programs
• Control Structures control the flow of the program
• Any program can be written using the following control structures
• Sequence
• Selection
• Repetition
Sequence Structure
• Built into C++
Selection Structures
• Selection structures cause one section of code to be executed or not
depending on a conditional clause.
• Conditional operator (also called Ternary Operator)
• if statement
• switch statement
Decision: Using the switch statement
// demonstrates switch ... Case
#include <iostream>
using namespace std;
int main(){
int x,y; char op;
cout << "Enter two integers: "; cin >> x >> y;
cout << "Enter an operator [+,-,*,/,%]: "; cin >> op;
switch (op){
case '+': cout << x + y << endl; break;
case '-': cout << x - y << endl; break;
case '*': cout << x * y << endl; break;
case '/': cout << x / y << endl; break;
case '%': cout << x % y << endl; break;
default: cout <<"Invalid Operator \n";
}
return 0; }
Decision: Using the ? : statement
// demonstrates ? :
#include <iostream>
using namespace std;
int main(){
int m,n;
cout << "Enter two integers: ";
cin >> m >> n;
cout << ( m < n ? m : n ) << " is the minimum. \n";
return 0;
}
// The conditional expression ( m<n ? m : n ) evaluates
// to m if m < n, and to n otherwise.
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
Ref: Brig. Javed’s Lectures, MIT OCW, Deitel & Deitel
while Loop
Syntax:
while(condition)
{
statement1;
…
statement n;
}
while Loop
Initialization
Example: Output:
Condition
int a=1; 1
2
while(a<=3) 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;
}
What is this program doing?
int main() "<<ch <<" is incorrect.\n";
{ cout <<"Try again.\n";
int j; cout <<"\nType in a letter from
char ch='a'; 'a' to 'e':";
for (j=0; j<5; j++) cin >>ch;
{ }
cout <<"\nType in a cout <<"\nThat's it!\n";
letter from 'a' to 'e':"; }
cin >>ch; cout <<"Game's over!\n";
while( ch!= 'd') return 0;
{ }
cout <<"\nsorry
Repetition Structures
• Repetition structures specify that actions should be repeated while
some condition remains true
• while
• for
• do while
• Also called loops
• One run of a loop is called an iteration
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
Conditi
on
Loop Body
Variable
increment
for Loop
Syntax
• for ( initialization ; condition ; increment )
statement1;
• for ( initialization ; condition ; increment )
{statement1;
statement2;
statement3;
}
For Loop
Condition
Declaration +
Initialization Increment
for ( int i = 1; i <= 10; i++ ) 1. Run the initialization
{ cout << i << " "; statement.
2. Check the condition.
} 3. If condition is true, run the
loop.
4. After 1st iteration, perform
Output:
increment.
5. Check the condition, and if
1 2 3 4 5 6 7 8 9 10 its still true run the loop
again.. And so on..
For Loop Header
for Loop
• If the control variable
Declaration + is declared while being initialized it can be used
only in theInitialization
body of the for statement,
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;
}
Task
• 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.
• 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 )
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
2 4 6 … … … … 20
cout <<z<<" "; 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;
}