You are on page 1of 2

The IF-ELSE-IF

A common programming construct in Turbo C is the IF ELSE If ladder. The expressions are
evaluated from the top downward. As soon as a true condition is found, the statement associated
with it is executed, and the rest condition is found, the statement associated with it is executed.
And the rest of the ladder will not be executed. If none of the condition is true, the final else is
executed.

The final else acts as a default condition. If all other conditions are false, the last else statement
is performed. If the final else statement is not present, then no action takes place.

Sample Scenario of the ladder;

If(expression_1)
Statement_1;
else if(expression_2)
Statement_2;
else if(expression_3)
Statement_3;

else
statement_else;

Example

Write a program that will ask the user input an integer then output the equivalent day of the
week. 1 is Sunday, 2 is Monday, and so on. If the inputted number is not within 1 – 7 output “
Day is not Available!”

#include<stdio.h>
Main()

Int day;
Printf(“Enter an integer:”);
Scanf(“%d”, &day);
If (day == 1)
Printf(“Sunday”);
Else if (day ==2)
Printf(“Monday”); Else if (day ==3)
Printf(”Tuesday”); Else if (day ==4)
Printf(“Wednesday”);
Else if (day ==5)
Printf(“Thursday”);
Else if (day ==6)
Printf(“Friday”); Else if (day ==7)
Printf(“Saturday”);

Else
Printf(“Day is not available!”);
Getch();
}
The SWITCH Statement

The switch statement is a multiple-branch decision statement.

The general form of the switch statement is:

Switch (variable)
{
Case statement1;
Statement sequence_1;
Break;
Case statement2;
Statement sequence_2;
Break;
Default:
Statement_sequence_default;
}
In a switch statement, a variable is successively tested against a list of integer or
character constants. If a match is found, a statement or block of statements is executed. The
default part of the switch is executed if no matches are found. The default statement is used to
terminate the statement sequence associated with each case statement.

Rewrite the program using the 1st example;

#include<stdio.h>
Main()

{
Int day;
Printf(“enter an integer:”);
Scanf(“%”, &day);

Switch (day)
{
Case 1:
Printf(“Sunday”);
Break;
Case 2:
Printf(“Monday”);
Break; Case 3:
Printf(“Tuesday”);
Break; Case 4:
Printf(“Wednesday”);
Break; Case 5:
Printf(“thursday”);
Break; Case 6:
Printf(“friday”);
Break; Case 7:
Printf(“Sunday”);
Break;
Default: printf(“day is not available”);
}
Getch();
}

You might also like