if-else unpredictable behaviour

ghz 8months ago ⋅ 141 views

I am trying to write a basic C program to display contents of a file on the screen. I am facing a problem with the way if-else seems to work. Here are two codes which I think should work the same, but for some reason they do not.

Code 1:

    while((c=fgetc(fp))!=EOF)
    {    if(j==3&&c!=' ')
         {
            printf("%c",c);
            j++;
         }
    
         else if(j!=3)
         { 
            printf("%c",c);
            j++;
         }
    }
    

Code 2:

   while((c=fgetc(fp))!=EOF)
   {
       if(j==3&&c!=' ')
          printf("%c",c);
    
       else if(j!=3)
          printf("%c",c);
    
       j++;
   }

Please point out where I am going wrong. Thanks in advance.

Answers

The two code snippets you provided are indeed very similar, but there is a slight difference in how they handle the j variable incrementation, which affects the logic flow.

In the first code snippet, the j variable is incremented within both the if and the else if blocks. This means that j is incremented twice when j is not equal to 3 (once inside the if block and once inside the else if block), resulting in j being incremented by 2 each time.

However, in the second code snippet, the j variable is incremented unconditionally at the end of the loop (j++). This means that j is incremented by 1 regardless of whether the if or the else if condition is met.

To make the two code snippets behave the same way, you need to ensure that j is incremented consistently. Here's how you can modify the second code snippet to match the behavior of the first one:

while((c=fgetc(fp))!=EOF)
{
    if(j==3&&c!=' ')
        printf("%c",c);
    else if(j!=3)
        printf("%c",c);

    j++; // Increment j outside the if-else blocks
}

With this modification, j will be incremented by 1 after each character is printed, ensuring consistent behavior with the first code snippet.