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;
}
CodePudding user response:
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
CodePudding user response:
It seems the problem is an incorrect nesting of compound statements.
I can suggest the following solution.
#include <stdio.h>
int main( void )
{
enum { Negative = -1, Zero = 0, Positive = 1};
printf( "Enter a number: " );
int x = 0;
scanf( "%d", &x );
int sign = ( 0 < x ) - ( x < 0 );
switch (sign)
{
case Negative:
printf( "Negative " );
break;
case Zero:
puts( "Zero" );
break;
case Positive:
printf( "Positive " );
break;
}
if (sign != 0)
{
puts( x % 2 == 0 ? "even." : "odd." );
}
}
The program output might look like
Enter a number: 10
Positive even.
