Professional Documents
Culture Documents
EX: for each student in a class, the formula for determining the course
grade is the same.
C++ has three repetition (looping) structures that let you repeat statements
over and over until certain conditions are met. These are:
1. while loop
2. do while loop
3. for loop
1. while loop
The general form of the while statement is:
while is a reserved word.
the statement can be one or compound statement between {and}
It is called body of the loop.
Note that the parentheses around the expression are part of the syntax.
The expression acts as a decision maker and is usually a logical expression
and provides an entry condition.
If it initially evaluates to true, the statement executes. Then the expression is
then reevaluated.If it again evaluates to true, the statement executes again.
The statement continues to execute until the expression is no longer true.
A loop that continues to execute endlessly is called an infinite loop.
To avoid an infinite loop, make sure that the loops body contains statement(s)
that assure that the expression in the while loop will eventually be false.
EX1:
int i = 0;
while (i <= 20)
{
cout << i << \t;
i = i + 5;
//change it to print: 0 2 4 6 8 10 and 1 3 5 7 9 and 3 6 9
}
cout << "\n****************************"<<endl;
Sample Run:
0
5
10
15
20
The expression i <= 20 is evaluated first. Because it evaluates to true, the body of
the while loop executes next. The statement i = i + 5; changes the value of i
to 5. After executing the body of while loop, the expression is evaluated
again. Because i is 5, the expression evaluates to true and the body of the
while loop executes again.
This process of evaluating the expression and executing the body of the
while loop continues until the expression no longer evaluates to true.
Notes:
- When i becomes 25 will not be printed because the entry condition is false.
- If you omit the statement: i = i + 5;
you will have an infinite loop, continually printing rows of zero values.
- You must initialize the loop control variable i before you execute the loop.
Otherwise, you will have an infinite loop, continually printing rows of garbage values.
- If the 2 statements in the body of the loop are interchanged, itll alter the result. Such as:
int i = 0;
while (i <= 20)
{
//a semantic error because the condition is i <= 20 and it produces results for i > 20.
i = i + 5;
cout << i << \t;
}
cout << endl;
The output is:
5
10 15 20
25
5 minute question
What is the output of this program?
#include <iostream>
using namespace std;
int main()
{
int i = 20;
while (i < 20)
{
cout << i << " ";
i = i + 5;
}
cout << **********<<endl;
//wrong initialization
//initially the loop entry condition evaluates to false
//the body of the while loop will never execute
//there wont be any output
//the value of i remains 20
//the first statement that will be executed
return 0;
}
Before executing the body of the while loop, the counter is compared with N. If
counter < N, the body of the while executes.
The body of the loop continues to execute until the value of counter >= N.
Thus, inside the body of the while loop, the value of counter increments after it
reads a new item.
In this case, the while loop might look like the following:
EX: a program to add SOME entered numbers & find their average (you don't know how many integers)
#include <iostream>
using namespace std;
int main() {
int limit;
//store the number of the entered items
int number;
//variable to store the entered number
double sum = 0.0; //variable to store the sum
int counter = 0;
//loop control variable
MUST BE INITIALIZED BEFORE THE LOOP
cout << "Enter the number of integers in the list: ";
cin >> limit;
cout<<"Enter "<<limit<<"integers: "<<endl; //will be appeared once to the user as it is outside of the loop!
while (counter < limit)
//how many times this loop will be executed?
{
//start while
cin >> number;
sum = sum + number;
//sum+=number;
counter++;
}
//end of while
cout<<"The sum of the " <<limit<< " numbers = "<<sum<<endl; //note printing string vs variable!
double avg = sum/counter;
//declare a new needed variable, avg
cout << "The average = " << avg << endl;
return 0; }
Sample Run:
cout << "The total number of boxes sold: " << totalNumOfBoxesSold << endl;
cout << "Enter the cost of one box: ";
cin >> costOfOneBox;
cout <<\n The total money by selling cookies: $<< totalNumOfBoxesSold * costOfOneBox;
cout << \n The avg no. of boxes sold by each volunteer: << totalNumOfBoxesSold / counter << endl;
return 0; }
//A program to read some positive integers and average them, but you do not have a preset number of them.
//Suppose the number -999 marks the end of the entered integers.
#include <iostream>
using namespace std;
const int SENTINEL = -999;
int main() {
int number=0;
//variable to store the number
double sum = 0.0;
//variable to store the sum
int count = 0;
//variable to store the totalnumbers read
cout << "Enter integers ending with " << SENTINEL << endl;
cin >> number;
while (number != SENTINEL)
{
cout << "The sum of the " << count << " numbers is " << sum << endl;
cout << "The average is " << sum / count << endl;
return 0; }
The variable found, which is used to control the execution of the while loop,
is called a flag variable.
The program then prompts the user to guess the number. If the user guesses the
number correctly, the program outputs an appropriate message. Otherwise,
the program checks whether the guessed number is less than the random
number. If the guessed number is less than the random number generated by
the program, the program outputs the message Your guess is lower than the
number. Guess again!; otherwise, the program outputs the message Your
guess is higher than the number. Guess again!. The program then prompts
the user to enter another number. The user is prompted to guess the random
number until he enters the correct number.
To generate a random number, use the function rand() of the header file cstdlib.
EX: The expression rand() returns an int value between 0 and 32767.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int num = rand() % 100;
int guess;
bool isGuessed = false;
while (!isGuessed)
{
cout << "Enter an integer greater than or equal to 0 and less than 100: ";
cin >> guess;
if (guess == num)
{
cout << \n You guessed the correct number. << endl;
isGuessed = true;
//to exit from the loop
}
else if (guess < num) cout << "Your guess is lower than the number.\n Guess again! \n;
else cout << "Your guess is higher than the number. \n Guess again! << endl;
}
return 0;
}
Sample Run:
Enter an integer greater than or equal to 0 and less than 100: 45
Your guess is higher than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 20
Your guess is lower than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 35
Your guess is higher than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 28
Your guess is lower than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 32
You guessed the correct number.
In the previous examples, the expression in the while loop is quite simple
as it is controlled by a single variable.
However, there are situations where the expression in the while may be
more complex.
EX:
The previous program gives as many tries as the user needs to guess the
number. Suppose you want to give the user no more than five tries
to guess the number. If the user does not guess the number correctly
within five tries, then the program outputs the random number
generated by the program as well as a message that you have lost the
game.
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
The initial statement, loop condition, and update statement are enclosed within ( )
10
The initial statement is the first statement to execute and it is executed only
once.
EX1:
A program to print the first 10 nonnegative integers
#include <iostream>
using namespace std;
int main()
{
11
Sample run:
Hello!
*
Hello!
*
Hello!
*
Hello!
*
Hello!
Homework:
What will be the output if we omit the {} from the for loop?
EX3:
The action of the following for loop is empty !
for (i = 0; i < 5; i++);
// semantic error.
cout << "*" << endl;
The semicolon at the end of the for statement (before the output statement)
terminates the for loop.
12
EX4:
#include <iostream>
using namespace std;
int main()
{
for (int i = 10; i >= 1; i--)
cout << " " << i;
cout << endl;
return 0;
}
13
EX5:
You can increment (or decrement) the loop control variable by any fixed number.
In the following example, the variable is initialized to 1; at the end of the for loop, i is
incremented by 2. to outputs the first 10 positive odd integers.
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 20; i = i + 2)
cout << " " << i;
//simple statement
cout << endl;
//printed once only!
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
EX6:
14
EX7:
The loop condition evaluates to true, so the output statement executes, which outputs 10.
#include <iostream>
using namespace std;
int main()
{
for (int i = 10; i <= 10; i++)
cout << i << " ";
cout << endl;
return 0;
}
//////////////////////////////////////////////////////////////////////////
EX8:
If the loop condition is omitted from the for statement, the loop condition is always true.
This is an infinite loop.
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; ; i++)
cout << i << " ";
cout << endl;
return 0;
}
15
EX9:
In this example, a for loop reads five numbers and finds their sum and average.
#include <iostream>
using namespace std;
int main()
{
int i, newNum, sum = 0;
double average;
cout<<"please enter 5 numbers"<<endl;
for (i = 1; i <= 5; i++)
{
cin >> newNum;
sum = sum + newNum;
}
average = sum / 5;
cout << "The sum is " << sum << endl;
cout << "The average is " << average << endl;
return 0;
}
initial expression
while (expression)
{
statement
update expression
}
EX:
These for and while loops are equivalent:
for (int i = 0; i < 10; i++) cout << i << " ";
cout << endl;
int i = 0;
while (i < 10)
{
cout << i << " ";
i++;
}
cout << endl;
16
EX:
#include <iostream>
using namespace std;
int main()
{
int i = 0;
do
{
cout << i << " ";
i = i + 5;
}
while (i <= 20);
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
17
Because the while and for loops both have entry conditions, these loops
may never activate.
The do...while loop, on the other hand, has an exit condition and therefore
always executes the statement at least once.
b. #include <iostream>
using namespace std;
int main()
{
int i = 11;
do
{
cout << i << " ";
i = i + 5;
}
while (i <= 10);
cout << endl;
return 0;
}
18
If you do not know, and the program cannot determine in advance the
number of repetitions needed, and it could be zero, the while loop is
the right choice.
If you do not know, and the program cannot determine in advance the
number of repetitions needed, and it is at least one, the do...while
loop is the right choice.
19