If else statement in C Programming

If else statement in C

  • This statement is useful to execute a task depending upon 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 else part is optional.
Example: if(a>b)
        printf("\n Bigger=%d",a);
        printf("\n Bigger=%d",b);

  • In the above example, ‘a’ value is compared with that of ‘b’. If ‘a’ is really greater than ‘b’ then the condition a>b will become true. Then ‘a’ value will be displayed. If ‘a’ value is not greater than ‘b’ then b value is displayed.

 

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 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.

naveed08st
 

Click Here to Leave a Comment Below 0 comments

Leave a Reply: