What will be the values of variables 'P' and 'Q' after the execution of the following code-

Solution and detailed answer shared after three hours. Comment your answer below!

Take this opportunity to master your Arduino coding skills!

UPDATE- Here's the SOLUTION-

So lets deal with the value of P first-

1. Notice that the only place we are altering the value of P is in the definition of the for loop i.e-

2. The value of P will get incremented till satisfies the condition, P<=4.

Which means when the value of P becomes 5, the loop will terminate.

Hence the

Now, moving on the find the value of Q-

For a quick recap, this is how for loops work-

This is just another way of writing,

So in every iteration, two things happen-

1. The new value of Q becomes the value of Q + the present value of P.

2. One is subtracted from the value of Q.

So in the first iteration, initially, P=0 and Q=0.

Which, after the execution of the loop becomes P=1 and Q=0.

Second iteration,

P=2 and Q=1.

Third Iteration-

P=3 and Q=4.

Fourth iteration-

p=4 and Q=6.

Fifth iteration-

P=5 and Woops! The condition P<=4 is no longer satisfied, so the loop terminates here. Hence, the value of Q=6.

int P,Q=0; for(P=1; P<=4; P++) { Q+=P; Q--; }

Solution and detailed answer shared after three hours. Comment your answer below!

Take this opportunity to master your Arduino coding skills!

UPDATE- Here's the SOLUTION-

**The value of P will be 5 and the value of q will be 6**. If you've answered it correctly, congrats! If not, no worries, continue reading below to understand the question better.So lets deal with the value of P first-

1. Notice that the only place we are altering the value of P is in the definition of the for loop i.e-

for(P=1; P<=4; P++)

2. The value of P will get incremented till satisfies the condition, P<=4.

Which means when the value of P becomes 5, the loop will terminate.

Hence the

**value of P will be 5**.Now, moving on the find the value of Q-

For a quick recap, this is how for loops work-

And incase you're new to this,

Q+=P;

This is just another way of writing,

Q=Q+P;

1. The new value of Q becomes the value of Q + the present value of P.

2. One is subtracted from the value of Q.

So in the first iteration, initially, P=0 and Q=0.

Which, after the execution of the loop becomes P=1 and Q=0.

Second iteration,

P=2 and Q=1.

Third Iteration-

P=3 and Q=4.

Fourth iteration-

p=4 and Q=6.

Fifth iteration-

P=5 and Woops! The condition P<=4 is no longer satisfied, so the loop terminates here. Hence, the value of Q=6.

## Comments

## Post a Comment