In this tutorial you will learn about the C Decision Making and its application with practical example.
Decision Making Statement allows computer to decide block of code to be execute based on the condition.if, if … else,if … else if and switch statements are used as decision making statements in c programming language.
The if Statement
Block of statement executed only when a specified condition is true.
Syntax:
1 2 |
if( expression ) statement; |
Example:
1 2 |
if(a>b) printf("a is greater than b"); |
Above example is valid for single statement in the body of the if statement. If there is a set of multiple statements in the body of the if statement, than it is written inside a pair of parenthesis.
1 2 3 4 5 |
if(a>b) { printf("body of if statement"); printf("a greater than b"); } |
The If…Else Statement
When we want to execute some block of code if a condition is true and another block of code if a condition is false, In such a case we use if….else statement.
1 2 3 4 5 6 7 8 |
if(expression) { //Block of code to be executed comes here if condition is true; } else { //Block of code to be executed comes here if condition is false; } |
Nested If else
When there is an if statement inside another if statement then it is known as nested if else.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
if(expression) { Statement; } else { if(expression) { Statement; } else { Statement; } } |
The if else ladder
The if….elseif…else statement is used to select one of among several blocks of code to be executed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
if(expression1) { Statement 1; } else if(expression2) { Statement 2; } . . else { Statement n; } |
The Switch Statement
The switch statement is simplified form of the nested if … else if statement , it avoids long blocks of if..elseif..else code.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
switch (expression) { case val1: //Block of code to be executed if expression = val1; break; case val2: //Block of code to be executed if expression = val2; break; default: //Block of code to be executed //if expression is different //from both val1 and val2; } |