The If statement in C programming is one of the most useful decision-making statements 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. If the test condition is true, then only statements within the if statement 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) { Statement 1; Statement 2; Statement 3; …………. …………. Statement n; }
From the above code, If the test condition in the If statement is true, then the statements (Statement 1, Statement 2, Statement 3, ……., Statement n) will be executed. Otherwise, all these statements 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; }
NOTE: For the single printf statement, curly brackets not required in C Programming. But for multiple statements, it is mandatory. It is always good practice to use curly brackets following the If statement.
OUTPUT
ANALYSIS
If you look at the above if statement, Value stored in the number variable is greater than or equal to 0. That’s why it printed (print statement) inside the curly brackets ({}}.
From the above example, what happens if the condition fails? (number < 1).
It prints nothing because we don’t have anything to print after the if statement. 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:
If the test condition is true, STATEMENT 1 executed followed by STATEMENT N. If the condition is False, STATEMENT N execute because it is out of the if statement block. It has nothing to do with the condition result.
/* 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"); } printf("This Message is not coming from IF STATEMENT\n"); return 0; }
OUTPUT
You can observe from the above output it printed both the printf statements because 22 is greater than 1. Let’s try the negative values to fail the condition deliberately
If condition (number < 1) failed here, it prints nothing from the If condition block. So, it wrote only one printf statement, which is outside the statement block.