Docsity

Progamming in C Language (Unit-2), Study notes of C programming

Toggle sidebar
bg1
LECTURENOTE-10

CONTROLSTATEMENTS
InC,programsareexecutedsequentiallyintheorderofwhichtheyappear.Thiscondition
doesnotholdtruealways.Sometimes a situation mayarisewhereweneed to execute a
certainpartoftheprogram.Alsoitmayhappenthatwemaywanttoexecutethesamepart
more than once. Control statements enable us to specifyt he order in whichth e various
instructionsinthe programaretobeexecuted.Theydefinehowthecontrolis transferred
tootherpartsoftheprogram.Controlstatementsareclassifiedinthefollowingways:



Fig:1Classificationofcontrolstatements






pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Progamming in C Language (Unit-2) and more Study notes C programming in PDF only on Docsity!

LECTURENOTE-10

CONTROLSTATEMENTS

InC,programsareexecutedsequentiallyintheorderofwhichtheyappear.Thiscondition doesnotholdtrue always.Sometimesasituation mayarisewhere weneed toexecutea certainpartoftheprogram.Alsoitmayhappenthatwemaywanttoexecutethesamepart more than once. Control statements enable us to specifythe order in whichthe various instructionsintheprogramaretobeexecuted.Theydefinehowthecontrolistransferred tootherpartsoftheprogram.Controlstatementsareclassifiedinthefollowingways:

Fig:1Classificationofcontrolstatements

SELECTIONSTATEMENTS

TheselectionstatementsarealsoknownasBranchingorDecisionControlStatements.

IntroductiontoDecisionControlStatements

Sometime we come across situations where we have to make a decision. E.g. If the weatherissunny,Iwillgoout&play,elseIwillbeathome.Heremycourseofactionis governed by the kind of weather. If it’s sunny, I can go out & play, elseI have to stay indoors.Ichooseanoptionoutof2alternateoptions.Likewise,wecanfindourselvesin situations wherewe havetoselectamongseveralalternatives.Wehavedecisioncontrol statementstoimplementthislogicincomputerprogramming.

Decisionmakingstructuresrequirethattheprogrammerspecifyoneormoreconditionsto beevaluatedortestedbytheprogram,alongwithastatementorstatementstobeexecuted iftheconditionisdeterminedtobetrue,andoptionally,otherstatementstobeexecutedif theconditionisdeterminedtobefalse.

ifStatement

Thekeywordiftellsthecompilerthatwhatfollowsisadecisioncontrolinstruction.Theif statementallowsustoputsomedecision-makingintoourprograms.Thegeneralformof theifstatementisshownFig2:

Fig2:ifstatementconstruct

scanf("%d",&no); if(no<0) { printf("noenteredisnegative"); no=-no; } printf("valueofnois%d\n",no); return0; }

Output:

Enterano:6

valueofnois6

Output:

Enterano:-2

valueofnois2

2.Writeaprogramtoperformdivisionof2nos

#include intmain() { inta,b; floatc; printf("Enter2nos:"); scanf("%d%d",&a,&b); if(b==0) { printf("Divisionisnotpossible"); } c=a/b; printf("quotientis%f\n",c); return0; }

Output: Enter2nos:62 quotientis3

Output: Enter2nos:60 Divisionisnotpossible

if-elseStatement

Theifstatementby itselfwillexecuteasinglestatement,oragroupofstatements,when the expressionfollowing ifevaluatestotrue.By using elseweexecute anothergroup of statementsiftheexpressionevaluatestofalse.

if(a>b) {z=a; printf(“valueofzis:%d”,z); } else {z=b; printf(“valueofzis:%d”,z); } The groupofstatementsaftertheifiscalledan‘ifblock’.Similarly,thestatementsafter

theelseformthe‘elseblock’.

Programs:

3.Writeaprogramtocheckwhetherthegivennoisevenorodd

#include intmain() { intn; printf("Enteraninteger\n"); scanf("%d",&n); if(n%2==0) printf("Even\n"); else

Nestedif-else

Anentireif-elseconstructcanbewrittenwithineitherthebodyofthe ifstatementorthe

body of an else statement.This is called‘nesting’of ifs.This isshown inthefollowing

structure.

if(n>0)

{ if(a>b) z=a; } else z=b; The second if construct is nested in the first if statement. If the condition in the first if statement is true, then thecondition in the second if statement is checked. If it is false, thentheelsestatementisexecuted. Program: 5.Writeaprogramtocheckfortherelationbetween2nos

#include intmain() { intm=40,n=20; if((m>0)&&(n>0)) { printf("nosarepositive"); if(m>n) { printf("misgreaterthann"); } else { printf("mislessthann"); } } else

printf("nosarenegative");^ } return0; } Output 40isgreaterthan20

else-ifStatement:

Thissequenceofifstatementsis themost generalwayofwriting amulti−waydecision. The expressionsare evaluatedin order; ifan expressionistrue, thestatement associated with it is executed, and this terminates the whole chain. As always, the code for each statementiseitherasinglestatement,oragroupoftheminbraces. (^) If(expression) statement elseif(expression) statement elseif(expression) statement elseif(expression) statement else statement Thelastelseparthandlesthe``noneoftheabove''ordefaultcasewherenoneoftheother conditionsis satisfied.Sometimes thereis no explicitactionforthe default; inthat case thetrailingcanbeomitted,oritmaybeusedforerrorcheckingtocatchan“impossible” condition. Program: 6.Theaboveprogramcanbeusedasaneghere. #include intmain() {

The integerexpressionfollowing thekeywordswitch isanyC expressionthatwillyield an integer value. It could be an integer constant like 1, 2 or 3, or an expression that evaluates to an integer. If a case matches the expression value, execution starts at that case.Allcaseexpressionsmustbedifferent.Thecaselabelled defaultisexecutedifnone of the other cases are satisfied. Adefaultisoptional; if it isn't there and if none of the cases match, no action atall takesplace. Casesand the default clause can occur in any order. Considerthefollowingprogram: main() {inti=2;switch (i) { case1: printf("Iamincase1\n"); case2: printf("Iamincase2\n"); case3: printf("Iamincase3\n"); default: printf("Iamindefault\n");} } Theoutputofthisprogramwouldbe: Iamincase2 Iamincase3 Iamindefault Here the program printscase2and3 and thedefaultcase.If youwantthat onlycase2 shouldgetexecuted,itisuptoyoutogetoutoftheswitchthenandtherebyusingabreak statement. main() { inti=2; switch(i) { case1: printf("Iamincase1\n");

break; case2: printf("Iamincase2\n"); break; case3: printf("Iamincase3\n"); break; default: printf("Iamindefault\n"); } } Theoutputofthisprogramwouldbe: Iamincase2 Program 7.WAPtoenteragrade&checkitscorrespondingremarks. #include intmain() { chargrade; printf(“Enterthegrade”); scanf(“%c”,&grade); switch(grade) { case'A':printf("Outstanding!\n"); break; case'B':printf("Excellent!\n"); break; case'C':printf("Welldone\n"); break; case'D':printf("Youpassed\n"); break; case'F':printf("Bettertryagain\n"); break; default:printf("Invalidgrade\n"); }

LECTURENOTE-11

ITERATIVESTATEMENTS

whilestatement

The while statement is used when the program needs to perform repetitive tasks. The generalformofawhilestatementis: while(condition) statement; The program will repeatedly execute the statement inside the while until the condition becomes false(0). (Ifthe condition is initially false,the statement will not be executed.) Considerthefollowingprogram: main() {intp,n,count; floatr,si; count=1; while(count<=3) { printf("\nEntervaluesofp,nand r"); scanf(“%d%d%f",&p,&n,&r); si=pnr/100; printf("Simpleinterest=Rs.%f",si); count=count+1; } } Someoutputsofthisprogram: Entervaluesofp,nandr1000513.5 SimpleInterest=Rs.675.000000 Entervaluesofp,nandr2000513.5 SimpleInterest=Rs.1350.000000 Entervaluesofp,nandr3500513.5 SimpleInterest=Rs.612.000000

The programexecutesall statementsafter thewhile3times.Thesestatementsformwhat iscalledthe‘body’ofthewhileloop.Theparenthesesafterthewhilecontainacondition. As long as this condition remains true all statements withinthe body of the while loop keepgettingexecutedrepeatedly. Considerthefollowingprogram; /Thisprogramcheckswhetheragivennumberisapalindromeornot/ #include intmain() { intn,reverse=0,temp; printf("Enteranumbertocheckifitisapalindromeornot\n"); scanf("%d",&n); temp=n; while(temp!=0) { reverse=reverse*10; reverse=reverse+temp%10; temp=temp/10; } if(n==reverse) printf("%disapalindromenumber.\n",n); else printf("%disnotapalindromenumber.\n",n); return0; } Output: Enteranumbertocheckifitisapalindromeornot 12321 12321isapalindrome Enteranumbertocheckifitisapalindromeornot 12000 12000isnotapalindrome

sum=1 (^) Considerthefollowingprogram: #include main() { inti=10; do { printf("Hello%d\n",i); i=i-1; }while(i>0); } Output Hello10 Hello9 Hello8 Hello7 Hello6 Hello5 Hello4 Hello3 Hello2 Hello1 Program 8.Programtocountthenoofdigitsinanumber #include intmain() { intn,count=0; printf("Enteraninteger:"); scanf("%d",&n);

do { (^) n/=10;/n=n/10/ count++; }while(n!=0); printf("Numberofdigits:%d",count); } Output Enteraninteger:34523 Numberofdigits:5

forLoop

The for isthe most popularloopinginstruction.The generalform of for statement is as under: for(initialisecounter;testcounter;Updatingcounter) { dothis;

andthis;

andthis;

} Theforallowsustospecifythreethingsaboutaloopinasingleline: (a)Settingaloopcountertoaninitialvalue. (b)Testingtheloopcountertodeterminewhetheritsvaluehasreachedthenumberof repetitionsdesired. (c)Updatingthevalueofloopcountereitherincrementordecrement. Considerthefollowingprogram intmain(void) { intnum; printf("nncubed\n"); for(num=1;num<=6;num++)

intn,i,sum=0; printf("Enterthelimit:"); scanf("%d",&n);

for(i=1;i<=n;i++) { sum=sum+i; } printf("SumofNnaturalnumbersis:%d",sum); } Output Enterthelimit:5 SumofNnaturalnumbersis15. 10.Programtofindthereverseofanumber #include intmain() { intnum,r,reverse=0; printf("Enteranynumber:"); scanf("%d",&num); for(;num!=0;num=num/10) { r=num%10; reverse=reverse*10+r; } printf("Reversedofnumber:%d",reverse); return0; } Output: Enteranynumber:123 Reversedofnumber:321

NESTINGOFLOOPS

Cprogramminglanguageallowsusingoneloopinsideanotherloop.Followingsectionshowsfew examplestoillustratetheconcept.

Syntax:

ThesyntaxforanestedforloopstatementinCisasfollows:

for(init;condition;increment) {

for(init;condition;increment)

{ statement(s); } statement(s); } ThesyntaxforanestedwhileloopstatementinCprogramminglanguageisasfollows: while(condition) { while(condition) { statement(s); } statement(s); } Thesyntaxforanesteddo...whileloopstatementinCprogramminglanguageisasfollows: do { statement(s); do { statement(s); }while(condition);