Anda di halaman 1dari 9

SWITCH-CASE STATEMENT

Engr. Annalyn D. Soria

How to use a switch-case statement


The switch-case is a good alternative to cascading if-else statements. Syntax: switch(<expression>) { case<value1>: statement1; break; case<value2>: statement2; break; }

Note: 1. The <expression> must always be enclosed within a pair of parenthesis. 2. The <expression> must evaluate to a whole number, the use of single precision and double precision floating point values will result into an error. 3. The <expression> is tested if it is equivalent to any <value1>, <value2> and so on. If it is equivalent to <value1> for example, then <statement1> will be executed. The same applies to other cases.

4. The break statement is optional. If it is present, it will cause the program to break or jump out of the switch-case, and to execute the next statement following switch-case. If the break is not present, it will cause the program to execute the statement in the following case.
5. If the <expression> is not equivalent to any of the values, then it will execute the <statement> in the default case if it is present.

Example: Write a program that will allow the user to input an integer value representing the days of the week. Let 1 represent Monday, 2 for Tuesday, 3 for Wednesday and so on. The output should be the day of the week in words.
#include <stdio.h> void main(void) { int day; printf( Input day in numeric form: ); scanf(%d,&day);

switch(day) { case1: printf(The day is Monday\n); break; case2: printf(The day is Tuesday\n); break; case3: printf(The day is Wednesda\n); break; case4: printf(The day is Thursday\n); break; case5: printf(The day is Friday\n); break; case6: printf(The day is Saturday\n); break; case7:printf(The day is Sunday\n); break; } printf(Have a nice day\n); getch();}

2. Write a program that will determine the income of an employee. An employee is either a part time employee or a full-time employee. A part time employees gross income is computed as the product of his/her hourly rate and the number of hours worked. The gross income of a fulltime employee is computed as regular pay plus overtime pay. The overtime pay is computed as overtime rate multiplied by the number of overtime hours.

#include<stdio.h> void main(void) { int emp; float gross, hr, hw, regpay, oth, otr, ovpay; printf(Enter employee type: 1-Par time, 2-Full time ); scanf(%d,&emp); switch(emp) { case1: { printf(Enter hourly rate:); scanf(%f,&hr); printf(Enter number of hours_worked:); scanf(%f,&hw); gross = hr*hw; break;}

{ case2: { printf(Enter regular pay:); scanf(%f,&regpay); printf(Enter overtime hours:); scanf(%f,&oth); printf(Enter overtime rate:); scanf(%f, &otr); ovpay = oth*otr; gross = regpay+ovpay; break; } printf(Gross Pay = %f, gross); getch(); }

Anda mungkin juga menyukai