If Else Statement in C
This statement is useful to execute a task depending on whether a condition is true or not.
Syntax: if(condition)
statements1;
[else statements2;]
If the condition is true, then statement1 will be executed. If the condition is false, then the statement2 will be executed. The else part is written inside the square braces:[].This represents another part that is optional.
Example: if(a>b)
printf("\n Bigger=%d",a);
printf("\n Bigger=%d",b);
In the above example, the ‘a’ value is compared with that of ‘b’. If ‘a’ is really greater than ‘b’ then the condition a>b will become true. Then the ‘a’ value will be displayed. If ‘a’ value is not greater than ‘b’ then b value is dislplayed.
if(x)
{
printf("%d",x);
--x;
}
else printf("\n NavTutorials");
In the above example, if x value is not 0, then it is taken as true. The statements:
printf("%d,x);
--x;
are included in the curly braces { and }. Whenever there is more than one statement, they should be included inside curly braces.
Program to test whether a number is +ve or -ve
#include<stdio.h>
void main()
{
int num;
printf("\n Enter an integer number:");
scanf("%d",&num);
if(num==0);
printf("\n It is zero");
else if(num>0)
printf("\n%d is positive");
printf("\n%d is negative");
}
Output:
Enter an integer number: -5
5 is positive
Logic – If else statement
If the number is equal to zero, it is neither positive nor negative. If the number is greater than 0, then it is positive. If the number is less than 0, then it is negative.