Computer Science
State the final value of q at the end of the following program segment after execution. Show the dry run.
for(m=2;m<=3;++m)
{
for(n=1;n<=m;++n)
{
p=m+n-1;
if(p%3 == 0)
q += p;
else
q += p+4;
}
}
Java
Java Iterative Stmts
38 Likes
Answer
Final value of q = 29.
Dry Run
m | n | p | q | Remarks |
---|---|---|---|---|
0 | 0 | 0 | 0 | Assuming initial value of all variables to be zero. |
2 | 0 | 0 | 0 | First iteration of outer loop begins, m is initialized to 2. |
2 | 1 | 0 | 0 | First iteration of inner loop begins, n is initialized to 1. |
2 | 1 | 2 | 0 | p = 2 + 1 - 1 = 2 |
2 | 1 | 2 | 6 | q = 0 + 2 + 4 = 6 as p%3 != 0 |
2 | 2 | 2 | 6 | Second iteration of inner loop begins, n is incremented to 2. |
2 | 2 | 3 | 6 | p = 2 + 2 - 1 = 3 |
2 | 2 | 3 | 9 | q = 6 + 3 = 9 as p%3 == 0 |
2 | 3 | 3 | 9 | Inner loop terminates as n becomes greater than m. |
3 | 3 | 3 | 9 | Second iteration of outer loop begins, m is incremented to 3. |
3 | 1 | 3 | 9 | Inner loop restarts from first iteration, n is initialized to 1.. |
3 | 1 | 3 | 9 | p = 3 + 1 - 1 = 3 |
3 | 1 | 3 | 12 | q = 9 + 3 = 12 as p%3 == 0 |
3 | 2 | 3 | 12 | Second iteration of inner loop begins, n is incremented to 2. |
3 | 2 | 4 | 12 | p = 3 + 2 - 1 = 4 |
3 | 2 | 4 | 20 | q = 12 + 4 + 4 = 20 as p%3 != 0 |
3 | 3 | 4 | 20 | Third iteration of inner loop begins, n is incremented to 3. |
3 | 3 | 5 | 20 | p = 3 + 3 - 1 = 5 |
3 | 3 | 5 | 29 | q = 20 + 5 + 4 = 29 as p%3 != 0 |
4 | 3 | 5 | 29 | Outer loop terminates as m becomes greater than 3, final value of q is 29. |
Answered By
19 Likes
Related Questions
Rewrite the following using for loop:
int i = 1, f = 1; do { f=f*i; i++; } while(i<=10); System.out.println(f);
Rewrite the following using for loop:
a=1; while(a<=5) {b = 1; while(b<=a) { System.out.print(b); b++; } System.out.println(); a++; }
Write the following statement using switch case construct.
if (a==1) { b += 10; System.out.println(b); } else if (a == 2) { b -= 10; System.out.println(b); } else { b *= a; System.out.println(b); }
What is meant by statement? Name the different types of statements which are used in Java programming.