If Statement in C

The If statement in C programming is one of the most useful decision-making expression in real-time programming. C If statement allows the compiler to test the condition first, and then, depending upon the result, it will execute the statements. Whether the test condition is true, then only statements within the if condition performed by the C compiler.

If Statement in C syntax

The basic syntax of If statement in C programming has a simple structure:

// If statement in C Syntax
if (test condition)
{
 
  Statement1;
  Statement2;
  Statement3;
  ………….
  ………….
  Statementn;
}

From the above code, whether the test condition in the If clause is true, then the code block (Statement1, Statement2, Statement3, ……., Statementn) will be executed. Otherwise, all these lines will skip.

If statement in C Example

This example program check for the positive number using if statement in C

/* If Statement in C Programming Example */
#include <stdio.h>

int main()
{
 
 int number;
 
 printf("Enter any integer Value\n");
 scanf("%d",&number);
 
 if( number >= 1 )
 {
   printf("You Have Entered Positive Integer\n");
 }
  
 return 0;
}

For the single printf function, curly brackets not required in C Programming. But for multiple lines of code, it is mandatory. It is always good practice to use curly brackets following the If statement.

Enter any integer Value
22
You Have Entered Positive Integer

When you look at the above if condition, Value stored in the number variable is greater than or equal to 0. That’s why it printed (print function) inside the curly brackets ({}}.

From the above example, what happens when the condition fails? (number < 1).

Enter any integer Value
-22
Program ended with exit code: 0

It prints nothing because we don’t have anything to print after the if block. Hope you are confused with the result, let us see the flow chart

If Statement Flow Chart

The flow chart of an If statement in C programming is as shown below:

 Flow Chart for If statement in C Language

Whether the test condition is true, STATEMENT1 executed followed by STATEMENTN. When the condition is False, STATEMENTN execute because it is out of the if block. It has nothing to do with the condition result.

#include <stdio.h>

int main()
{
 int number;
 
 printf("Enter any integer Value\n");
 scanf("%d",&number);
 
 if( number >= 1 )
 {
   printf("You Have Entered Positive Integer\n");
 }
 
 printf("This Message is not coming from IF STATEMENT\n");
 
 return 0;
}
If Statement in C Programming 3

You can observe from the above output it printed both the printf functions because 22 is greater than 1. Let’s try the negative values to fail the condition deliberately.

Enter any integer Value
-13
This Message is not coming from IF STATEMENT

If condition (number < 1) failed here, it prints nothing from the If condition block. So, it wrote only one printf, which is outside of the block.