Ads block

Banner 728x90px

if statement

In a real life example, a person performs different task in different situations. Same in the programming world, we have to execute some code lines in specific coditions. This is possible in C language if we use the if statements. If statement is used to control the flow of program based on some conditions. The block of codes specified in the if block are executed, if the expression is evaluated to true. Otherwise, it will get skipped.

According to the requirements, there are four ways to use of if-statement.

  • if statement
  • if-else statement
  • if else-if ladder
  • nested if

Before execution of if block codes, it checks the given condition. On the basis of given condition the controller takes decision that what operation is to be performed. Here is the syntax of if-statement.

if(condition)
{
 // codes to be executed
 .....
 .....
}

Let's see a simple program to find weather an integer is positive or negative.

#include<stdio.h>
int main()
 {
   int age;
   printf("Enter your age for vote: ");
   scanf("%d",&age);
   if(age<=18)
      printf("Sorry! you are not eligible");
   if(age>18)
      printf("Congrats! you are eligible");

   return 0;
 }

16
Sorry! you are not eligible
25
Congrats! you are eligible



if-else statement

The if-else statement is the next version of if statement. It is used in the program when we have two conditions. In the if-else statement, the block code is defined in the if block are executed, if the condition is evaluated to true. Otherwise, it will execute the codes defined in the else block. This concept provides an optional feature in the program.

Let's see the syntax of if-else statement.

if(condition)
{
  /*if block codes
    to be executed
*/

}
else
{
  /*else block codes
    to be executed
*/

}

Here, we are using a program to check whether an integer is positive or negative.

#include<stdio.h>
int main()
 {
   int n;
   printf("Enter an integer: ");
   scanf("%d",&n);
    if(n>=0)
       printf("\n%d is positive integer.",n);
    else
       printf("\n%d is negative integer.",n);

   return 0;
 }

-5
-5 is negative integer.
8
8 is positive integer.