Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

What do the following loops print? Work out the answer by tracing the code, not

ID: 3555103 • Letter: W

Question

What do the following loops print? Work out the answer by tracing the code, not by using the computer. a. int s = 1; for (int n = 1; n <= 5; n++) { s = s + n; System.out.print(s + " "); }
b. int s = 1; for (int n = 1; s <= 10; System.out.print(s + " ")) { n = n + 2; s = s + n; } c. int s = 1; int n; for (n = 1; n <= 5; n++) { s = s + n; n++; } System.out.print(s + " " + n);

6.19 What do the following program segments print? Find the answers by tracing the code, not by using the computer.
a. int n = 1; for (int i = 2; i < 5; i++) { n = n + i; } System.out.print(n);
b. int i; double n = 1 / 2; for (i = 2; i <= 5; i++) { n = n + 1.0 / i; } System.out.print(i);
c. double x = 1; double y = 1; int i = 0; do { y = y / 2; x = x + y; i++; } while (x < 1.8); System.out.print(i);
d. double x = 1; double y = 1; int i = 0; while (y >= 1.5) { x = x / 2; y = x + y; i++; } System.out.print(i);

Explanation / Answer

What do the following loops print? Work out the answer by tracing the code, not by using the computer.

a. int s = 1; for (int n = 1; n <= 5; n++) { s = s + n; System.out.print(s + " "); }
   
   s = 1 + 1 = 2
   s = 2 + 2 = 4
   s = 4+ 3 = 7
   s = 7+ 4 = 11
   s = 11 +5 = 16
  
   2 4 7 11 16

b. int s = 1; for (int n = 1; s <= 10; System.out.print(s + " ")) { n = n + 2; s = s + n; }

   s = 1 + 3 = 4
   s = 4 + 5 = 9
   s = 9 + 7 = 16

   4 9 16

c. int s = 1; int n; for (n = 1; n <= 5; n++) { s = s + n; n++; } System.out.print(s + " " + n);
  
   s = 1+1 = 2
   s = 2 + 3 = 5
   s = 5 + 5 = 10
   n = 7
  
   10 7

6.19 What do the following program segments print? Find the answers by tracing the code, not by using the computer.

a. int n = 1; for (int i = 2; i < 5; i++) { n = n + i; } System.out.print(n);

   n = 1+2 = 3
   n = 3+3 = 6;
   n = 6+4 = 10;

  
   10

b. int i; double n = 1 / 2; for (i = 2; i <= 5; i++) { n = n + 1.0 / i; } System.out.print(i);

    i will be 6;
  
   6

c. double x = 1; double y = 1; int i = 0; do { y = y / 2; x = x + y; i++; } while (x < 1.8); System.out.print(i);

   y = 1/2
   x = 1 + 1/2 = 1.5
   i = 1
   y = 1/4
   x = 1.5 + 0.25 = 1.75
   i = 2
   y = 1/8
   x = 1.75 + 0.125 = 1.875
   i = 3
   since x > 1.8 loops breaks

   3

d. double x = 1; double y = 1; int i = 0; while (y >= 1.5) { x = x / 2; y = x + y; i++; } System.out.print(i);
since y is not greater than 1.5
i will be 0 and it prints 0

0

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote