Advertisement Remove all ads

Explain Switch Case and If-else Ladder with Example. - Structured Programming Approach

Explain switch case and if-else ladder with example. 

Advertisement Remove all ads

Solution

Switch Case :-
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

Example :

Code :
// Following is a simple program to demonstrate syntax of switch.
#include <stdio.h>
#include <conio.h>
int main()
{
int x = 2;
switch (x)
{
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
case 3: printf("Choice is 3");
break;
default: printf("Choice other than 1, 2 and 3");
break;
}
return 0;
}

Output : 

Choice is 2 

If-else ladder :-
The if else ladder statement in C programming language is used to test set of conditions in sequence. An if condition is tested only when all previous if conditions in if-else ladder is false. If any of the conditional expression evaluates to true, then it will execute the corresponding code block and exits whole if-else ladder.
Example :

#include<stdio.h>
#include<conio.h>
void main()
{
int a;
printf(“Enter a number : “);
scanf(“%d”,&a);
if(a > 0)
{
printf(“\nThe number is positive “);
}
else if(a<0)
{
printf(“\n The number is negative”);
}
else
{
printf(“Number is zero”);
}
getch();
}

Output :
Enter a number : 25
The number is positive.

 

  Is there an error in this question or solution?
Advertisement Remove all ads
Advertisement Remove all ads
Advertisement Remove all ads
Share
Notifications

View all notifications


      Forgot password?
View in app×