Saturday, 31 January 2015

C Programming switch Statement

C Programming switch Statement

Decision making are needed when, the program encounters the situation to choose a particular statement among many statements. If a programmer has to choose one block of statement among many alternatives, nested if...else can be used but, this makes programming logic complex. This type of problem can be handled in C programming using switch statement.

Syntax of switch...case

switch (n) {
case constant1:
   code/s to be executed if n equals to constant1;
   break;
case constant2:
   code/s to be executed if n equals to constant2;
   break;
   .
   .
   . 
default:
   code/s to be executed if n doesn't match to any cases;
}
The value of n is either an integer or a character in above syntax. If the value of n matches constant in case, the relevant codes are executed and control moves out of the switch statement. If the ndoesn't matches any of the constant in case, then the default codes are executed and control moves out of switch statement.
Working of C switch...case statement in C programming with flowchart.

Example of switch...case statement

Write a program that asks user an arithmetic operator('+','-','*' or '/') and two operands and perform the corresponding calculation on the operands.

/* C program to demonstrate the working of switch...case statement */
/* C Program to create a simple calculator for addition, subtraction, 
   multiplication and division */

# include <stdio.h>
int main() {
    char o;
    float num1,num2;
    printf("Select an operator either + or - or * or / \n");
    scanf("%c",&o);
    printf("Enter two operands: ");
    scanf("%f%f",&num1,&num2);
    switch(o) {
        case '+':
            printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
            break;
        case '-':
            printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
            break;
        case '*':
            printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
            break;
        case '/':
            printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
            break;
        default:
            /* If operator is other than +, -, * or /, error message is shown */
            printf("Error! operator is not correct");
            break;
    }
    return 0;
}
Output
Enter operator either + or - or * or / 
*
Enter two operands: 2.3
4.5
2.3 * 4.5 = 10.3
The break statement at the end of each case cause switch statement to exit. If break statement is not used, all statements below that case statement are also executed.

No comments:

Post a Comment