How if else-if else ladder statement works in C program.
- Get link
- X
- Other Apps
How if else-if else ladder statement work in the C program.
In C programming or any other programming language, there is a concept of control statements or conditional statements. In one of our previous blog posts, we shed some light on the if else statement in the C program. In this post, we will cover the if else-if else ladder statement, which is used when multiple conditions need to be addressed. No, we are going to look at the syntax of the if else-if else ladder statement.
Syntax of if else-if else ladder statement
if (condition)
{
// code to be executed if the condition is true
}
else if (condition)
{
// code to be executed if the condition is true
}
else if (condition)
{
// code to be executed if the condition is true
}
else
{
// code to be executed if none of the conditions is true
}
The if else-if else ladder statement is very similar to the if else statement. The main difference is the addition of an else-if part in it. In the above syntax part, we used two else-if conditions, it is according to our requirement that how many different conditions are needed to be addressed. We can use multiple else-if conditions according to our requirements.
Below is the sample code given for the if else-if else ladder statement. We are going to take a number as input and then we are going to implement the if else-if else statement.
In the above coding segment, we are entering a number, and we are going to check that the entered number is equal to 10. We are using the if condition and going to print the message within the if block that the entered number is equal to 10.
In the above coding segment if the entered number is 20 then we are going to use the else-if condition and run the code block of else-if which prints that the entered number is equal to 20, and the same logic will be used for the remaining else-if conditions and their code blocks.
And at last, if the entered number is not equal to 10, 20, 50, or 100 then the else part will run and prints that the entered number is not equal to 10, 20, 50, or 100.
The Main difference between if and else-if statement
If we use multiple if conditions in our program, our program will check each and every if condition even if the very first if condition is true still the program will check all the remaining if conditions. Whereas in the else-if condition if the very first else-if condition is true the program will not check the remaining else-if conditions at all.
Congratulations we have successfully implemented the if else-if else ladder statement in our program.
- Get link
- X
- Other Apps
Comments
Post a Comment