5 if statement
TRANSCRIPT
-
8/14/2019 5 if Statement
1/23
Making decision & choosing alternatives
5 Making decision and choosing alternatives
Learn
if.. else statement
relational, equality and logical operators
Multiple choices switch and break statements
5.1 What shall I have for breakfast?
Fig 5. !ifficult decisions "
#e make decision and choose alternatives all the time. For e$ample, for tomorrow, you maychoose to have a long breakfast if you wake up early or you may %ust have a cup of coffee ifyou wake up late. he decision process is summarised in the pseudo codes below
If (I wake up early)I will have a cup of coffee;Make myself a tuna sandwich;And enjoy the morning paper;
elseI will just have a cup of coffee;
he ' language provides similar decision making constructs for us to control the flow of theprogram. (ne such construct is the if..elsecommand which has format similar to the
one above.
)*
-
8/14/2019 5 if Statement
2/23
Making decision & choosing alternatives
If (I wake up early)
I will have a cup of coffee;Make myself a tuna sandwich;
And enjoy the morning paper;!
elseI will just have a cup of coffee;
he flow process is depicted in the flow chart below.
Fig 5.+
n ', the if .. else.. format is shown below
if (conditional e"pression)
statement(s) if e"pression is true
elsestatement(s) if e"pression is false
)
n ' this part is called theconditional e$pression.
-ll these actions arecarried out if theconditionale$pression is true
f conditional e$pressionis false this action iscarried out.
#ake upearly "
ave a cup of coffeea tuna sandwich andread the newspaper.
/ust have a cup ofcoffee
0(
123
-
8/14/2019 5 if Statement
3/23
Making decision & choosing alternatives
-nd the flow chart for the if.. else statement is shown Fig 5.4
Fig 5.4
5.2 Relational, equality and logical oerators
he if..else statement rely on the relational or logical or equality e$pressions to decide theorder of e$ecution of program statements. Let us take a look at the three type of operators relational, equality and logical.
he following table contains the operators that are often used to control the flow of program.
6elational operators Meaning 2$amples
7 less than b 7 c
8 greater than a 8 579 less than or equal c 79 a : b
89 greater than or equal num; 89 5).4
2quality operators
9 9 equal ch 9 9 9 0ot equal $ >9 +
Logical operators
> 0( >5
&& -0! ?a 894@ && ?a 79*@
A A (6 'h9 9
-
8/14/2019 5 if Statement
4/23
Making decision & choosing alternatives
Defore we venture further, let us discuss more about the if...elsestatement format.
he test on the conditional e$pression gives two possible outcomes 6C2 or F-L32. heconditional e$pression must be in parentheses i.e. in brackets ? @. Dut what is truth" 'answers Eero ?*@ 9 false, nonEero?@ 9 true.
1our turn
3tate whether the following e$pressions return a 6C2 or a F-L32 value.
?a@ a9 4if ?a 9 9 )@ Galue ;;;;;;;;;;
?b@ i 9 *if ? i H 5 9 9 *@ Galue ;;;;;;;;;;
?c@ ch 9 9
-
8/14/2019 5 if Statement
5/23
Making decision & choosing alternatives
#$ %rogram &' $#include *stdio.h+main( )
int ,ecret-o guess;
,ecret-o / 0;
printf (12uess the secret num3er 3etween 4 and 45n6);printf (17nter your guess86);scanf (19d6:guess);
if (guess// ,ecret-o)printf (1ou have got it
-
8/14/2019 5 if Statement
6/23
Making decision & choosing alternatives
=ry harder ne"t time.
#$%rogram &'> $#include *stdio.h+main( )
int ,ecret-o guess;
,ecret-o / 0;
printf (12uess the secret num3er 3etween 4 and 45n6);printf (17nter your guess86);scanf (19d6:guess);
if (guess // ,ecret-o)printf (1ou have got it
-
8/14/2019 5 if Statement
7/23
Making decision & choosing alternatives
scanf(19d6:num>);
if ( num> // 4)printf(17rrorBannot perform division5n6);printf (1=he second num3er is 45n6);
! elseresults / (float)num#(float)num>;printf(19d divided 3y 9d is 9.?f5n6 numnum>results);!
!
5.! Multile choice if"else state#ent
Fig 5.K More difficult decisions "
Life is interesting and we are often offered more than two choices> Let go back to the
-
8/14/2019 5 if Statement
8/23
Making decision & choosing alternatives
else if (I wake up not so early E.44am) Cave a hearty 3reakfast; Dead the morning paper;
!elseI will just have a cup of coffee;
ere, three alternatives are given, so the ifelse if elsecontrol statement has to be
used.
he multiple choice if..elsestatement has the format shown below
if (condition e"pression) statement(s)!
else if (conditional e"pression>) statement(s)>!
..
..
else if (condition e"pression p) statement(s)p
!
else statement(s)F!
f conditional e"pressionis 6C2 then statement(s)will be e$ecuted and
the rest of the test conditions will be ignored. f it is F-L32, conditional
e"pression>will be tested.
f conditional e"pression>is 6C2, statement(s)>will be e$ecuted and the
rest of the test conditions will be ignored. f it is F-L32, the condition testing continue untilone of them meet the test conditions and the corresponding statement?s@ will be e$ecuted.f non of the condition e$pression is tested 6C2, then the else statement(s)Fwill be
e$ecuted.
)J
-
8/14/2019 5 if Statement
9/23
Making decision & choosing alternatives
- flow chart representation of the multiple choice if..else control structure is shown in Fig5.5.
)
conditionale$pression;
true "
conditionale$pression;+
true "
conditionale$pression;4
true "
conditionale$pression;p
true "
statement?s@;
statement?s@;+
statement?s@;4
statement?s@;p
statement?s@;q
if
6C2B123
6C2B123
6C2B123
6C2B123
F-L32B0(
F-L32B0(
F-L32B0(
else
Fig 5.5
-
8/14/2019 5 if Statement
10/23
Making decision & choosing alternatives
Let us modify rogram 5I4 above. t is required to perform the following division
num;
num;+and
num;+
num;
herefore it is necessary to check that the two numbers entered are non Eeroes. Defore westart modifying the program, let us look at the possibilities of the values of num; andnum;+, and decide on the actions. here are four possibilities
num; num;+
* * 'annot do division
0on Eero 0on Eero (N
* 0on Eero Oives * & infinity
0on Eero * Oives infinity & *
he algorithm in flow chart form is shown Fig 5.)
Fig 5.)here are many solutions to this problem. (ne is shown below.
)P
!eclarevariablesss
-sk for firstnumber
-sk forsecondnumber
DothnumbersEeroes "
2rrormessages
Doth notEeroes "
!odivision
rintresult
rint *
and
rint
and *
FirstnumberEero"
3tart
2nd
1es
1es
1es
0o
0o
0o
-
8/14/2019 5 if Statement
11/23
Making decision & choosing alternatives
#$ %rogram &'G $##$ =his program reads two integer values and check if 3oth num3ers are@eroes. It then performs divisions on the two num3ers $#
include*stdio.h+
main()
int numnum>; float resultsresults>;
printf(17nter the first num3er 8 6); scanf(19d6:num); printf (17nter the second num3er 86); scanf(19d6:num>);
if (( num // 4) :: (num> // 4))printf(17rrorBannot perform division.5n6);
printf (1Hoth num3ers are @eroes.5n6);!
else if ((num ;results> / (float)num>#(float)num;printf(19d divided 3y 9d is 9.?f5n6 numnum>results);printf(19d divided 3y 9d is 9.?f5n6 num>numresults>);!
else if ((num //4) :: (num> );
printf (19d divided 3y 9d is infinity.5n6num>num); !
elseprintf (19d divided 3y 9d is 4.5n6num>num);printf (19d divided 3y 9d is infinity.5n6numnum>);!
!
J*
-
8/14/2019 5 if Statement
12/23
Making decision & choosing alternatives
3ample runs on the program yield the following
he ne$t e$ample use the chartype of variables and the getchar()function to read the
characters entered from the keyboard.
#$%rogram &'& $#include *stdio.h+main()char choice;
printf(17nter a letter 86);choice / getchar();
if (choice // aJ KK choice //JAJ)printf (1Lirst letter of the alpha3et.5n6);
else if (choice //J3J KK choice HJ)printf (1,econd letter of the alpha3et.5n6);
else if (choice //JcJ KK choice//JBJ)printf (1=hird letter of the alpha3et.5n6);
elseprintf(1Invalid entry.5n6);printf(17nter the first three letters of the alpha3et only.5n6);
!
he program above can be simplified by first converting the character entered to a upper casecharacter, and the first test statement would be
if (choice // AJ)printf (..)
J
7nter the first num3er 8 47nter the second num3er 847rrorBannot perform division.Hoth num3ers are @eroes.
7nter the first num3er 8 ?G7nter the second num3er 8&E?G divided 3y &E is 4.E40&E divided 3y ?G is .EG0
7nter the first num3er 8 47nter the second num3er 8>?4 divided 3y >? is 4.>? divided 3y 4 is infinity.
7nter the first num3er 8 ?G7nter the second num3er 844 divided 3y ?G is 4.?G divided 3y 4 is infinity.
-
8/14/2019 5 if Statement
13/23
Making decision & choosing alternatives
'onversion is done using the toupper()function. he definition of the toupper()
function is found in the ctye.hheader file. he slightly modified version is shown below.
#$%rogram &'E $#
include *stdio.h+include *ctype.h+main()char choice;
printf(17nter a letter 86);choice / toupper(getchar());
if (choice //JAJ)printf (1Lirst letter of the alpha3et.5n6);
else if (choice HJ)printf (1,econd letter of the alpha3et.5n6);
else if (choice//JBJ)printf (1=hird letter of the alpha3et.5n6);else
printf(1Invalid entry.5n6);printf(17nter the first three letters of the alpha3et only.5n6);
!
1our turn
3hown below is part of a ?supposedly ' @ program that assigns the variablesAvalue,
Bvalueand Cvaluewith values +, 4 and K respectively, if ansis greater than *.(therwise they are assigned the values +, 4, K respectively. he specification isimplemented in the following program. dentify if there are any functional or synta$errors in this program. 'orrect these errors.
if (ans + 4) thenAvalue / >;Hvalue / ?Bvalue / G
else
Avalue / >;Hvalue / ?;Bvalue / G
end if
J+
nclude header file ctye.hto use library functiontoupper()
-
8/14/2019 5 if Statement
14/23
Making decision & choosing alternatives
+ elp the 2$amination (fficer to decide your grades. #rite a program to print out thegrade obtained based on the criteria below.
Marks Orade
5 and above !istinction)5.K Merit5*.)K assKP and below Fail
he program is to prompt the user for the marks and then prints out the correspondinggrade.
2$ample of printout on the screen would be
?int Cse the multiple choice if..elsecontrol statement@
4 ow much do you spend on electricity " he rates for electricity in Drunei are given as
follows.
First * units +5senBunit0e$t )* units 5senBunit0e$t ** units *senBunit6emaining units 5senBunit
- minimum charge of Q+.** is applied when the usage amounts to less than Q+.**
#rite a program to prompt the user for the amount of electricity used and calculateand print out the charges.
2$ample of screen print out
J4
7nter marks 8 E0
our grade is Merit.
7nter amount of electricity used (kh) 8 G&4
=he charge is N?&.&4
7nter amount of electricity used (kh) 8 G
=he charge is N>.44
-
8/14/2019 5 if Statement
15/23
Making decision & choosing alternatives
K Dack to the mmenu.c program. #e have not quite finished with our menu program.
Cse the multiple choice if..else if ..elseto control the flow of the program. For eachoption the user has selected, the program is to perform the required operation. For
e$ample if option ?-ddition@ is chosen, the program will prompt the user for 5 integernumbers, and calculate and print the sum and the average value of these numbers. 1oumay insert the program codes from an earlier e$ercise on adding numbers in this program.
For options such as R$. %ransistor circuit analysisS, which is beyond your capabilityto write at this point, you may print the message
$$
5.& Multile choice 'ith the switch andbreakstate#ent
-s the number of alternatives gets larger, the multiple choice ifelse ifelsecontrol
statement becomes cumbersome to use. ' provides a more convenient ?and elegant@ controlstructure for choosing alternatives. t is the use of the switch..caseand the 3reak
statementsrogram 5I) is reIwritten using the switch statement
#$%rogram &'0 $#include *stdio.h+include *ctype.h+main()char choice;
printf(17nter a letter 86);choice / toupper(getchar());
switch (choice)case AJ8
printf (1Lirst letter of the alpha3et.5n6);3reak;
case HJ8printf (1,econd letter of the alpha3et.5n6);3reak;
case BJ8printf (1=hird letter of the alpha3et.5n6);
3reak;
default 8
printf(1Invalid entry.5n6);
JK
nclude header file ctye.hto use library functiontoupper()
Option # 6 chosen. Transistor circuit analysis
Sorry, program for this option is under development.
Try again some other time.
-
8/14/2019 5 if Statement
16/23
Making decision & choosing alternatives
printf(17nter the first three letters of the alpha3et only.5n6);!
!
!
he structure of switch control statement is as follows
switch (integer e"pression) case constant8
statements3reak;
case constant>8statements>
3reak;..
default 8statementsd
!
he switch statement flow chart can be represented by the diagram in Fig 5.J.
Fig 5.J
he ?optional@ defaultcase is used to trap all those values that do not match any of the
case. hebreakstatement at the end of each case is used to cause the program to break out
from the switchstatement and %ump to the end it. rogram e$ecution then starts from that
point onwards.
J5
f integer e$pression matches caseconstant, statements; is e$ecuted.he break statement causes the programto %ump out of the switch loop.
switch?integer constant@
case case+ defaultcasen
!on=t forget thecolon at the end of
each case statement.!on=t forgetthese curly
brackets too
-
8/14/2019 5 if Statement
17/23
Making decision & choosing alternatives
ere is an interesting case. 3ay, for e$ample, that the same ?block of @ statements are to bee$ecuted if the integer e$pression matches case constant; and case constant;+. !oes onehave to write two set of statements as shown below "
switch (integer e"pression)
case constant8statements3reak;
case constant>8statements3reak;
TT
he answer is no. 1ou only have to write one set of statements and this is how it is done.
switch (integer e"pression) case constant8 case constant>8
statements3reak;
his is called a multiple labels case.
he ne$t e$ample demonstrate the use of multiple labels case. his program counts the
vowels in a line of te$t entered. - counter for each vowel is defined, for e$ample, cnt;a forvowel
-
8/14/2019 5 if Statement
18/23
Making decision & choosing alternatives
case iJ8case IJ8
cntiQQ;3reak;
case oJ8case RJ8cntoQQ;3reak;
case uJ8case SJ8
cntuQQ;3reak;
default83reak;
!#$ end of switch $#
! #$ end of while $#printf (15nnum3er of vowels 8 A 7 I R S5n6);printf (1 9d 9d 9d 9d 9d5n6
cntacntecnticntocntu);!
he screen output
he program above uses awhileloop which has not been discussed yet. hewhileloop is
used to repeat a certain tasks as long as a certain condition is met. n this program, thewhile
loop tests if the key pressed is 2nter. f a key other than the 2nter key is pressed, the programwill check if it is a vowel, and increment the appropriate vowel counters if it is one. f the key
pressed is 2nter, the program quits thewhileloop and prints the values in the vowel
counters.
'onsider another e$ample. his program prompts the user for a ma$imum of 5 numbers, andthen add them up and calculate the average of the numbers entered. First, let=s start with thealgorithm and is represented in the flow chart in Fig 5.P
JJ
7nter a line of test; press 7nter to Fuit.=he Fuick 3rown fo" jumps over the la@y dog.
-um3er of vowels 8 A 7 I R S ? G >
Line of te$t enteredby user
-
8/14/2019 5 if Statement
19/23
Making decision & choosing alternatives
Fig 5.P
#$ %rogram &'T $#
#$ Add a ma"imum of & num3ers and calculates the average $#include*stdio.h+include*conio.h+
main() int numnum>num?numGnum&numE; int sum/4 -oofnum3ers; float Average/4.4;
clrscr();
printf(1Cow many num3ers you want to add U5n6); scanf(19d6:-oofnum3ers);
swicth(-oofnum3ers)
case 48case 8
printf(1Impossi3le to do addition.5n6); 3reak;
case >8printf(1Add two num3ers.5n6);printf(1Lirst num3er 8 6); scanf(19d6:num);
printf(1,econd num3er 8 6); scanf(19d6:num>);
J
3tart
'annot doaddition
ow many
numbers toadd", 0
Oet the + nos.add & averagethem
Oet the 4 nos.add & averagethem
Oet the 5 nos.add & averagethem
Oet the K nos.add & averagethem
oo manyto add
rintresults
2nd
0 09+ 094 09K 095 0)
-
8/14/2019 5 if Statement
20/23
Making decision & choosing alternatives
sum/numQnum>;Average / (float) sum#-oofnum3ers;printf(1,um / 9d and the average is 9.>f.5n6 sum Average);3reak;
case ?8
printf(1Add three num3ers.5n6);printf(1Lirst num3er 8 6); scanf(19d6:num);printf(1,econd num3er 8 6); scanf(19d6:num>);printf(1=hird num3er 8 6); scanf(19d6:num?);sum/numQnum>Qnum?;Average / (float) sum#-oofnum3ers;printf(1,um / 9d and the average is 9.>f.5n6 sum Average);3reak;
case G8printf(1Add four num3ers.5n6);printf(1Lirst num3er 8 6); scanf(19d6:num);
printf(1,econd num3er 8 6); scanf(19d6:num>);printf(1=hird num3er 8 6); scanf(19d6:num?);printf(1Lourth num3er 8 6); scanf(19d6:numG);sum/numQnum>Qnum?QnumG;Average / (float) sum#-oofnum3ers;printf(1,um / 9d and the average is 9.>f.5n6 sum Average);3reak;
case &8printf(1Add five num3ers.5n6);printf(1Lirst num3er 8 6); scanf(19d6:num);printf(1,econd num3er 8 6); scanf(19d6:num>);
printf(1=hird num3er 8 6); scanf(19d6:num?);printf(1Lourth num3er 8 6); scanf(19d6:numG);printf(1Lifth num3er 8 6); scanf(19d6:num&);sum/numQnum>Qnum?QnumGQnum&;Average / (float) sum#-oofnum3ers;printf(1,um / 9d and the average is 9.>f.5n6 sum Average);3reak;
default8printf(1=oo many num3ers to add.5n6);printf(1Sse a calculator.5n6);3reak;
! #$ end of switch $#
printf(15n5n6);printf(1=hatJs all folks.5n6);printf(1=hank S for using this program.5n6);printf(12ood3ye.5n6);printf(15n5nVuiting press any key to Fuit.5n6);getch();
!
JP
-
8/14/2019 5 if Statement
21/23
Making decision & choosing alternatives
hebreakstatement at the end of each case tells the program to break out from the switch
statement and continue with program e$ecution at end of the switchstatement.
f the break statement is not insert at the end of a case, program e$ecution continues into thene$t case. For e$ample, consider the following program segment.
case >8printf(1=he num3er is >.5n6);
case ?8printf(1=he num3er is ?.5n6);3reak;
case G8printf(1=he num3er is G.5n6)8
3reak;
f case + is true, the print out on the screen would look like this
#e can make use of this feature to simplify rogram 5IP. he flow chart for the simplerprogram is shown in Fig 5.*
Fig 5.*
*
0o break statement inthis case. rograme$ecution continues intocase 4
he number is +.he number is 4.
3tart
'annot doaddition
ow manynumbers toadd", 0
Oet the 5thnumber
Oet the Kthnumber
Oet the + nos.add & averagethem
Oet the 4rdnumber
oo manyto add
rintresults
2nd
0 095 09K 094 09+ 0)
-
8/14/2019 5 if Statement
22/23
Making decision & choosing alternatives
#$ %rogram &'4A shorter program P using switch ..case control structure without the 3reakstatement in some cases.$#
include*stdio.h+include*conio.h+
main() int numnum>num?numGnum&numE; int -oofnum3ers sum/4 count/; float Average/4.4;
num/num>/num?/numG/num&/numE/4; clrscr();printf(1Cow many num3ers you want to add U5n6);
scanf(19d6:-oofnum3ers);
switch (-oofnum3ers) #$ 3eginning of switch $#
case &8 printf(W-um3er 9d 8Wcount);scanf(W9dW:num&);countQQ;
case G8 printf(W-um3er 9d 8Wcount);scanf(W9dW:numG);countQQ;
case ?8 printf(W-um3er 9d 8Wcount);scanf(W9dW:num?);countQQ
case >8 printf(W-um3er 9d 8Wcount);scanf(W9dW:num>);countQQ;printf(W-um3er 9d 8Wcount);scanf(W9dW:num);
sum/numQnum>Qnum?QnumGQnum&;
Average / (float)sum#-oofnum3ers;printf(W,um/ 9d and Average / 9.>f5nWsumAverage);
3reak;
case 48
case 8printf(1Impossi3le to do addition.5n6);
3reak;
default8 printf(W=oo many num3ers to add.5nW); printf(WSse a calculator.5nW); 3reak;
! #$ end of switch $#
printf(15n5n6);printf(1=hatJs all folks.5n6);printf(1=hank S for using this program.5n6);printf(12ood3ye.5n6);printf(15n5nVuiting press any key to Fuit.5n6);getch();
!
-
8/14/2019 5 if Statement
23/23
Making decision & choosing alternatives
1our turn
2$amine rogram 5I* and answer the following questions?a@ f at the prompt RCow many num3ers you want to add US and K is entered, which
case will the program %ump to "
?b@ #hat does theprintfstatement (W-um3er 9d 8Wcount)do and what is the
value of the variable count"
?c@ #hat will be the value of count after this case is e$ecuted "
+ 6eIwrite then menu program using the switch control structure.
$$