The below program gives correct result for negative and zero integer, but for positive integer, it gives wrong output:
Enter the value of a : 6
The no is positive
The no is zero
Why?
int main()
{ int a;
printf("Enter the value of a : ");
scanf("%d",&a);
if(a>0)
printf("The no is positive\n");
if(a<0)
printf("The no is negative\n");
else
printf("The no is zero\n");
}
You have to write
if(a>0)
printf("The no is positive\n");
else if(a<0)
printf("The no is negative\n");
else
printf("The no is zero\n");
Otherwise the two if statements are executed independly.
if(a>0)
printf("The no is positive\n");
and
if(a<0)
printf("The no is negative\n");
else
printf("The no is zero\n");
and for a positive number you will get two outputs.
Your second if
should be else if
. Both the first condition and the else
get run otherwise when you have a positive number.
It's because you are using if
statements without following else
blocks. Once the first if
is evaluated, it still evaluated the second if
and then since that will be false if the input is positive, the else
block will run, printing the wrong output.
Brother you have to use else if because the code checks for the first check ie a>0 which is true then it goes after that as no else is present it goes on to the next if block ie a<0 which is false so it goes to else condition of that and prints the number is zero.
Inorder to avoid it consider using else if so only one block is true ie a>0 and then the program exits the conditional statement
if(a>0)
printf("The no is positive\n");
else if(a<0)
printf("The no is negative\n");
else
printf("The no is zero\n");
You have missed the condition, to get it satisfied you have to use if..else..if
int main()
{
int a;
printf("Enter the value of a : ");
scanf("%d",&a);
if(a>0)
printf("The no is positive\n");
else
if(a<0)
printf("The no is negative\n");
else
printf("The no is zero\n");
}
In your case second if
condition was failing so it was directly printing whatever there is in else
condition Please try above code you will get correct answer.
int a;
printf("Enter the value of a : ");
scanf("%d",&a);
if(a>0)
printf("The no is positive\n");
else if(a<0)
printf("The no is negative\n");
else
printf("zero");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.