Home > Software engineering >  Confused with "for loop" output [closed]
Confused with "for loop" output [closed]

Time:09-17

I have a very basic C program, and confused with its output:

#include<stdio.h>

int main() {
        int i;
        char s[] = "K";

        for(i=0; s[i]; i  ); {
                printf("%d ", i);
                printf("%c ", s[i]);
        }
}

It outputs i value as 1, but as per one of the answer from this thread: Difference between pre-increment and post-increment in a loop?

    int i = 0; // Initialization

    loopStart:
    if (i < 5) // Condition
    {
       Output(i);

       i   or   i; // Increment

       goto loopStart;
     }

Increment happens after the Output(i) (equivalent to printf("%d ", i);), Then how i's value comes as 1 but not 0?

CodePudding user response:

It's because of ; after for loop

for(i=0; s[i]; i  );

Remove semicolon and it's fine.

for(i=0; s[i]; i  )

It's because the semicolon will be considered as an end of the statement and your printf is not part of the loop and will be executed once the loop execution gets completed.

CodePudding user response:

When you add semicolon at the end of for loop then execution will terminated after checking the condition in for loop. If you want the output : 0 And : K

Then try this

int main()
{
     int i = 0;
     char s[] = 'K';
     for(i = 0; s[]; i  )
     {
          printf("%d", i);
          printf("%c",s[i]);
     }
     return 0;
}

CodePudding user response:

Your code block

for(i=0; s[i]; i  ); {
    printf("%d ", i);
    printf("%c ", s[i]);
}

has misleading indentation. With correct indentation, it would look like this:

for(i=0; s[i]; i  )
    ;

{
    printf("%d ", i);
    printf("%c ", s[i]);
}

As you can see, the for loop is empty, and the code block with the printf statements is not part of the for statement (which means that it is not part of the loop). What you want is probably the following:

for(i=0; s[i]; i  ) {
    printf("%d ", i);
    printf("%c ", s[i]);
}

Note that this code is identical to your code, except that a semicolon was removed.

  • Related