CS201 In Class Exercise-ch5 (while loops) f2007 solution

# CS201 In Class Exercise-ch5 (while loops) f2007 solution -...

This preview shows pages 1–2. Sign up to view the full content.

While Loop (In Class Exercise) 1. If the boolean expression in a while loop statement is initially false, what happens? 2. Why does code within the loop body of a while loop statement need to affect the Boolean expression for the loop? 3. What is the output when the following programs are executed? a. int main() b. int main() { int N; { int K; N = 10; int Sum; while (N > 5) K = 0; { cout << N << " "; Sum = 0; N = N – 2; while (K <= 10) } { K = K + 2; } Sum = Sum + K; } cout << "K = " << K << "Sum = " << Sum << endl; } c. int main() d. int main() { int Small; { int B; int Large; B = 2; Small = 1; while (B < 100) Large = 20; { cout << B << " "; while (Small < Large) B = B * 2; { cout << Small + Large << endl; } Small = Small + 2; } Large = Large – 3; } }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
4. Using a while loop, write the statements to sum the integers from 1 to 20. Display the sum. cnt = 0; while (cnt < 20) { cnt ++; sum = sum + cnt; } cout << “The sum is “ << sum << endl; 5. Using a while loop, write the statements to produce this pattern: 3, 6, 9, . . . 27, 30 cnt = 0; while (cnt < 30) { cnt = cnt + 3; cout << cnt << “, ”;
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: } // there will be a comma at the end 27, 30, 6. Write a complete program to accept numbers from the user, one at a time and sum them, until he/she enters -1. Use display the sum and the average of the numbers entered. sum = 0; cnt = 0; cout << “Enter number or -1 to quit” << endl; cin >> num; while ( num != -1) { cnt++; sum = sum + num; cout << “Enter number or -1 to quit” << endl; cin >> num; } avg = sum /cnt; cout << “The sum is “ << sum << endl; cout << “The average is “ << avg << endl; 7. Write a program that accepts salaries from the user until he/she enters (-1). Use display the largest of the salaries entered. cout << “Enter salary or -1 to quit” << endl; cin >> sal; largest = sal while (sal!= -1) { if (sal > largest) largest = sal; cout << “Enter salary or -1 to quit” << endl; cin >> sal; } cout << “The largest salary is “ << largest << endl; CS 101 Introduction to Programming 2...
View Full Document

## This note was uploaded on 04/18/2008 for the course CS 201 taught by Professor Conway during the Fall '07 term at Bowling Green.

### Page1 / 2

CS201 In Class Exercise-ch5 (while loops) f2007 solution -...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online