In this tutorial, you will learn to control flow control of a program using c programming if statement.
Normally, statements in a program are executed one after the other in the order in which they are written. This is called sequential execution.
But sometimes, along with the program, the order of execution needs to be changed or the programmer must know how to change the flow of the program.
For this C provides control statement if
and if..else
to control the flow of program.
It’s a one-way branching in which the statements will only execute if the given expression is true.
if ( expression) { statements; }
Here, statements will be executed only if the expression is true.
[adsense1]
if..else
statement is used if we want to execute some code if the condition is true and another code if the condition is false.
Here, if an expression
is true then statement1
will be executed , otherwise, statement2
will be executed.
if (expression) { statement1; } else { statement2; }
Here, if the expression
is true then statement1
will be executed otherwise, statement2
will be executed.
if...else
statements. Type beginning and ending of braces and then write statements between them.
Example: if grades are less than 40 you will get failed result, otherwise you will get pass result
#include <stdio.h> int main () { int grades; printf("enter your grades :"); scanf("%d",&grades); if ( grades >= 40 ) printf("Congratulations you are passed"); else printf("Sorry you are failed"); return 0; }
Output
enter your grades : 50 Congratulations you are passed
if...else if...else
statement is used to select a particular block of code when several block of codes are there.
if(expression1) { statement1; } else if (expression2) { statement2; } else if (expression3) { statement3; }
Here, statement1
will be executed if expression1
is TRUE, statement2
will be executed if expression2
is TRUE and if none of the expressions are true then statement3
will be executed.
Note: Syntax error is detected by the compiler whereas logic error has its effect at execution time.