cs202ch2.docx
《cs202ch2.docx》由会员分享,可在线阅读,更多相关《cs202ch2.docx(16页珍藏版)》请在冰豆网上搜索。
![cs202ch2.docx](https://file1.bdocx.com/fileroot1/2023-1/27/79dc0be3-7adf-45e6-bf73-8b8fb29733a3/79dc0be3-7adf-45e6-bf73-8b8fb29733a31.gif)
cs202ch2
COURSE:
CLanguage(CS102)
UNIT:
2.1
CONTROLSTRUCTURE
SEQUENCE
*Instructionsareexecutedoneafteranotherwithoutbranching.
*E.g.#include
main()
{
inta,b;
printf("Enterthefirstinteger");
scanf("%d",&a);
printf("Enterthesecondinteger\n");
scanf("%d",&b);
printf("Sumis%d\n",a+b);
return0;
}
SELECTIONSTRUCTURE
Aselectionstructureisusedtochooseamongdifferentactions.
<1>SingleSelection(IFSelectionStructure)
*Itperformsanactiononlywhenaconditionistrue.
*Format:
if(condition)
statement
Problem:
printthewordPassedifthegradeisgreaterthan60
Coding:
if(grade>60)
printf("Passed\n");(printonlyifgrade>60)
Warning:
if(grade>60);->if(grade>60);
printf(“Passed\n”);printf(“Passed\n”);
(printwithanygrade)
<2>DoubleSelection(IF/ELSESelectionStructure)
*Itperformsanactionwhenaconditionistrue,
performadifferentactionwhentheconditionisfalse
*Format:
if(condition)
statement-1
else
statement-2
Problem:
printthewordPassedifthegradeisgreaterthan60
printthewordFailedifthegradeisbeloworequal60
Coding:
if(grade>60)
printf("Passed\n");
else
printf("Failed\n");
<3>MultipleSelection
NestedIF/ELSESelectionStructure
*Format:
if(condition-1)
statement-1
elseif(condition-2)
statement-2
.........
*Problem
(1):
printAforthemarksgreaterthanorequalto80.
printBforthemarkgreaterthanorequalto70.
printCforthemarkgreaterthanorequalto60.
AndFforothermarks
*Coding:
if(grade>=80)//80-100
printf("A\n");
elseif(grade>=70)//70-79
printf("B\n");
elseif(grade>=60)//60-69
printf("C\n");
else//59orbelow
printf("F\n");
*ifselectionstructureexpectsonlyonestatementinitsbody,toinclude
severalstatementsinthebody,enclosethesetofstatementsusing{}
*E.g.if(grade<60)
{
printf("Failed\n");
printf("Youmustworkhard\n");
}
elseif……..
*Problem
(2):
Convertanintegerintothecorrespondingdayofaweek.
*Coding:
if(day==1)
printf("TodayisMonday\n");
elseif(day==2)
printf("TodayisTuesday\n");
elseif(day==3)
printf("TodayisWednesday\n");
elseif(day==4)
printf("TodayisThursday\n");
elseif(day==5)
printf("TodayisFriday\n");
elseif(day==6)
printf("TodayisSaturday\n");
elseprintf(“TodayisSunday\n”)
Switchstructure(multipleselection)
Problem:
Convertanintegerintothecorrespondingdayofaweek.
Coding:
main()
{
intday;
printf("Enteranintegerbetween1to7.Enter-1toquit:
");
scanf("%d",&day);
switch(day)
{
case1:
printf("TodayisMonday\n\n");
break;
case2:
printf("TodayisTuesday\n\n");
break;
case3:
printf("TodayisWednesday\n\n");
break;
case4:
printf("TodayisThursday\n\n");
break;
case5:
printf("TodayisFriday\n\n");
break;
case6:
printf("TodayisSaturday\n\n");
break;
case7:
printf("TodayisSunday\n\n");
break;
default:
printf("IncorrectNumberEntered!
");
break;
}
return0;
}
Enteranintegerbetween1to7.Enter-1toquit:
1
TodayisMonday
Enteranintegerbetween1to7.Enter-1toquit:
6
TodayisSaturday
Enteranintegerbetween1to7.Enter-1toquit:
9
IncorrectNumberEntered!
!
!
Enteranintegerbetween1to7.Enter-1toquit:
-1
Break
*Theswitchstructureisexitedimmediatelywiththebreakstatement.
*Ifbreakisnotused,evenamatchisfound,thestatementsforallthe
remainingcaseswillstillbeexecuted.
*breakcan/cannotbeusedindefaultstatement(laststatement)
Default
*Ifnomatchoccurs,thedefaultcaseisexecuted
*placethedefaultclauseattheendoftheswitchstructure.
Case
*Eachcasecanhaveoneormoreactionandbraces{}arenotrequired
aroundmultipleactioninacaseofaswitch
Switch
*switchstructurecanonlybeusedfortestingaconstant
integralexpression,thatis,anycombinationofcharacterconstants
andintegerconstantsthatevaluatestoaconstantintegervalue.
switch(day)
{
E.g.<1>case1:
..
case2:
..
E.g.<2>case'a':
..
case'b':
..
E.g.<3>case"abc":
..WRONGUSE!
!
!
!
!
case"123":
..
}
REPETITION(looping)STRUCTURE
*Anactionwillberepeatedwhilesomeconditionremainstrue.
*Theactionwillstoponlyiftheconditionbecomefalse.
<1>WHILERepetitionStructure
*Format:
while(condition)
statement
*Problem
(1):
sumalltheintegerfrom1to10
*Coding:
main()
{
intsum,number;
sum=0;
number=1;
while(number<=10)
{
sum=sum+number;
number++;
}
printf(“Sumis%d”,sum);
}
*Therewillbeaninfiniteloopiftheconditionalwaystrue.
*Mustbeanactionthateventuallycausetheconditiontobecomefalse
*Probem
(2):
Determinetheclassaverageofatesttakenby5student.
*Coding:
main()
{
intstudent_counter,total_mark,mark;
doubleaverage;
total_mark=0;
student_counter=1;
while(student_counter<=5)
{
printf("Pleaseenterthemark:
");
scanf("%d",&mark);
total_mark=total_mark+mark;
student_counter=student_counter+1;
}
average=total_mark/5;
printf("Theclassaverageis%lf\n",average);
return0;
}
*OUTPUT:
Pleaseenterthemark:
50
Pleaseenterthemark:
10
Pleaseenterthemark:
90
Pleaseenterthemark:
93
Pleaseenterthemark:
50
Theclassaverageis58.000000
*Actualaverageshouldbe(50+50+10+90+93)/558.6
Why%fprints58.000000insteadof58.6?
?
?
?
NOTE:
average=total_mark/10;
(float)(int)(int)
Integerdivisionyieldsanintegerresult
Significantdigitsarecut.
*Problem
(2)RevisedProgram
*Coding:
main()
{intstudent_counter,mark;
doubleaverage,total_mark;
total_mark=0;
student_counter=0;
printf("Enterthemark,orenter-1toend:
");
scanf("%d",&mark);
while(mark!
=-1)
{
total_mark=total_mark+mark;
student_counter=student_counter+1;
printf("Plsenterthenextmark,orenter-1toend:
");
scanf("%d",&mark);
}
if(student_counter!
=0)
{
average=total_mark/student_counter;
printf("Theclassaverageis%.3lf\n",average);
}
else
printf("Nomarkswereentered\n");
return0;
}
*OUTPUT<1>
Enterthemark,orenter-1toend:
50
Pleaseenterthenextmark,orenter-1toend:
10
Pleaseenterthenextmark,orenter-1toend:
90
Pleaseenterthenextmark,orenter-1toend:
93
Pleaseenterthenextmark,orenter-1toend:
50
Pleaseenterthenextmark,orenter-1toend:
-1
Theclassaverageis58.600
*OUTPUT<3>
Enterthemark,orenter-1toend:
-1
Nomarkswereentered
*Formatstring"%.3f"
.3->afloating-pointwith3decimaldigitstotherightofdecimalpoint.
eg.printf("%.2f",9.348);9.35
eg.printf("%.1f",9.348);9.3
eg.printf("%.0f",9.348);9
Thedefaultprecisionis(%.6f==%f)
*Precisionareonlyusedinprintf,notscanf.
eg.scanf(“%.5lf\n”,&a)wrong!
!
!
scanf(“%lf”,&a)
*Donotcomparefloating-pointvalueforequality.
<2>DO/WHILEStructure
Ittesttheloop-continuationconditionaftertheloopbodyisperformed,soloop
bodywillbeexecutedatleastonce.
*Format:
do{
statements;
}
while(condition);
*Problem:
Findtheno.oftimesthestatementshasbeenexecutedintheloop.
*CodingUsingDo/WhileLoop:
main()
{intloop_count,number;
loop_count=0;
number=0;
do{
loop_count++;
number--;
}
while(number>0);
printf("Loop_countis%d\n",loop_count);
printf("Numberis%d\n",number);
return0;
}
Numberis-1
*CodingUsingWhileLoop:
main()
{intloop_count,number;
loop_count=0;
number=0;
while(number>0)
{
loop_count++;
number--;
}
printf("Loop_countis%d\n",loop_count);
printf("Numberis%d\n",number);
return0;
}
Numberis0
<3>FORStructure
*Problem:
Print1to10
1
*Coding
(1):
main()2
{intcounter;3
4
for(counter=1;counter<=10;counter++)5
{6
printf("%d",counter);:
printf("\n");:
}
return0;
}
*Coding
(2):
main()
{intcounter=1;
for(;counter<11;counter++)
printf("%d",counter);
printf(“\n”);
return0;
}
*
*for(counter=1;counter<=10;counter++)
Initialization,repetitioncondition,incrementareallputintheheader.
-Initializationoccursonlyonce,
-Incrementoccursafterthebodystatementisperformed.
124
for(counter=1;counter<=10;counter++)
{
printf("%d",counter);
3printf("\n");
}
1234
*Thecondition(counter<=10)or(counter<11)isOK
But(counter<10)willrunonly9timeandcausedoff-by-oneerror.
*ForLoopWhileLoop
main()main()
{{
intcount;intcount;
for(count=1;count<=10;count++)count=1;
printf("%d",count);while(count<=10)
printf(“\n”);{
return0;printf("%d",count);
}count++;
}
printf(“\n”);
return0;
}
*Initialization,condition,and