Lecture08 Decision Switch

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

CS 110-Fundamentals of Computer Programming

Decision making in C
Asma Majeed

1
The switch statement
Agenda
To be followed in today’s lecture
Switch format

Comparison with if else

Switch flow chart

Switch components

Fundamentals of computer programming 2


The switch statement (Multiple-selection statement)
• Useful when a variable or expression is tested for all the values it can
assume and different actions are taken

• The switch statement is often faster than nested if...else (not always).
Also, the syntax of switch statement is cleaner and easy to understand.

Fundamentals of computer programming 3


switch format
switch ( value ) {
case '1':
actions;
break; // break exits from switch
case '2':
actions;
break;
default: // optional
actions;
break; // not necessary
}

Fundamentals of computer programming 4


If-else style
if ( choice == 0 )
printf( “ Mango ”) ;
else if ( choice == 1 )
printf( “ Banana ” );
else if ( choice == 2 )
printf( “ Grapes ”) ;
else if ( choice == 3 )
printf( “ Apple ”) ;
else if ( choice == 4 )
printf( “ Pear ”) ;
else
printf(“Invalid Choice “);

Fundamentals of computer programming 5


The switch statement style

int choice
case 3:
switch( choice ) {
printf( “ Apple ”) ;
case 0:
break;
printf( “ Mango ”) ;
case 4:
break;
printf( “ Pear ”) ;
case 1:
break;
printf( “ Banana ”) ;
default:
break;
printf( “ Invalid Choice ”) ;
case 2:
break; }
printf( “ Grapes ”) ;
break;

Fundamentals of computer programming 6


To test multiple conditions
• more efficient than if else ladders
• Example.
switch ( opt ){
case ’A’: /* execute if opt == ’A’ */
break;

case ’B’:
case ’C’:
/* execute if opt == ’B’ || opt == ’C’ */
default:
}

Fundamentals of computer programming 7


8
switch components

• switch (control_variable or expression)


• Must evaluate to an integer or character
• Floats and strings are not allowed

Fundamentals of computer programming 9


switch components
• case constant_expression:
• Must be a constant
• n + 10 is allowed provided n is a macro that represents a
constant
• Must evaluate to an integer or character

Fundamentals of computer programming 10


switch components
• Multiple statements between cases do not require braces { }
• Duplicate case labels are not allowed
• Cases can give same result
case 60: case 70: case 80:
printf(“ Greater than 50”);
break;
• Cases do not test range of values
• The break statement is used to prevent the code running
into the next case.
Fundamentals of computer programming 11
Exercises

• Simple Calculator using switch Statement


• functions (add, sub, divide, multiply)

• Write a switch statement to print the day of the week depending on


the user’s choice of day.
• E.g. if a user enters 1, print Monday
• If a user enters 2, print Tuesday. and so on.
• And if a user enters an invalid number, print Invalid day !!!

Fundamentals of computer programming 12

You might also like