0

I have this question here:

What is i after the following for loop? The given code is:

 int y= 0; 
for (int i= 0; i<10; ++i) 
{  
  y+= i; 
}

I put that the answer is 9, but that is incorrect according to the grader. I even printed 'i' and it came out as 9.

ecain
  • 1,282
  • 5
  • 23
  • 54

3 Answers3

2

The answer is that i is undefined after the loop. It is 9 at the last iteration, though.

Alain
  • 532
  • 6
  • 15
  • 2
    `i` is 10 at the last iteration, but everything else is spot on. – Makoto Jul 15 '15 at 23:00
  • Guess it depends on how we define "last iteration". If we were to print the value of `i` inside the loop the highest value you'd see is 9, but `i` is assigned the value 10 before the program exits the loop. I think. Now I have to go try it. – Alain Jul 15 '15 at 23:07
1

Think of it this way. Using y+=i is constantly adding the current value of y to the value of i. So, in turn, you're not getting the true value of i, but rather the cumulative value.

This is what is actually happening in y+=i

1+2+3+4+5+6+7+8+9

Also, just printing out i after the loop would be invalid since outside that for loop, i no longer exists.

You could just do this:

int y=0;
for(int i = 0; i<10;i++)
  y=i;
System.out.println(y);
UnknownOctopus
  • 2,057
  • 1
  • 15
  • 26
1

Value of i would be 10. As of now, if you try to print the value of i outside the loop, i is undefined.

When i was 9, you continued with the loop, for next iteration i became 10 and condition fails and causes to break the loop. So value of i is 10. Keep it in mind having stpe statement as ++i or i++ is not different w.r.t the values that i would attend. step statement always executes before start of the next iteration.

Following small change would help you to prove the output.

 int i,y= 0; 
 for (i= 0; i<10; ++i) 
 {  
      y+= i; 
 }
 printf("%d\n",i);

That being said if you are printing the value of i within the loop, then you'll get maximum value of i as 9 on the output. Probably this is what you were doing to conclude the answer as 9.

 int y= 0; 
 for (int i= 0; i<10; ++i) 
 {  
     y+= i; 
     printf("%d\n",i);
 }
Vallabh Patade
  • 4,960
  • 6
  • 31
  • 40