Credits

Wednesday, February 11, 2009

Condition Statements Using Switch

Another condition statement in C or in C++ is the switch statement. The general syntax is :

switch (selector)
{
case value1: ;break;
case value2: ;break;
:
case valuen: ;break;
default:
;
}

Check the sample program below.



[+/-] show/hide




/* a program to determine the days of the months in a year */

#include stdio.h /* must include stdioh in between <> */
main()
{ int month,days;
clrscr();
printf("Input a month from 1-12: ");
scanf("%d",&month);
switch (month)
{
case 1:
case 3:
case 5: /* these statements are valid if to mean several values but w
ith one group of action*/
case 7:
case 8:
case 10:
case 12:
days=31;printf("\nMonth %d has % days",month,days);break;
case 2: if (month%4==0)
days=29;
else
days=28;
printf("\nMonth %d has % days",month,days);break;
case 4:
case 6:
case 9: /* these statements are valid if to mean several values but w
ith one group of action*/
case 11:
days=30;printf("\nMonth %d has % days",month,days);break;
default:
printf("\nYour input %d is out of range",month);
}
getch();
}


What is the output of this program?
Replace the input and output commands in Bloodshed C++. Translate this.

AddThis