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

37 Likes

Answer

Final value of q = 29.

Dry Run

mnpqRemarks
0000Assuming initial value of all variables to be zero.
2000First iteration of outer loop begins, m is initialized to 2.
2100First iteration of inner loop begins, n is initialized to 1.
2120p = 2 + 1 - 1 = 2
2126q = 0 + 2 + 4 = 6 as p%3 != 0
2226Second iteration of inner loop begins, n is incremented to 2.
2236p = 2 + 2 - 1 = 3
2239q = 6 + 3 = 9 as p%3 == 0
2339Inner loop terminates as n becomes greater than m.
3339Second iteration of outer loop begins, m is incremented to 3.
3139Inner loop restarts from first iteration, n is initialized to 1..
3139p = 3 + 1 - 1 = 3
31312q = 9 + 3 = 12 as p%3 == 0
32312Second iteration of inner loop begins, n is incremented to 2.
32412p = 3 + 2 - 1 = 4
32420q = 12 + 4 + 4 = 20 as p%3 != 0
33420Third iteration of inner loop begins, n is incremented to 3.
33520p = 3 + 3 - 1 = 5
33529q = 20 + 5 + 4 = 29 as p%3 != 0
43529Outer loop terminates as m becomes greater than 3, final value of q is 29.

Answered By

19 Likes


Related Questions