80 likes | 222 Views
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. Example 18. #include<iostream.h> int main() { double value =0.0; double sum = 0.0; int i = 0; char indicator ='n';
E N D
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.
Example 18 #include<iostream.h> 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; }
Continue Statement • Executing continue within a loop starts the next loop iteration immediately, skipping over any statements remaining in the current iteration.
Example19 #include<iostream.h> 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; }
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;
Example 20 #include<iostream.h> 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; }
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 = 4 60 - 69 = 1 80 - 89 = 3 59 and less = 0 70 - 79 = 2
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.