swith-case

switch-case is used to execute statement depends on condition. It is similar to if-else.
Syntax:
switch(expression)
{
case constant1:
statement1;
break;
case constant2:
statement2;
break;
.
.
.
case constantN:
statementN;
break;
default:
statement4;

}
Explanation:

The expression inside switch() will be checked against constant1, constant2… constantN. If any constant matches with the expression then corresponding statements will be executed. Here break; is used to skip the rest of case

Example:

#include<stdio.h>
int main()
{
    int a;
    printf("Enter a positive value : ");
    scanf("%d",&a);
    switch(a%2)
    {
       case 0:
       printf("Entered value is even ");
       break;
       case 1:
       printf("Entered value is odd");
       break;
    }
    return 0;
}

OUTPUT

Enter a positive value : 84
Entered value is even

#include<stdio.h>
int main()
{
    int n;
    printf("Enter a value : ");
    scanf("%d",&n);
    (n>0)? printf("Value is positive") : printf("Value is negative");
    return 0;
}

OUTPUT

Enter a positive value : 81
Entered value is odd

NOTE

Expression inside switch() should contain only char or int type variable or constant.


Next Previous