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

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

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

View Full Document Right Arrow Icon
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; } }
Background image of page 1

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

View Full DocumentRight Arrow Icon
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 << “, ”;
Background image of page 2
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 &lt;&lt; Enter number or -1 to quit &lt;&lt; endl; cin &gt;&gt; num; while ( num != -1) { cnt++; sum = sum + num; cout &lt;&lt; Enter number or -1 to quit &lt;&lt; endl; cin &gt;&gt; num; } avg = sum /cnt; cout &lt;&lt; The sum is &lt;&lt; sum &lt;&lt; endl; cout &lt;&lt; The average is &lt;&lt; avg &lt;&lt; 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 &lt;&lt; Enter salary or -1 to quit &lt;&lt; endl; cin &gt;&gt; sal; largest = sal while (sal!= -1) { if (sal &gt; largest) largest = sal; cout &lt;&lt; Enter salary or -1 to quit &lt;&lt; endl; cin &gt;&gt; sal; } cout &lt;&lt; The largest salary is &lt;&lt; largest &lt;&lt; endl; CS 101 Introduction to Programming 2...
View Full Document

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 Right Arrow Icon
Ask a homework question - tutors are online