Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

if-else unpredictable behaviour

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   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.

>Solution :

Because Code 1 doesn’t increase j when j == 3 and c == ' ' but Code 2 does.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading