If...else is the first and the most widely used Control Statements in C. It is widely used because of its simplicity. If Else Statements is used in three ways. In all the three cases, it just takes some condition and perform some set of statements.
The condition we use is mostly by using the relational operators and the logical operators. We can use a single condition or multiple conditions in a single if statement.
The condition we use is mostly by using the relational operators and the logical operators. We can use a single condition or multiple conditions in a single if statement.
If Statement:
If is the first and the simple control flow Statement in C.
Syntax:
- if(condition)
- {
- -----
- -----
- }
Example:
- if(a==5)
- {
- printf(" In the If condition");
- }
Thus we use the if statement to perform some kind of operations. If a is not equal to 5 in the above example, the inner statements are not executed.
If...Else Statement:
If...Else is an extension of the if statement. In the above example, we have observed that if the condition is true, then we have specified some statements to execute. But we don't have a chance to specify the statements when the condition fails. Here comes a solution to the above problem.
Syntax:
- if(condition)
- {
- //Statements to be executed
- }
- else
- {
- //Statements to be executed
- }
Example:
- if(a==5)
- {
- printf("Condition is true");
- }
- else
- {
- printf("Condition failed");
- }
In the above example, if the condition is true, then the upper set of statements are executed. If the condition fails, then the lower set of statements are executed.
Nested If...Else Statements:
In the nested If...Else statements, we can use any number of if...else statements one inside the other. You can understand it more clearly by seeing the following example.
Example:
- if(a==5)
- {
- if(b==3)
- {
- printf("Both the statements are true");
- }
- else
- {
- printf("One condition, a is true");
- }
- }
- else
- {
- if(b==3)
- {
- printf("One condition, b is true");
- }
- else
- {
- printf("Both are false");
- }
- }
We can clearly understand what is nested if...else by observing the above example. We can nest any conditions like that.
If...Else-If...Else Statement:
If...Else-if...Else is an advancement of if...else. Suppose, we want to separate the blocks of statements based on the value of a, then we can do that by using this statement.
Syntax:
- if(condition)
- {
- //Statements
- }
- else if(condition)
- {
- //Statements
- }
- else
- {
- //Statements
- }
Example:
- if(a<5)
- {
- printf("a is less than 5");
- }
- else if(a==5)
- {
- printf("a is equal to 5");
- }
- else
- {
- printf("a is greater than 5");
- }
Thus we can use if statement based on our need.