50 likes | 182 Views
CS 1400. Chapter 5, section 2. Loops!. while ( rel-expression ) while ( rel-expression ) { statements statement }. if the relational-expression is true, execute the statement(s) then repeat. (This is a pre-test loop). Example.
E N D
CS 1400 Chapter 5, section 2
Loops! while (rel-expression) while (rel-expression) { statements statement } if the relational-expression is true, execute the statement(s) then repeat. (This is a pre-test loop)
Example • Convert a list of temperatures from Fahrenheit to Centigrade. • int main() • { float fahr; • char continue = ‘Y’; • while (continue == ‘Y’) • { cout << “Enter a temperature: “; • cin >> fahr; • cent = 5.0/9.0 * (fahr-32.0); • cout >> “centrigrade conversion is: “ << cent << endl; • cout >> “Enter Y to continue…”; • cin >> continue; • } • }
Counting loops • Convert exactly 5 temperatures to centigrade… • int main() • { float fahr; • int count = 0; • while (count < 5) • { cout << “Enter a temperature: “; • cin >> fahr; • cent = 5.0/9.0 * (fahr-32.0); • cout >> “centrigrade conversion is: “ << cent << endl; • count = count + 1; • } • }
Examples… • Write a program to output the sum of a list of positive numbers provided by the user. • Modify the above program to output the average of a list of positive numbers provided by the user. • Write a program that prompts the user to enter an age in the range 18 to 25. Re-prompt the user if an invalid age is entered.