7th Lecture
7th Lecture
1
While
• The statement that is repeated is known as the body of the loop. It is also
considered a conditionally executed statement, because it is executed only under
the condition that the expression is true.
number = 0;
2
While - Pretest loop
• The while loop is known as a pretest loop, which means it tests its expression
before each iteration.
• The number variable is initialized with the value 0. If number had been initialized
with the value 5 or greater, as shown in the following program segment, the loop
would never execute:
3
While
• If a loop does not have a way of stopping, it is called an infinite loop. An infinite
loop continues to repeat until the program is interrupted.
• Ex: program to read a set of numbers and it finds the average of the even numbers.
The set of numbers is finished with a value 55.
4
Do While
• The do-while loop is a posttest loop, which means its expression is tested after
each iteration.
5
Do While
• The do-while loop is a posttest loop. As a result, the do-while loop always
performs at least one iteration, even if the expression is false to begin with. This
differs from the behavior of a while loop, which you will recall is a pretest loop.
6
Do While
• This program averages 3 test scores. It repeats as many times as the user wishes.
7
Do While
8
Infinite loop
• An infinite loop continues to repeat until the program is interrupted.
9
Random values
#include <cstdlib>
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
int lb = 20, ub = 100;
srand(time(0));
// This program will create some sequence of random
// numbers on every program run within range lb to ub
for (int i = 0; i < 5; i++)
cout << (rand() % (ub - lb + 1)) + lb << " ";
return 0;
}
10
Examples
• A program to read set of characters and finds number of capital letters, small letters,
special characters. The program asks the users “do you want to continue or not”, if the
answer is “N”, the program will stop.
• Using while and do-while write program to compute the factorial value of a number.
11
The End
12