Download presentation
Presentation is loading. Please wait.
Published byJemima Harriet Warner Modified over 8 years ago
1
Infinite for Loop If you omit the test condition, the value is assumed to be TRUE so the loop will continue indefinitely unless you provide some other means of exiting.
2
Example 18 #include int main() { double value =0.0; double sum = 0.0; int i = 0; char indicator ='n'; for(;;) { cout <<endl <<"Enter a value:"; cin>>value; i++; sum +=value; cout <<endl <<"Do you want to enter another value (enter n to end)?"; cin>>indicator; if ((indicator == 'n') || (indicator == 'N')) break; } cout <<endl <<"The average of the " <<i <<" values you entered is " <<sum/i <<"." <<endl; return 0; }
3
Continue Statement Executing continue within a loop starts the next loop iteration immediately, skipping over any statements remaining in the current iteration.
4
Example19 #include int main() { int i=0, value=0,product=1; for (i=1; i<=10; i++) { cout <<"Enter value # " <<i <<endl; cout <<"\t\t" <<i <<" number is = "; cin>>value; if (value == 0) continue; product *= value; } cout <<endl; cout <<"Product (ignoring zero):" <<product <<endl <<endl; return 0; }
5
The while Loop A while loop causes the program to repeat a sequence of statements as long as the starting condition remains true. The general form of the while loop is while (condition) statement;
6
Example 20 #include int main() { double value =0.0, sum=0.0; int i=0; char indicator = 'y'; while (indicator =='y') { cout << endl <<"Enter a value:"; cin >> value; ++i; sum += value; cout <<endl <<"Do you want to enter another value (enter y for yes or n to end)?"; cin >> indicator; } cout <<endl <<"The average of the " << i <<" value you entered is " <<sum/i <<"." <<endl; return 0; }
7
Exercise Write a program that asks the user to enter a two digit grade (such as 80 or 75) and then display the corresponding single digit grade (such as 2 or 3). Use the following grade ranges: 90 - 100 = 460 - 69 = 1 80 - 89 = 359 and less = 0 70 - 79 = 2
8
Exercise Write a program which reads number from cin, and adds them, stopping when 0 has been entered. Construct two versions of this program, using for and while loop.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.