You are on page 1of 5

UET Taxila Computer system & Programming

Mechanical Engineering Dept

Objective
Make use of
Switch Statement
The switch statement lets the value of a variable or expression determine
where the program will branch.
A branch occurs when one part of a program causes another part to
execute. The if/else, if
statement allows your program to branch into one of several possible
paths. It performs a series of tests (usually relational) and branches when
one of these tests is true. The
statement is a similar mechanism. It, however, tests the value of an integer
expression and then uses that value to determine which set of statements
to branch to.

Here is the format of switch statement:

switch(integerExpression)
{
case ConstantExpression:
//place one or more
//statement here
case ConstantExpression:
//place one or more
//statement here
//case statement may be repeated as many
//time as necessary
default:
//place one or more
//statement here
}

33
UET Taxila Computer system & Programming
Mechanical Engineering Dept

The first line of the statement starts with the word switch, followed by an
integer expression inside parentheses. This can be either of the following:
A variable of any of the integer data types (including char)
An expression whose values is of any of the integer data type.

On the next line is the beginning of a block containing several statements.


Each case statement is formatted in the following manners:

case ConstantExpression:
//place one or more
//statement here
An optional default section comes after all case statements. The program
branches to this section if none of the case expressions matches the switch
expression. So, it functions like a else in an if/else statement.

34
UET Taxila Computer system & Programming
Mechanical Engineering Dept

Program No.23
Write a program in C using switch statement to find largest number among
three variables.
Output of Program No.23

35
UET Taxila Computer system & Programming
Mechanical Engineering Dept

Program No.24
Write a program in C using switch statement to find ODD or EVEN.
Output of Program No.24

36
UET Taxila Computer system & Programming
Mechanical Engineering Dept

Program No.25
Write a program in C++ using switch statement to find grade of student.
HINT: grade >= 90 Grade A
grade >= 80 Grade B
grade >=70 Grade C
grade >=60 Grade D
Output of Program No.25

37

You might also like