2Rewrite the following loop using an equivalent for loop int

2.Rewrite the following loop using an equivalent for loop.

int count = 0;

int i = 0;

int x = 0;

while (i < n) {

scanf(\"%d\", &x);

if (x == i) ++count;

++i;

}

3. Assume that the values of j, k,, x, y, and z are 6, 3, 4, 10, 3 respectively. What are the values of variables m, p, x after the following code segment is executed?

m = j-- + k--;

p = k + j;

y /= 2 * z + 2;

4. Rewrite the following code using a do-while loop with no decisions in the loop body.

sum = 0;

for (odd = 1; odd < n; odd = odd + 2)

sum = sum + odd;

printf(\"Sum of the positive odd numbers less than %d is %d\ \", n, sum);

In what situation, will the rewritten code print an incorrect sum?

Solution

Please find the answers below:

2) Equivalent representation in for loop is given below.

int count = 0;
   int x = 0;
   int i = 0;
   for(i=0; i<n; ++i){ //here the initialization i=0 is the first part, and condition inside while is given here as second part(i<n), and the post iteration ,ie, ++i is the third part of the for loop
scanf(\"%d\", &x);
if (x == i)
++count;
   }

3)

m = j-- + k--;

m = 6 + 3 = 9; (after this evaluation, the value of j will be decremented by 1, also k will be decremented by1. Thus j=5, k=2)

p = k + j;

p = 9 + 5 = 14;

y /= 2 * z + 2;

y = y / (2 * z + 2)

y = 10 / (2 * 3 + 2) = 10 / (6 + 2) = 10/8 = 1.25(if y is float) or 1 (if y is int)

Therefore after the execution of these statements, the values of m, p, and x are :

m = 9,

p = 14,

x = 4

4)

in do..while loop :

   sum = 0;
   odd = 1;
   do{
       sum = sum + odd;
       odd = odd + 2;
   }while(odd < n)
   printf(\"Sum of the positive odd numbers less than %d is %d\ \", n, sum);

This rewritten code will give incorrect sum in the cases where n < 1.

2.Rewrite the following loop using an equivalent for loop. int count = 0; int i = 0; int x = 0; while (i < n) { scanf(\
2.Rewrite the following loop using an equivalent for loop. int count = 0; int i = 0; int x = 0; while (i < n) { scanf(\

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site