Loop Homework

 

 

 

 

1. Given the run of the following C++ code fragment if the user inputs 3, 7, 12, and 5

 

int n, times, total, curr;

cout << “How many times: “;

cin >> times;

total = 0;

for (n = 1; n <= times; n = n + 1)

{

cout << “Enter an int: “;

cin >> curr;

total = total + curr;

cout << curr << “ “ << total << endl;

}

 

2. What is printed by the following C++ program fragment if the user enters 27?

 

     divisor = 1;

     flag = 0;

 

     cout << "Please enter a number: ";

 

     cin >> num; //num is 27

 

     while ( !flag)

     {

          if ((num % divisor) == 0) flag = 1;

          divisor = divisor + 1;

          if (divisor == num) flag = 1;

          cout << "Help me please!" <<endl;

     }

     if (divisor == num) cout << "I hate computers!" << endl;

     else cout << "I love computers!"  << endl;

 

 


3.  What is printed by each of the following program fragments?

 

a) for (j = 20; j <= 5; j = j -4)

cout << "Again\n";

 

b) for (j = 10; j > 4; j--)

cout << j << ' ';

 

c)  

n = 5;

r = 1;

do{

cout << r << "**";

r = r + 2;

        }while (r <= n);

     cout << r;

 

d) for (i = 1; i <= 5; i++)

{

  for (j = 0; j < i; j++)\

       cout << '*';

  cout << endl;

}

 

 

 

4. Write the code fragment     (not a complete program)   that prints the first n positive integers, such that each integer is preceded by two asterisks. 

For example, if n = 3 then the output would be **1**2**3

                      if n = 5 then the output would be **1**2**3**4**5

 

 

5. What is printed by the following while loops?

 

a)         int m = 5;

     while (m >= 1)

     {

          cout << "m = " << m << endl;

          m = m - 2;

     }   

 

b)        sum = 8;

 

          while (sum < 10)

          {

              sum--;

              cout << "sum = " << sum;

          }