Loop Repetition Loop Int Main : Repetition Structure, Counter Controlled Repetition
Loop Repetition Loop Int Main : Repetition Structure, Counter Controlled Repetition
Loop = repetition
While loop
int main ()
{….
…..
int c = 1; // 1- counter initialization
while ( c < = 5) // 2- counter condition
{ cout << c << “ Hello\n” ;
c = c + 1; // 3- counter modification
}
cout << “Bye”;
cout << c ; // 6
return 0;
}
No: repetition but one time seletion : if ( c <=5)
cout << ”hello”;
Run:
Hello
Hello
Hello
Hello
Hello
Bye
6
cout << c <<“ Hello\n” ;
1 Hello
2 Hello
3 Hello
4 Hello
5 Hello
Bye
6
Infinite loop (no counter modification)
int c = 1 ; // 1- counter initialization
while ( c < = 5) // 2- counter condition
{ cout << c << “ Hello\n” ;
}
Run:
1 hello
1 hello
1 hello
1 hello
1 hello
1 hello
1 hello
……. to infinity
Counting downward
int c = 10 ; // 1- counter initialization
while ( c >= 1) // 2- counter condition
{ cout << c << “ Hello\n” ;
c = c + 1; // 3- counter modification
}
---------------------------
NB: We should make sure that the counter modification will lead to a false
condition in order to stop the repetition.
the below repetition will not stop theoretically (it will stop when the memory
reserved for the variable c will overflow)
int c = 10 ; // 1- counter initialization
c = c + 1; // 3- counter modification
}
Int total = 0
int c = 1; // counter initialization
while ( c < = 3) // counter condition
{ cout << “please enter a no”;
Take the grade;
Add the grade to the total
c = c + 1; // counter modification
}
Cout << “ the average is …….
int garde, total = 0;
int c = 1; // 1- counter initialization
while ( c < = 3) // 2- counter condition
{ cout << “Please enter a grade: ”;
cin >> grade;
total = total + grade; //0+ 75, 75+85=160, 160+80=240
c = c + 1; // 3- counter modification
}
Cout << “The average is” << total/3;
if (x < 10)
if (y > 10)
cout<<”***\n”;
else
cout<<”###\n”;
cout<<”$$$\n”;
if (x < 10)
if (y > 10) // this is the statement to be executed when the above if is true
cout<<”***\n”;
else
cout<<”###\n”;
cout<<”$$$\n”;
x is 9, y is 9 x is 9 , y is 11 x is 11 , y is 9 x is 11, y is 11
$$$ $$$
if (x < 10)
if (y > 10)
cout<<”***\n”;
else
{ cout<<”###\n”;
cout<<”$$$\n”; }
x is 9, y is 9 x is 9 , y is 11 x is 1 1 , y is 9 x is 11, y is 11
$$$
if (x < 10)
{ if (y > 10)
cout<<”***\n”; }
cout<<”###\n”;
cout<<”$$$\n”;
x is 9, y is 9 x is 9 , y is 11 x is 11 , y is 9 x is 11, y is 11