0
7.8kviews
Explain switch case and if-else ladder with example.
1 Answer
0
452views

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:

Program:

// 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:

Program:

#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
Please log in to add an answer.