Why is 'i' equal to 7?I know it's super simple but can anyone help me?

Joined
Feb 11, 2023
Messages
1
Reaction score
0
#include <stdio.h>
int main() {
int a = 0,i;
for(i = 1;i <= 6;i++)
a += 2*i;
printf("a = %d\t i = %d\n",a,i);


return 0;
}
 
Joined
Mar 5, 2023
Messages
36
Reaction score
12
In the provided code snippet, the value of 'i' is not set to 7 anywhere in the code. Instead, 'i' is initialized to 1 and incremented by 1 in each iteration of the 'for' loop until it reaches 6.

In the loop, 'a' is being updated by adding 2 times the current value of 'i' in each iteration. After the loop completes, the value of 'a' will be equal to 2+4+6+8+10+12 = 42.

When the 'printf' statement is executed, it will print the values of 'a' and 'i', which are 42 and 7 respectively. This is because the final value of 'i' that was used in the loop was 7, even though the loop terminated when 'i' reached 6. Therefore, the value of 'i' that is printed is the last value assigned to it in the loop.

So to summarize, the value of 'i' is not equal to 7, but it becomes 7 after the 'for' loop completes its last iteration.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top