<< Chapter < Page | Chapter >> Page > |
statements;
}
The flow chart of the while statement is given below.
// this program computes the sum of 10 first integers starting from 1
#include<iostream.h>
int main()
{
const int N = 10
int sum = 0;
int count = 1; // initialize count
while (count<= N){
sum = sum + count;
count++; // increment count
}
cout<<“The sum is “<<sum<<endl;
return 0;
}
The output of the above program:
The sum is 55
In the above program, the loop incurs a counter-controlled repetition. Counter-controlled repetition requires:
#include<iostream.h>
int main()
{
int i;
i = 10;
while (i>= 1)
{
cout<<i<<" ";
i--; // subtract 1 from i
}
return 0;
}
The output of the above program:
Combining interactive data entry with the repetition capabilities of the while statement produces very adaptable and powerful programs.
// Class average program with counter-controlled repetition
#include<iostream.h>
int main()
{
int total, // sum of grades
gradeCounter, // number of grades entered
grade, // one grade
average; // average of grades
// initialization phase
total = 0;
gradeCounter = 1; // prepare to loop
while ( gradeCounter<= 10 ) { // loop 10 times
cout<<"Enter grade: "; // prompt for input
cin>>grade; // input grade
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter
}
// termination phase
average = total / 10; // integer division
cout<<"Class average is "<<average<<endl;
return 0;
}
The following is a sample run of the above program:
Enter grade: 98
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81
In programming, data values used to indicate either the start or end of a data series are called sentinels. The sentinel values must be selected so as not to conflict with legitimate data values.
Example
#include<iostream.h>
int main()
{
float grade, total;
grade = 0;
total = 0;
cout<<"\nTo stop entering grades, type in any number less than 0.\n\n";
cout<<"Enter a grade: ";
cin>>grade;
while (grade>= 0 )
{
total = total + grade;
cout<<"Enter a grade: ";
cin>>grade;
}
cout<<"\nThe total of the grades is "<<total<<endl;
return 0;
}
The following is a sample run of the above program:
To stop entering grades, type in any number less than 0.
Enter a grade: 95
Enter a grade: 100
Enter a grade: 82
Enter a grade: -2
The total of the grades is 277
The break statement causes an exit from the innermost enclosing loop statement.
Example:
while( count<= 10)
{
cout<<“Enter a number: “:
cin>>num;
if (num>76){
cout<<“you lose!\n”;
break;
}
else
cout<<“Keep on trucking!\n”;
count++;
}
//break jumps to here
Notification Switch
Would you like to follow the 'Programming fundamentals in c++' conversation and receive update notifications?