Lecture 05 Loops 2014
Lecture 05 Loops 2014
Lecture 5
Repetition Structure
boolean
expr
false
true
statements
next statement
}
next statement;
5
Infinite Loops
An infinite loop is one in which the
10
11
#include <iostream>
using namespace std;
int main()
{
int number, sum, cnt;
//Initialization
cout << Enter a list of integers terminated by 99;
cin >> number;
//first number
sum = 0;
cnt = 0;
while (number != -99) //Loop to sum and count values
{
sum += number;
++cnt;
cin >> number;
//Read next number
} //while
//Calculate and print average
cout << The average is << sum/float(cnt);
return 0;
} //main
12
i=1;
while (i <= 10)
{
14
Example
Print the numbers from 100 to 10 as follows;
10090
80
70
--------- 10
15
16
Nesting of Loops
The statements in the loop body may be any
I=I+1
I <=5
next statement
K=1
K=K+1
K <=3
cout<<I<<,<<K
20
Loop
statement
do
statement;
while (bool expr);
true
bool
expr
false
Next statement
do
{
statement 1;
statement 2;
}while (bool expr);
21
22
Notes on semantics of
Do While Loop
At least one of the variables in the boolean
24
25