Saturday, May 10, 2008

Case control statements

Case control statements

The Case control statements allow the computer to take
decision as to be which statements are to be executed next.
It is a multi way decision construct facilitate number of
alternatives.

C has multi way decision statement known as switch statements.
It tests the value of a given variable or expression
against a list of case value and when a match found a
block of statement associated with the case is executed.

Syntax of switch statement:

switch(expression)
{
case constant_1:
statements;
case constant_2:
statements;
case constant_n:
statements;
default:
statements;
}

Explanation:

First in expression parentheses we give the condition.
This condition checks to match, one by one with case constant.
If value match then its statement will be executed. Otherwise
the default statement will appear.

A structure image of switch statements>



An example program to check whether a given number is even
or odd, using switch statements:




output:



Explanation of the program:

First you will be asked to enter any number
Suppose you enter 7

Now the given condition check, so the modulus is 0 or not.
(% operator is use to find out the remainder)


if the modulus is 0 then ch=1 otherwise 2, statement will be execute.



0 comments:

Copyright

Copyright © 2008 C Tutorial, All rights are reserved