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

So,I made this simple C program to give output,so it is correct for positive and zero integer values but it is coming wrong for negative even and odd

How to get out of this first if else construct because when I input Negative values,because the condition here is checked and then it goes to the last else statement where this just prints zero

 #include<stdio.h>
      int main() {
         int x;
      scanf("%d", &x);

 if(x>0)
{

    printf("Positive");
    {
        if(x%2==0)
        {

            printf("Even");

        }
        else
        {

            printf("Odd");
        }

    }

I want this to be executed when I input negative values,but I’m unable to do so

    if(x<0)
    {
            
 printf("Negative");

        {

            if(x%2==0) {

                printf("Even");

            }
            else {

                printf("Odd");

            }


        }


    }

}

else {

    printf("Zero");

}
return 0;
}

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

>Solution :

Just reindent your code you will find strange { like the one after printf("Positive");

Juste removing this strange { and fixing your coding style will be:

#include<stdio.h>
int main() {
    int x;
    scanf("%d", &x);

    if ( x > 0) {
        printf("Positive");
        if ( x % 2 == 0) {
            printf("Even");
            
        } else {
            printf("Odd");
        }
    } else if( x < 0) {
        printf("Negative");
        if( x % 2 == 0) {
            printf("Even");
        } else {
            printf("Odd");
        }
    }   
    else {
        printf("Zero");
    }   
    return 0;
} 

easier to read, easier to debug

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