05 LoopingAndFiles
05 LoopingAndFiles
int number = 6;
while (number <= 5)
{
cout << "Hello\n";
number++;
}
Watch Out for Infinite Loops
• 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
An Infinite Loop
int number = 1;
while (number <= 5)
{
cout << "Hello\n";
}
Using the while Loop for
Input Validation
Using the while Loop for
Input Validation
• Input validation is the process of
inspecting data that is given to the
program as input and determining whether
it is valid.
int x = 1;
do
{
cout << x << endl;
} while(x < 0);
• General Format:
1) Perform initialization
2) Evaluate test expression
– If true, execute statement
– If false, terminate loop execution
3) Execute update, then re-evaluate test
expression
for Loop - Example
int count;
int sum = 0;
for (int num = 0; num <= 10; num++)
sum += num;