Decision-making statements in C: These are used to specify the order in which the statements are executed. C programming language assumes any non-zero and non-null values as true, if it is either zero or null, then it is assumed as false.
This programming allows 3 different types of control statements as follows:
- If statement
- If…else statement
- Nested if statement
- Goto statement
- Switch statement
Decision Making Statements in C
If statement( ) in C
if statement consists of a Boolean expression followed by one or more statements.
Syntax
if(test_expression) {
statement 1;
statement 2;
————–}
Flow chart for if statement
Example
int main() { int x=40,y=40; if (m == n) { printf("x and y are equal"); } }
Output
x and y are equal
If…else statement in C
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
Syntax
if(test_expression)
{ //execute your code
}
else {
//execute your code
}
Example
#include <stdio.h> int main() { int x=40,y=20; if (m == n) { printf("x and y are equal"); } else { printf("x and y are not equal"); } }
Output
x and y are not equal
Nested if statement in C
It is used for one conditional statement inside another conditional statement.
Syntax
if(test_expression one)
{
if(test_expression two)
{
//Statement block Executes when the Boolean test expression two is true.
}
}
Else
{
//else statement block
}
Example
#include <stdio.h> int main() { int x=40,y=20; if (x>y) { printf("x is greater than y"); } else if(x<y) { printf("x is less than y"); } else { printf("x is equal to y"); } }
Output
x is greater than y
Goto statement in C
It is used to branch unconditionally, within a program from one point to another. Mainly programmers use this statement to change the sequence of the execution.
Syntax
goto label;
– – – – – – – – – –
label:
statement – X;
Example
#include <stdio.h> int main() { int sum=0; for(int i = 0; i<=10; i++) { sum = sum+i; } if(i==5) { goto addition; addition: printf("%d", sum); return 0; } }
Output: 15
Switch Statement in C
A switch statement allows variables to test for equality against a list of values.
Syntax
switch(variable) {
case 1: //execute your code break;
case n: //execute your code break;
default: //execute your code break;
}
Example
#include <stdio.h> int main() { int num=2; switch(num+2) { case 1:printf("Case1: Value is: %d", num); case 2:printf("Case1: Value is: %d", num); case 3:printf("Case1: Value is: %d", num); default:printf("Default: Value is: %d", num); } return 0;}
Output
value is 2