Curriculum
This article is an overview of the Control flow or the Decision making statements in C programming.
The decision control statements are used in the program to control the flow of the program as it executes certain statements based on the outcome of the condition provided. It allows you to make a decision based on the result of the condition(i.e. true or false).
This will check the condition and then executes a set of statements if the condition is evaluated to True or executes another set of statements if the condition is evaluated to False. Lets us understand some of the control statements.
It checks the condition defined by ‘if’ statement and only if it is True then statements inside the ‘if’ body will be executed. If the condition turns false then the statements inside the ‘if’ body is skipped. You can have n number of if statements in a program.
if(test_expression)
{
statement 1;
statement 2;
...
}
Example
#include<stdio.h> main() { int a = 10, b = 7; if (a>b) { printf("a is greater"); } }
Output
a is greater
Here, we have two blocks of statements. If the condition results true then statements in if block gets executed, if condition results false then statements inside else block executes. You cannot use else without an if statement.
if(test_expression)
{
//executable statements
}
else
{
//executable statements
}
Example
#include<stdio.h> main() { int a; printf("enter your age:") scanf("%d", &a) if (a>=18) { printf("eligible to vote"); } else { printf("not eligible to vote"); } }
Output
enter your age:16
not eligible to vote
Switch statement is needed to evaluate multiple conditions. The switch block defines an expression or condition and the case block has a set of statements, based on the result of the expression or condition, the corresponding case block gets executed. A switch block can have any number of cases.
Syntax
switch(variable)
{
case 1:**
//statements
break;
case n:
//statements
break;
default:
//statements
break;
}
Example
#include<stdio.h> main() { int x; printf(" enter a option between 1 and 3: "); scanf("%d",&x); switch(x) { case 1: printf("Your option is One"); break; case 2: printf("Your option is Two"); break; case 3: printf("Your option is Three"); break; default : printf("Invalid option"); break; } }
Output
enter a option between 1 and 3:2
Your option is two
The conditional operator known as a ternary operator is the decision-making statements that depends upon the output of the expression. It is represented by two symbols, i.e. ‘?’ and ‘:’. It is similar to the ‘if-else’ statement. The conditional operator is known as the ternary operator as it works on three operands.
Syntax:
Expression1? expression2: expression3;
Example
(age>=18)? (printf("Eligible to vote")) : (printf("not eligible to vote"));