Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

C - Iteration

Uploaded by

mod nod
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

C - Iteration

Uploaded by

mod nod
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Iterative Control Structure

• 1- For statement
• 2- Nested For
• 3- while statement
• 4- Usage of while
• 5- Avoid Infinite loop
• 6- do-while statement

(C) Copyright 2020 by Prof. Abeer ElKorany


C++ Iterative Constructs
• Iteration causing a set of statements (the
body) to be executed repeatedly.
• Mechanisms for deciding under what
conditions an action should be repeated
• Three constructs
• for statement
• while statement
• do-while statement

(C) Copyright 2020 by Prof. Abeer ElKorany


General terms of any iteration construct
• An iteration
- one complete execution of the body

• Loop entry
– The point where flow of control passes to the body

• Loop test (Loop condition)


- The point at which the decision is made to (re)enter
the body, or not

• Loop exit
- The point at which the iteration ends and control
passes to the next statement after the loop

(C) Copyright 2020 by Prof. Abeer ElKorany


1-The for statement
for (Initialization; Test ; Update)
statement; No
semicolon
or {block of statements} after for
statement

The main function is to repeat statement while condition remains true


1. Perform initialization (This is executed only once)
2. Evaluate test expression
If true, execute statement (body of for loop)
If false, terminate loop execution
3. Execute update, then re-evaluate test expression

(C) Copyright 2020 by Prof. Abeer ElKorany


Evaluated once
at the beginning
of the for
statements's ForInit
The ForExpr is
execution evaluated at the
start of each
iteration of the
loop
If ForExpr is ForExpr
true, Action is
executed true false

After the Action If ForExpr is


has completed, Action
false, program
the execution
PostExpression continues with
is evaluated next statement

PostExpr

After evaluating the


PostExpression, the next
iteration of the loop starts (C) Copyright 2020 by Prof. Abeer ElKorany
Example of Repetition
int num;

for ( num = 1 ; num <= 3 ; num++ )


{
cout << “Hello” << num <<endl;
}
(C) Copyright 2020 by Prof. Abeer ElKorany
num ?
Example of Repetition
int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << “Hello ” << num <<endl ;

OUTPUT

(C) Copyright 2020 by Prof. Abeer ElKorany


num 1 Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << “Hello” << num <<endl;

OUTPUT

(C) Copyright 2020 by Prof. Abeer ElKorany


num 1 Example of Repetition

int num;
true
for ( num = 1 ; num <= 3 ; num++ )

cout << “Hello ” << num<<endl ;

OUTPUT

(C) Copyright 2020 by Prof. Abeer ElKorany


num 1 Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << “Hello ” << num <<endl ;

OUTPUT
Hello 1

(C) Copyright 2020 by Prof. Abeer ElKorany


num 2 Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << “Hello ” << num <<endl ;

OUTPUT
Hello 1

(C) Copyright 2020 by Prof. Abeer ElKorany


num 2 Example of Repetition

int num;
true
for ( num = 1 ; num <= 3 ; num++ )

cout << “Hello ” << num <<endl ;

OUTPUT

Hello 1

(C) Copyright 2020 by Prof. Abeer ElKorany


num 2 Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << “Hello ” << num <<endl;

OUTPUT

Hello 1
Hello 2
(C) Copyright 2020 by Prof. Abeer ElKorany
num 3 Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << “Hello ” << num <<endl;

OUTPUT
Hello 1
Hello 2
(C) Copyright 2020 by Prof. Abeer ElKorany
num 3 Example of Repetition

int num;
true
for ( num = 1 ; num <= 3 ; num++ )

cout << “Hello ” << num <<endl;

OUTPUT
Hello 1
Hello 2
(C) Copyright 2020 by Prof. Abeer ElKorany
num 3 Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << “Hello ” << num <<endl;

OUTPUT

Hello 1
Hello 2
Hello 3
(C) Copyright 2020 by Prof. Abeer ElKorany
num 4 Example of Repetition

int num;

for ( num = 1 ; num <= 3 ; num++ )

cout << “Hello” << num <<endl ;

OUTPUT

Hello 1
Hello 2
Hello 3 (C) Copyright 2020 by Prof. Abeer ElKorany
num 4 Example of Repetition

int num;
false
for ( num = 1 ; num <= 3 ; num++ )

cout << “Hello ” << num <<endl ;

OUTPUT

Hello 1
Hello 2
Hello 3
(C) Copyright 2020 by Prof. Abeer ElKorany
Simple For Example
i 0
Example
for (int i = 0; i < 3; ++i) i 1

{ i 2
cout << "i is " << i << endl;
i 3
}
cout << "all done" << endl;
i is 0
i is 1
This code produces
i is 2
all done
(C) Copyright 2020 by Prof. Abeer ElKorany
#include <iostream>
using namespace std;
int main()
{
const int MIN_NUMBER = 1, // Starting value
MAX_NUMBER = 10; // Ending value
int num;
cout << "Number\t Number Squared\n";
cout << "-------------------------\n";
for (num = MIN_NUMBER; num <= MAX_NUMBER; num++)
cout << num << "\t\t" << (num * num) << endl;

return 0;
}

(C) Copyright 2020 by Prof. Abeer ElKorany


The for statement(cont.)
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main () int main ()
{ {
int n; int n;
for (n=10; n>0 ; n--) for (n=0; n<10 ; n++)
cout << n << " , "; cout << n << " , ";
cout << "FIRE!"; cout<<endl;
return 0; return 0;
} }

(C) Copyright 2020 by Prof. Abeer ElKorany


The for statement (cont.)
0 1
#include <iostream> 2 2
4 4
using namespace std; Step greater 6 8
int main () 8 16
than 1 10 32
{ 12 64
14 128
const int TableSize = 20; 16 256
18 512
int Entry = 1; 20 1024
for (int i = 0; i <= TableSize; i=i+2)
{
cout << i << "\t\t" << Entry << endl;
Entry *= 2;
}

return 0;
}
(C) Copyright 2020 by Prof. Abeer ElKorany
The for statement (cont.)
More than one control variable in for loop
#include <iostream>
95% 11=7
using namespace std; This code produces
92% 12=8
int main)(
89% 13=11
{
86% 14=2
int n,m; 83% 15=8
for (m=95, n=11; m%n > 0; n++)
{
cout << m << "%" << n << " = " << m%n << endl;
m-=3;
}
return 0;
}
(C) Copyright 2020 by Prof. Abeer ElKorany
#include <iostream>
using namespace std;
The for statement (cont.)
int main()
{
int x;
for (x = 3 ; x < 13 ; x++)
{
switch (x)
{
case 3 : cout<<"The value is three\n"; break;
case 4 : cout<<"The value is four\n"; break;
case 5 :
case 6 :
case 7 :
case 8 : cout<<"The value is between 5 and 8\n"; break;
case 11 : cout<<"The value is eleven\n";break;
default : cout<<"It is one of the undefined values\n";break;
} /* end of switch */
} /* end of for loop */
return 0; (C) Copyright 2020 by Prof. Abeer ElKorany
}
• The value is three
• The value is four
• The value is between 5 and 8
• The value is between 5 and 8
• The value is between 5 and 8
• The value is between 5 and 8
• It is one of the undefined values
• It is one of the undefined values
• The value is eleven
• It is one of the undefined values

(C) Copyright 2020 by Prof. Abeer ElKorany


Common errors in constructing
for Statements
for (j = 0, j < n, j = j + 3)

// commas used when semicolons needed

for (j = 0; j < n)

// three parts needed

for (j = 0; j >= 0; j++)

?????what is wrong here ?????

for (j=0, j=10; j++);

(C) Copyright 2020 by Prof. Abeer ElKorany


Nesting For Loops
Row col
#include <iostream> 1 1 2 3
using namespace std; 2 1 2 3
int main() 3 1 2 3

{
int row,col;
for (row=1; row<=3; row++) //outer
{
Output is
for (col=1; col<=3; col++)//inner 1 2 3
cout << row * col << "\t ";
2 4 6
cout<< endl;
} 3 6 9
return 0;
}

(C) Copyright 2020 by Prof. Abeer ElKorany


Nesting For Loops(cont.)
xxxxxxxxx
xxxxxxxxx
#include <iostream> xxxxxxxxx
using namespace std; xxxxxxxxx
xxxxxxxxx
int main () xxxxxxxxx
xxxxxxxxx
{ xxxxxxxxx
xxxxxxxxx
for (int n=1; n <10 ; n++)
{
for (int x=1; x <10 ; x++)
cout << “X ";
cout << “\n ";
}
return 0;
} (C) Copyright 2020 by Prof. Abeer ElKorany
Nested Loops
int row,col;
for (row = 0; row < 5; row++)
{
cout << "\n" <<row; //throws a new line
for (col = 1; col <= 3; col++)
{
cout <<"\t" << col;
Output
} 0 1 2 3 **
cout << "\t**"; //use of tab
1 1 2 3 **
}
2 1 2 3 **
3 1 2 3 **
4 1 2 3 **
(C) Copyright 2020 by Prof. Abeer ElKorany
Nesting For Loops(cont.)
What is the output of this program:
#include <iostream>
*
using namespace std;
**
int main() ***
{ ****
int i,j; *****
for(i=1; i<=6; i++)
{
for(j=1; j<i; j++)
cout<<"*";
cout<<"\n";
}
return 0;
} (C) Copyright 2020 by Prof. Abeer ElKorany
2- The while loop
while (expression)
statement;
or {block of statements}
Repetition structure
– Action repeated while some condition remains true
expression is evaluated
if true, then statement is executed, and expression is evaluated again
if false, then the loop is finished and program statements following
statement execute
Example: true
product <= 1000 product = 2 * product
int product = 2;
while ( product <= 1000 ) false

product = 2 * product;
(C) Copyright 2020 by Prof. Abeer ElKorany
#include <iostream>
loop control variable
using namespace std;
pls enter the max number 4
int main()
{
Number Number Squared
const int MIN_NUMBER = 1; 1 // Starting number to square 1
int MAX_NUMBER ; 2 // Maximum number to square 4
int num = MIN_NUMBER; //3Counter: a variable that must be initialized 9
before entering loop

cout<< "pls enter the max number ";


4 16
cin >> MAX_NUMBER;
cout<< "Number \t Number Squared\n";
while (num <= MAX_NUMBER)
{
cout << num << "\t\t" << (num * num) << endl;
num++; //incremented or decremented each time a loop repeats

}
return 0;
}

(C) Copyright 2020 by Prof. Abeer ElKorany


The while Loop – How It Works
while (expression)
statement;
• expression is evaluated
– if true, then statement is executed, and
expression is evaluated again
– if false, then the loop is finished and program
statements following statement execute

(C) Copyright 2020 by Prof. Abeer ElKorany


The While loop Example
#include <iostream>
using namespace std;
int main ()
{
int n;
cout << "Enter the starting number > ";
cin >> n;
while (n> 0)
{cout << n-- << “\n";
cout << "FIRE!";}
return 0;
} (C) Copyright 2020 by Prof. Abeer ElKorany
2- Usage of While loop
Input Validation Example
cout << "Enter a number less than 10: ";
cin >> number;
while (number >= 10)
{
cout << "Invalid Entry!"
<< "Enter a number less than 10: ";
cin >> number;
}

(C) Copyright 2020 by Prof. Abeer ElKorany


2- Usage of While loop(cont.)
Multiple Statements in a while Loop
#include <iostream>
#include <iomanip> //for setw
using namespace std; 1 1
2 16
int main() 3 81
4 256
{ 5 625
6 1296
int pow=1; 7 2401 //power initially 1
8 4096
int numb=1; 9 6561 //numb goes from 1 to ???
while( pow<10000 ) //loop while power <= 4 digits
{
cout << setw(2) << numb; //display number
cout << setw(5) << pow << endl; //display fourth power
++numb; //get ready for next power
pow = numb*numb*numb*numb; //calculate fourth power
}
cout << endl;
return 0;
} (C) Copyright 2020 by Prof. Abeer ElKorany
#include <iostream> 2- Usage of While loop(cont.)
using namespace std;
int main()
{ int total = 0, int GoOn = 1, /* initialize flag */
int thisGrade;
while ( GoOn == 1 )
{
cout <<" Enter Grade, -1 to quit ";
cin>> thisGrade ;
if ( thisGrade == -1 )
GoOn = 0 ; /* change flag value */
else {
total = total + thisGrade ;
}
}
cout <<" Total is \n "<< total << endl;
}
(C) Copyright 2020 by Prof. Abeer ElKorany
#include <iostream>
2- Usage of The While loop(cont.)
#include <iomanip>
using namespace std;
int main()
{
int grade,total=0,gradeCounter=0;
double average;
cout << "Enter grade, -1 to end: ";
cin >> grade; // read grade from user
while ( grade != -1 ) {
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter
cout << "Enter grade, -1 to end: "; // prompt for input
cin >> grade; // read next grade
}
if ( gradeCounter != 0 )
average = total / gradeCounter;
cout << "Class average is " << setprecision(2)<<average << endl;
else
cout << "No grades were entered" << endl;
return 0;
}
(C) Copyright 2020 by Prof. Abeer ElKorany
#include <iostream>
using namespace std;
int main()
{ const int MIN= 9, MAX = 15;
int players, teamPlayers,numTeams,leftOver; // Number of available players
cout << "How many players do you wish per team? "; // Get the number of players per team.

cin >> teamPlayers;


while (teamPlayers < MIN || teamPlayers > MAX) // Validate the input.
{
cout << "You should have at least " << MIN << " but no more than " << MAX << " per team.\n";
cout << "How many players do you wish per team? "; // Get the input again.

cin >> teamPlayers;


}
cout << "How many players are available? "; // Get the number of players available.

cin >> players;


while (players <= 0) { // Get the input again.
cout << "Please enter 0 or greater: ";
cin >> players; }
numTeams = players / teamPlayers; // Calculate the number of teams.
leftOver = players % teamPlayers; // Calculate the number of leftover players.
cout << "There will be " << numTeams << " teams with " << leftOver << " players left over.\n"; // //Display the results
return 0;
}
(C) Copyright 2020 by Prof. Abeer ElKorany
Watch Out for Infinite Loops
The while loop should contains the following:
• an initialization of the loop control variable
• an expression to test for continuing the loop
• an update of the loop control variable to be executed with
each iteration of the body
• The loop must contain code to make expression
become false
• Otherwise, the loop will have no way of stopping
• Such a loop is called an infinite loop, because it will
repeat an infinite number of times

(C) Copyright 2020 by Prof. Abeer ElKorany


Example of an Infinite Loop

int number = 1;
while (number <= 5)
{
cout << "Hello\n";
}

(C) Copyright 2020 by Prof. Abeer ElKorany


3-The do-while loop.
• Similar to while structure
– a posttest loop – execute the loop, then test the
expression( test at end, not beginning)
– Loop body executes at least once even if condition is
never fulfilled
– Note that a semicolon is required after (expression)
• Format action(s)
do {
statement
} while ( condition ); true
condition

false

(C) Copyright 2020 by Prof. Abeer ElKorany


3-The do-while loop (cont.)
#include <iostream>
using namespace std;
int main)(
{
// prints the sum of the first n integers for an input n:
int n, i=0;
cout << "Enter a positive integer;" :
cin >> n;
int sum=0; Enter a positive integer, 9
do The sum of the first 9 integers is 45
sum += i++;
while (i <= n);
cout << "The sum of the first " << n << " integers is " <<sum << endl;
return 0;
}

(C) Copyright 2020 by Prof. Abeer ElKorany


#include <iostream>
using namespace std;
int main()
{
int score1, score2, score3; // Three scores
double average; // Average score
char again; // To hold Y or N input
do
{ // Get three scores.
cout << "Enter 3 scores and I will average them: ";
cin >> score1 >> score2 >> score3;
average = (score1 + score2 + score3) / 3.0;
cout << "The average is " << average << ".\n";
cout << "Do you want to average another set? (Y/N) ";
cin >> again;
} while (again == 'Y' || again == 'y');
return 0;
}
(C) Copyright 2020 by Prof. Abeer ElKorany
Difference between while/do- while Loop
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main() int main()
{ {
int x = 1 ; int x = 1 ;
int n = 0 ; int n = 0 ;
while ( x<=5) do {
{ x++;
x++; n += x ;
n += x ; } while (x<=5);
} cout<<“N is “<< n<<endl;
cout<<“N is “<< n<<endl; return 0;
return 0;
} (C) }Copyright 2020 by Prof. Abeer ElKorany
Break and Continue statement
• break statement
– Immediate exit from while, for, do/while, switch
– Program continues with first statement after structure
• Common uses
– Escape early from a loop
– Skip the remainder of switch
• continue statement
– Used in while, for, do/while
– Skips remainder of loop body
– Proceeds with next iteration of loop

(C) Copyright 2020 by Prof. Abeer ElKorany


The break Statement
int j = 40;
while (j < 80){
j += 10;
if (j == 70)
break;
cout << “j is “ << j<< ‘\n’;
}
cout << “We are out of the loop as j=70.\n”;

j is 50
j is 60
We are out of the(C)loop
Copyrightas
2020j=70.
by Prof. Abeer ElKorany
The continue Statement
int j = 40;
while (j < 80){
j += 10;
if (j == 70)
continue; //skips the 70
cout << “j is “ << j<< ‘\n’;
}
cout << “We are out of the loop” << endl;
j is 50
j is 60
j is 80
We are out of the loop.
(C) Copyright 2020 by Prof. Abeer ElKorany
Break and Continue statement (cont.)
#include <iostream>
using namespace std;
int main()
{
int x;
for(x = 5 ; x < 15 ; x ++)
{
if (x == 8)
break;
cout<<"In the break loop, x is \t"<< x<<"\n";
}
cout<< "\n";
for (x = 5 ; x < 15 ; x ++)
{
if (x == 8)
continue;
cout<<"In the continue loop, x is \t" <<x<<"\n";
}
return 0;
(C) Copyright 2020 by Prof. Abeer ElKorany
}
Program output:
In the break loop, x is 5
In the break loop, x is 6
In the break loop, x is 7

In the continue loop , x is 5


In the continue loop , x is 6
In the continue loop , x is 7
In the continue loop , x is 9
In the continue loop , x is 10
In the continue loop , x is 11
In the continue loop , x is 12
In the continue loop , x is 13
In the continue loop , x is 14

(C) Copyright 2020 by Prof. Abeer ElKorany

You might also like