[Solved] loops and switches in c my code


There are 3 places where i is changed (after the initialization to 1)

Check the comments in order A, B, C, …

int main()
{   
  int i;
  for(i=1;i<10;i++)
             // ^^ 6 -> 7 (end of 1st loop)          C
             // ^^ 10 -> 11 (end of 2nd loop)        E
  {
    switch(i)
    {
      case 1: i=i+2;     // 1 -> 3 (1st loop)        A

      default : i=i+3;   // 3 -> 6 (1st loop)        B
                         // 7 -> 10 (2nd loop)       D
    }
  }
  printf("%d",i);
  return 0;
}

So it’s the i++ that makes i change from 10 to 11 before i is printed.

Remember that

for(i=1;i<10;i++)
{
    code
}

is equivalent to

i=1;
while(i<10)
{
    code

    i++;  // Notice: The increment is before the i<10 condition is checked
}

solved loops and switches in c my code