What is a Conditional Statement in C?
Conditional Statements in C programming are used to make decisions based on the conditions. Conditional statements execute sequentially when there is no condition around the statements. If you put some condition for a block of statements, the execution flow may change based on the result evaluated by the condition. This process is called decision making in C. In C programming conditional statements are possible with the help of the following two constructs:
1. if Statement
2. if-else Statemen 3.Nested if-else
if Statement :
In C language, the if statement is a simple decision-making and branching statement and it is used to control the flow of the program execution. If statement is a two-way branching statement and it involves boolean expression. It means depending on the condition the control is transferred either to the true block or false block.
Syntax of if Statement: if(Expression){ // code } Examples of if Statement:
output:
if-else Statement:
In C language,If the test expression is true, then the true-block statement(s), immediately following the if statements are executed first; otherwise, the false-block statement(s) are executed first.
Examples of if -else
Output:
3.Nested if-else: When an if else statement is present inside the body of another if or else then this is called nested if else.
Syntax:
if(condition) { //Nested if else inside the body of “if” if(condition2) { //Statements inside the body of nested “if” } else { //Statements inside the body of nested “else” } }
else { //Statements inside the body of “else”
}
Examples of Nested if-else: * C program to find largest from three numbers given by user to Explain Nested if-else
#include<stdio.h>
int main() {
int num1, num2, num3;
printf(“Enter three numbers:\n”);
scanf(“%d%d%d”,&num1, &num2, &num3);
if(num1>num2)
{
/* This is nested if-else */
if(num1>num3) { printf(“Largest = %d”, num1); }
else {
printf(“Largest = %d”, num3);
}
}
else {
/* This is nested if-else */
if(num2>num3) {
printf(“Largest = %d”, num2); }
else {
printf(“Largest = %d”, num3); }
}
return(0);
}