Professional Documents
Culture Documents
Name :..
Matrix No:..
Year :
Course :...
LAB 3
SELECTION STRUCTURE
1. OBJECTIVES:
1.1 Introduction to if, if . else, nested if and switch statements.
1.2 Able to use selection control structures in programs.
1.3 Able to modify program according to user requirements.
2 INTRODUCTION:
In C language, there are several selection methods which can be used:
(a) One way selection
(b) Two way selection
(c) Multi selection
(d) Nested if
(e) Switch command
if (condition)
statement;
if (condition) Flowchart:
{
statement1; start
statement2;
}
condition Yes statement1
No
Flowchart:
start
if (condition) start
statement;
else if (condition)
statement; condition T statement1
else
statement; F
condition T statement1
statement1
end
Flowchart:
start
condition T
F
condition
statement1
statement1 statement2
statement1
end
switch (variable)
{
case value1: printf(Message 1);
break;
case value2: printf(Message 2);
break;
case value3: printf(Message 3);
break;
case value4: printf(Message 4);
break;
case value5: printf(Message 5);
break;
default: printf(Default Message);
}
Note: The break statement is used to end the switch after the category or selection is selected.
Omitting the break statement will not generate a syntax error in your program but it will produce
semantic error.
3 TASKS:
3.1
(a) The following code segment is syntactically correct, but difficult to read. Rewrite
the segment using indentation that improves its readability.
if (cRoadStat == 's')
if (fTemp > 0)
printf("Roads wet.\n");
else
printf("Roads icy.\n");
else
printf("Roads dry.\n");
(c) The decision table below shows fines imposed for speeding violations. Write a
code segment that assigns the correct fine to type double variable fine based on
the value of type int variable speed.
3.2 Write a program for the National Earthquake Information centre implementing the
following decision table to characterize an earthquake based on its Richter scale
number.
Richter Scale Number (N) Characterization
N < 5.0 Little or no damage
5.0 N 5.5 Some damage
5.5 N 6.5 Serious damage: wall may crack or fall
6.5 N 7.5 Disaster: house and buildings may collapse
higher Catastrophe: most buildings destroyed
b. Can you handle this problem with a switch statement? If so, use a switch
statement; if not, explain why;
3.3 Write a nested if statement for the decision diagrammed in the accompanying
flowchart. Use a multiple-alternative if for intermediate decisions where possible.
false true
pH > 7
Neutral
false false
true Alkaline
pH > 2
3.4 Write a program that assigns to the variable lumens the expected brightness of
a standard light bulb whose power has been stored in watts. Use the following table: