control statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/l2... · 2019-08-14 · the...

76
Control Statements Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute of Technology Kharagpur

Upload: others

Post on 23-Mar-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

ControlStatements

IndranilSenGupta

Dept.ofComputerScience&Engg.IndianInstituteofTechnology

Kharagpur

Page 2: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 2

Whatdotheydo?

• Allowdifferentsetsofinstructionstobeexecuteddependingontheoutcomeofalogicaltest.– WhetherTRUEorFALSE.– Thisiscalledbranching.

• Someapplicationsmayalsorequirethatasetofinstructionsbeexecutedrepeatedly,possiblyagainbasedonsomecondition.– Thisiscalledlooping.

Page 3: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 3

Howdowespecifytheconditions?

• Usingrelationaloperators.– Fourrelationoperators: <,<=,>,>=– Twoequalityoperators: ==,!=

• Usinglogicaloperators/connectives.– Twologicalconnectives: &&,||– Unarynegationoperator: !

Page 4: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 4

Examples

count <= 100

(math+phys+chem)/3 >= 60(sex == ’M’) && (age >= 21)(marks >= 80) && (marks < 90)(balance>5000) || (no_of_trans>25)

!(grade ==‘A’)!((x>20) && (y<16))

Page 5: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 5

Theconditionsevaluateto…

• Zero– IndicatesFALSE.

• Non-zero– IndicatesTRUE.– TypicallytheconditionTRUEisrepresentedbythevalue‘1’.

Page 6: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 6

Branching:TheifStatement

• Diamondsymbol(decisionsymbol)- indicatesdecisionistobemade.– ContainsanexpressionthatcanbeTRUEorFALSE.– Testthecondition,andfollowappropriatepath.

• Single-entry/single-exitstructure.

• Generalsyntax:if(condition) {……..}

– Ifthereisasinglestatementintheblock,thebracescanbeomitted.

Page 7: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 7

A decision can be made on any expression.

zero - false

nonzero - true

if (grade>=60){printf(“Passed \n”);printf(“Good luck\n”);

}

grade >= 60

print “passed; good luck”

true

false

Page 8: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 8

Example

#include <stdio.h>main() {

int a,b,c;scanf (ʺ%d %d %dʺ, &a, &b, &c);if ((a>=b) && (a>=c))

printf (ʺ\n The largest number is: %dʺ, a);if ((b>=a) && (b>=c))

printf (ʺ\n The largest number is: %dʺ, b);if ((c>=a) && (c>=b))

printf (ʺ\n The largest number is: %dʺ, c);}

Page 9: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 9

ConfusingEquality(==)andAssignment(=)Operators

• Dangerouserror– Doesnotordinarilycausesyntaxerrors.– Anyexpressionthatproducesavaluecanbeusedincontrolstructures.

– Nonzerovaluesaretrue,zerovaluesarefalse.

• Example:if (payCode = = 4)

printf(ʺYou get a bonus!\nʺ);

if (payCode = 4)printf(ʺYou get a bonus!\nʺ); WRONG

Page 10: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 10

SomeExamples

if (10<20) { a = b + c; printf (ʺ%dʺ, a); }

if ((a>b) && (x=10)) { …………… }

if (1) { ……………… }

if (0) { ……………… }

Page 11: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 11

Branching:Theif-elseStatement

• Alsoasingle-entry/single-exitstructure.

• Allowsustospecifytwoalternateblocksofstatements,oneofwhichisexecuteddependingontheoutcomeofthecondition.

• Generalsyntax:if (condition) { …… block 1 …… }else { …… block 2 …… }

– Ifablockcontainsasinglestatement,thebracescanbedeleted.

Page 12: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 12

if ( grade >= 60 ) printf ("Passed\n");

elseprintf ("Failed\n");

grade >= 60 print “Passed”truefalse

print “Failed”

Page 13: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 13

Nestingofif-elseStructures

• Itispossibletonestif-elsestatements,onewithinanother.

• Allifstatementsmaynotbehavingthe“else”part.– Confusion??

• Ruletoberemembered:– An“else”clauseisassociatedwiththeclosestprecedingunmatched“if”.

– Someexamplesshownnext.

Page 14: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 14

if e1 s1else if e2 s2

if e1 s1

else if e2 s2else s3

if e1 if e2 s1

else s2else s3

if e1 if e2 s1

else s2

?

Page 15: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 15

ife1s1 ife1s1elseife2s2 elseife2s2

ife1s1 ife1s1elseife2s2 elseife2s2elses3 elses3

ife1ife2s1 ife1ife2s1elses2 elses2elses3 elses3

ife1ife2s1 ife1ife2s1elses2 elses2

Page 16: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 16

Example#include <stdio.h>main()

{

int a,b,c;

scanf (ʺ%d %d %dʺ, &a, &b, &c);if (a>=b)

if (a>=c)

printf (ʺ\n The largest is: %dʺ, a);

else printf (ʺ\n The largest is: %dʺ, c);else

if (b>=c)

printf (ʺ\n The largest is: %dʺ, b);

else printf (ʺ\n The largest is: %dʺ, c);}

Page 17: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 17

Example

#include <stdio.h>main() {

int a,b,c;scanf (ʺ%d %d %dʺ, &a, &b, &c);if ((a>=b) && (a>=c))

printf (ʺ\n Largest number is: %dʺ, a);else if (b>c)

printf (ʺ\n Largest number is: %dʺ, b);else

printf (ʺ\n Largest number is: %dʺ, c);}

Page 18: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 18

TheConditionalOperator?:

• Thismakesuseofanexpressionthatiseithertrueorfalse.Anappropriatevalueisselected,dependingontheoutcomeofthelogicalexpression.

• Example:interest = (balance>5000) ? balance*0.2 : balance*0.1;

Returnsavalue

Page 19: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 19

• Examples:

x = ((a>10) && (b<5)) ? a+b : 0

(marks>=60) ? printf(ʺPassed \nʺ) : printf(ʺFailed \nʺ);

Page 20: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 20

TheswitchStatement

• Thiscausesaparticulargroupofstatementstobechosenfromseveralavailablegroups.– Uses“switch”statementand“case”labels.– Syntaxofthe“switch”statement:

switch (expression) {case expression-1: { …… }case expression-2: { …… }

case expression-m: { …… }default: { ……… }

}

where“expression”evaluatestointorchar

Page 21: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 21

Example

switch (letter) {

case 'A':

printf (ʺFirst letter \nʺ);

break;case 'Z':

printf (ʺLast letter \nʺ);break;

default :

printf (ʺMiddle letter \nʺ);break;

}

Page 22: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 22

ThebreakStatement

• Usedtoexitfromaswitchorterminatefromaloop.– Alreadyillustratedinthepreviousexample.

• Withrespectto“switch”,the“break”statementcausesatransferofcontroloutoftheentire“switch”statement,tothefirststatementfollowingthe“switch”statementblock.

Page 23: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 23

Example

switch (choice = getchar()) {

case ’r’:case ’R’: printf (ʺRED \nʺ);

break;case ’g’:case ’G’: printf (ʺGREEN \nʺ);

break;case ’b’:case ’B’: printf (ʺBLUE \nʺ);

break;default: printf (ʺInvalid choice \nʺ);

}

Page 24: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 24

Example

switch (choice = toupper(getchar())) {

case ’R’: printf (ʺRED \nʺ);break;

case ’G’: printf (ʺGREEN \nʺ);break;

case ’B’: printf (ʺBLUE \nʺ);break;

default: printf (ʺInvalid choice \nʺ);}

Page 25: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

int main () {int operand1, operand2;int result = 0;char operation;/* Get the input values */printf (ʺEnter operand1 :ʺ);scanf(ʺ%dʺ, &operand1) ;

printf (ʺEnter operation :ʺ);scanf (ʺ\n%cʺ, &operation);

printf (ʺEnter operand 2 :ʺ);scanf (ʺ%dʺ, &operand2);

switch (operation) {case ′+′ :result = operand1 + operand2;break;

case ′-′ :result = operand1 - operand2;break;

case ′*′ :result = operand1 * operand2;break;

case ′/′ :if (operand2 !=0)result = operand1 / operand2;elseprintf (ʺDivide by 0 errorʺ);break;

default:printf (ʺInvalid operation\nʺ);

}printf (ʺResult: %d\nʺ,result);

}

Programming and DataStructureAutumn Semester2019 25

Page 26: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 26

• The“switch”statementalsoconstitutesasingle-entry/single-exitstructure.

switch statement

Page 27: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

ALookBackatArithmeticOperators:theIncrementandDecrement

Page 28: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 28

Increment(++)andDecrement(--)

• Bothoftheseareunaryoperators;theyoperateonasingleoperand.

• Theincrementoperatorcausesitsoperandtobeincreasedby1.– Example: a++, ++count

• Thedecrementoperatorcausesitsoperandtobedecreasedby1.– Example: i--, --distance

Page 29: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 29

• Operatorwrittenbeforetheoperand(++i,--i)– Calledpre-incrementoperator.– Operandwillbealteredinvaluebefore itisutilizedforitsintendedpurposeintheprogram.

• Operatorwrittenaftertheoperand(i++,i--)– Calledpost-incrementoperator.– Operandwillbealteredinvalueafter itisutilizedforitsintendedpurposeintheprogram.

Page 30: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 30

Examples

Initial values :: a = 10; b = 20;

x = 50 + ++a; a = 11, x = 61

x = 50 + a++; x = 60, a = 11

x = a++ + --b; b = 19, x = 29, a = 11

x = a++ – ++a; Undefined value (implementation

dependent)

Called side effects:: while calculating some values, something else get changed.

Page 31: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

ControlStructuresthatAllowRepetition

Page 32: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

TypesofRepeatedExecution

• Loop:Groupofinstructionsthatareexecutedrepeatedlywhilesomeconditionremainstrue.

Howloopsarecontrolled?

SentinelControlled

CounterControlled Condition

Controlled

Autumn Semester2019 32Programming and DataStructure

Page 33: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 33

• Counter-controlledrepetition– Definiterepetition– knowhowmanytimesloopwillexecute.

– Controlvariableusedtocountrepetitions.

• Condition-controlledrepetition– Loopexecutesaslongassomespecifiedconditionistrue.

• Sentinel-controlledrepetition– Indefiniterepetition.

– Usedwhennumberofrepetitionsnotknown.

– Sentinelvalueindicates“endofdata”.

Page 34: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 34

Counter-controlledRepetition

• Counter-controlledrepetitionrequires:– name ofacontrolvariable(orloopcounter).– initialvalue ofthecontrolvariable.– condition thattestsforthefinalvalueofthecontrolvariable(i.e.,whetherloopingshouldcontinue).

– increment(ordecrement) bywhichthecontrolvariableismodifiedeachtimethroughtheloop.

Page 35: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

CounterControlledLoop

Read 5 integers and display the value of their sum.

counter←1,sum←0

counter<6

sum←sum+n

falsetrue

counter++

outputsum

input nint counter=1, sum=0, n;

while (counter <6 ) { scanf (“%d”, &n);sum = sum + n;counter++;

}

printf (ʺ\nSum is: %dʺ,sum);

35

Page 36: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 36

int counter, sum=0, n;

for (counter=1;counter<6; counter++)

{

scanf(ʺ%dʺ, &n);sum = sum + n;

}

printf(ʺ\nSum is: %dʺ, sum);

Page 37: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 37

whileStatement

• The“while”statementisusedtocarryoutloopingoperations,inwhichagroupofstatementsisexecutedrepeatedly,aslongassomeconditionremainssatisfied.

while (condition)statement_to_repeat;

while (condition) {

statement_1;...

statement_N;}

Page 38: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 38

C

statement(s)

true

falseSingle-entry/single-exitstructure

Page 39: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 39

while ::Examples

int digit = 0;

while (digit <= 9)

printf (ʺ%d \nʺ, digit++);

int weight=100;

while ( weight > 65 )

{

printf (ʺGo, exercise,ʺ);

printf (ʺthen come back. \nʺ);

printf (ʺEnter your weight:ʺ);scanf (ʺ%dʺ, &weight);

}

Page 40: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Example:SumofNNaturalNumbers

START

READN

SUM=0COUNT=1

SUM=SUM+COUNT

COUNT=COUNT+1

ISCOUNT>N? OUTPUTSUM

STOP

YESNO

int main () {int N, count, sum;scanf (ʺ%dʺ, &N);sum = 0;count = 1;while (count <= N) {

sum = sum + count;count = count + 1;

}printf (ʺSum=%d\nʺ, sum);return 0;

}

Autumn Semester2019 40Programming and DataStructure

Page 41: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Example:Maximumofinputs

printf (ʺEnter positive numbers, end with -1.0\nʺ);max = 0.0;

scanf(ʺ%fʺ, &next);

while (next != -1.0) {if (next > max)

max = next;

scanf(ʺ%fʺ, &next);

}

printf (ʺThe maximum number is %f\nʺ, max) ;

Example of Sentinel-controlled loopInputs: 10 5 100 25 68 -1

Autumn Semester2019 41Programming and DataStructure

Page 42: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 42

do-whileStatement

• Similarto“while”,withthedifferencethatthecheckforcontinuationismadeattheend ofeachpass.– In“while”,thecheckismadeatthebeginning.

• Loopbodyisexecutedatleastonce.

do {statement-1;statement-2;

statement-n;} while (condition );

dostatement_to_repeat;

while (condition );

Page 43: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 43

C

statement(s)

true

false

Single-entry/single-exitstructure

Page 44: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 44

do-while::Examples

int digit = 0;

do

printf (ʺ%d \nʺ, digit++);

while (digit <= 9);

int weight;

do {

printf (ʺGo, exercise, ʺ);

printf (ʺthen come back. \nʺ);

printf (ʺEnter your weight:ʺ);

scanf (ʺ%dʺ, &weight);} while (weight > 65 );

Page 45: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 45

for Statement

• The“for”statementisthemostcommonlyusedloopingstructureinC.

• Generalsyntax:

for (expression1; expression2; expression3)

statement-to-repeat;

for (expression1; expression2; expression3)

{

statement_1;:

statement_N;

}

Page 46: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 46

• Howitworks?– “expression1”isusedtoinitialize somevariable(calledindex)thatcontrolstheloopingaction.

– “expression2”representsacondition thatmustbetrueforthelooptocontinue.

– “expression3”isusedtoalter thevalueoftheindexinitiallyassignedby“expression1”.

int digit;

for (digit=0; digit<=9;digit++)

printf (ʺ%d \nʺ, digit);

int digit;

for (digit=9;digit>=0;digit--)

printf (ʺ%d \nʺ, digit);

Page 47: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 47

Single-entry/single-exitstructure

expression2

statement(s)

true

false

expression1

expression3

Page 48: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 48

for::Examples

int fact = 1, i, N;

scanf (ʺ%dʺ, &N);

for (i=1; i<=N; i++)fact = fact * i;

printf (ʺ%d \nʺ, fact);

int sum = 0, N, i;

scanf (ʺ%dʺ, &N);

for (i=1; i<=N; i++)sum = sum + i * i;

printf (ʺ%d \nʺ, sum);

Compute factorialSum of squares of N natural numbers

Page 49: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

2-DFigure

Print***************

#define ROWS 3#define COLS 5....for (row=1; row<=ROWS; row++) {

for (col=1; col<=COLS; col++) {printf(ʺ*ʺ);

}printf(ʺ\nʺ);

}

Autumn Semester2019 49Programming and DataStructure

Page 50: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Another2-DFigure

Print***************

#define ROWS 5....int row, col;for (row=1; row<=ROWS; row++) {

for (col=1; col<=row; col++) {printf(ʺ* ʺ);

}printf(ʺ\nʺ);

}

Autumn Semester2019 50Programming and DataStructure

Page 51: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 51

• Thecommaoperator– Wecangiveseveralstatementsseparatedbycommasinplaceof“expression1”,“expression2”,and“expression3”.

for (fact=1, i=1; i<=10; i++)

fact = fact * i;

for (sum=0, i=1; i<=N, i++)

sum = sum + i*i;

expression2

statement(s)

true

false

expression1

expression3

Page 52: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 52

for::SomeObservations

• Arithmeticexpressions– Initialization, loop-continuation, andincrementcancontainarithmeticexpressions.for (k=x; k <= 4*x*y; k += y/x)

• "Increment"maybenegative(decrement)for (digit=9; digit>=0; digit--)

• Ifloopcontinuationconditioninitiallyfalse:– Bodyoffor structurenotperformed.– Controlproceedswithstatementafterfor structure.

Page 53: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Acommonmistake(;attheend)

Autumn Semester2019 Programming and DataStructure 53

int fact = 1, i;

for (i=1; i<=10; i++)fact = fact * i;

printf (ʺ%d \nʺ, fact);

int fact = 1, i;

for (i=1; i<=10; i++);fact = fact * i;

printf (ʺ%d \nʺ, fact);

Loopbodywillexecuteonlyonce!

Page 54: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 54

Specifying“InfiniteLoop”

while (1) {statements

}

for (; ;){

statements

}

do {statements

} while (1);

Page 55: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 55

The“break”StatementRevisited

• Breakoutoftheloop{}– canusewith

• while• dowhile• for• switch

– doesnotworkwith• if• else

• Causesimmediateexitfromawhile,do/while,for orswitchstructure.

• Programexecutioncontinueswiththefirststatementafterthestructure.

Page 56: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 56

Anexamplewith“break”

#include <stdio.h>main(){

int fact, i;

fact = 1; i = 1;

while (i<10) { /* break when fact >100 */fact = fact * i;if ( fact > 100 ) {

printf (ʺFactorial of %d above 100ʺ, i);break; /* break out of the loop */

}i++;

}}

Page 57: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 57

The“continue”Statement

• Skipstheremainingstatementsinthebodyofawhile,forordo/while structure.– Proceedswiththenextiterationoftheloop.

• whileanddo/while– Loop-continuation testisevaluatedimmediatelyafterthecontinuestatementisexecuted.

• forstructure– expression3 isevaluated,thenexpression2 isevaluated.

Page 58: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 58

Anexamplewith“break”and“continue”

fact = 1; i = 1; /* a program to calculate 10! */while (1) {

fact = fact * i;

i ++;

if (i<10)continue; /* not done yet ! Go to loop and

perform next iteration*/

break;}

Page 59: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

SomeExamples

Page 60: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Example:SUM=12 +22 +32 +N2

START

READ N

SUM=0COUNT =1

SUM=SUM+COUNT∗ COUNT

COUNT =COUNT +1

ISCOUNT >N? OUTPUT SUM

STOP

YESNO

int main () {int N, count, sum;scanf (ʺ%dʺ, &N) ;sum = 0;count = 1;while (count <= N) {

sum = sum + count∗count;count = count + 1;

}printf (ʺSum = %d\nʺ, sum) ;return 0;

}

Autumn Semester2019 60Programming and DataStructure

Page 61: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Example:ComputingFactorial

START

READN

PROD=1COUNT=1

PROD=PROD*COUNT

COUNT=COUNT+1

ISCOUNT>N? OUTPUTPROD

STOP

YESNO

int main () {int N, count, prod;scanf (“%d”, &N) ;prod = 1;for (count=1; count < N; count++)

prod = prod*count;printf (ʺFactorial = %d\nʺ, prod) ;return 0;

}

Autumn Semester2019 61Programming and DataStructure

Page 62: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Example:Computingex seriesuptoNterms

START

READX, N

TERM=1SUM=0COUNT=1

SUM=SUM+TERMTERM=TERM*X/COUNT

COUNT=COUNT+1

ISCOUNT>N? OUTPUTSUM

STOP

YESNO

ex = 1 + x/1! + x2/2! + x3/3! + …

Autumn Semester2019 62Programming and DataStructure

Page 63: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Example:Computingex seriesupto4decimalplaces

START

READX

TERM=1SUM=0COUNT=1

SUM=SUM+TERMTERM=TERM*X/COUNT

COUNT=COUNT+1

ISTERM<0.0001? OUTPUTSUM

STOP

YESNO

Autumn Semester2019 63Programming and DataStructure

Page 64: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 64

Example:Testifanumberisprimeornot

#include <stdio.h>main(){

int n, i=2;scanf (”%d”, &n);while (i < n) {

if (n % i == 0) {printf (”%d is not a prime \n”, n);exit(0);

}i++;

}printf (”%d is a prime \n”, n);

}

Page 65: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 65

Moreefficient??#include <stdio.h>#include <math.h>

main()

{

int n, i=3;scanf (”%d”, &n);

while (i < sqrt(n)) {

if (n % i == 0) {

printf (”%d is not a prime \n”, n);exit(0);

}

i = i + 2;

}printf (”%d is a prime \n”, n);

}

Page 66: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 66

Example:Findthesumofdigitsofanumber

#include <stdio.h>main()

{

int n, sum=0;

scanf (”%d”, &n);while (n != 0) {

sum = sum + (n % 10);

n = n / 10;

}printf (”The sum of digits of the number is %d \n”, sum);

}

Page 67: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 67

Example:Decimaltobinaryconversion

#include <stdio.h>main()

{

int dec;

scanf (”%d”, &dec);do

{

printf (”%2d”, (dec % 2));

dec = dec / 2;} while (dec != 0);

printf (”\n”);

}

Page 68: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 68

Example:ComputeGCDoftwonumbers

#include <stdio.h>main()

{

int A, B, temp;

scanf (”%d %d”, &A, &B);if (A > B)

{temp = A; A = B; B = temp;}

while ((B % A) != 0) {

temp = B % A;B = A;

A = temp;

}

printf (”The GCD is %d”, A);}

12 ) 45 ( 3369 ) 12 ( 1

93 ) 9 ( 3

90

Initial:A=12,B=45Iteration1:temp=9,B=12,A=9Iteration2:temp=3,B=9,A=3

B%A=0è GCDis3

Page 69: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 69

ShortcutsinAssignments

• Additionalassignmentoperators:+=,– =,*=,/=,%=

a+=b isequivalenttoa=a+ba*=(b+10) isequivalenttoa=a*(b+10)

andsoon.

Page 70: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Moreaboutscanfandprintf

Page 71: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 71

Enteringinputdata::scanffunction

• Generalsyntax:scanf(controlstring,arg1,arg2,…,argn);

– “controlstringreferstoastringtypicallycontainingdatatypesoftheargumentstobereadin;

– theargumentsarg1,arg2,…representpointerstodataitemsinmemory.Example: scanf(ʺ%d%f%cʺ,&a,&average,&type);

• Thecontrolstringconsistsofindividualgroupsofcharacters,withonecharactergroupforeachinputdataitem.– ‘%’sign,followedbyaconversioncharacter.

Page 72: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 72

– Commonlyusedconversioncharacters:c singlecharacterd decimalintegerf floating-pointnumbers stringterminatedbynullcharacterX hexadecimalinteger

– Wecanalsospecifythemaximumfield-widthofadataitem,byspecifyinganumberindicatingthefieldwidthbeforetheconversioncharacter.Example:scanf(ʺ%3d%5dʺ,&a,&b);

Page 73: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 73

Writingoutputdata::printffunction

• Generalsyntax:printf(controlstring,arg1,arg2,…,argn);

– “controlstringreferstoastringcontainingformattinginformationanddatatypesoftheargumentstobeoutput;

– theargumentsarg1,arg2,…representtheindividualoutputdataitems.

• Theconversioncharactersaresameasinscanf.• Canspecifythewidthofthedatafields.

– %5d,%7.2f,etc.

Page 74: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Autumn Semester2019 Programming and DataStructure 74

• Examples:printf(ʺTheaverageof%dand%dis%fʺ,a,b,avg);printf(ʺHello\nGood\nMorning\nʺ);printf(ʺ%3d%3d%5dʺ,a,b,a*b+2);printf(ʺ%7.2f%5.1fʺ,x,y);

• Manymoreoptionsareavailable:– Readfromthebook.– Practicetheminthelab.

• StringI/O:– Willbecoveredlaterintheclass.

Page 75: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Anexample

Autumn Semester2019 Programming and DataStructure 75

#include <stdio.h>main(){

int fahr;

for (fahr=0; fahr<=100; fahr+=20)printf (ʺ%3d %6.3f\n”,

fahr, (5.0/9.0)*(fahr-32)); }

0 -17.77820 -6.66740 4.44460 15.55680 26.667

100 37.778

Page 76: Control Statementscse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L2... · 2019-08-14 · The break Statement • Used to exit from a switch or terminate from a loop. – Already

Printwithleadingzeros

Autumn Semester2019 Programming and DataStructure 76

#include <stdio.h>main(){

int fahr;

for (fahr=0; fahr<=100; fahr+=20)printf (“%03d %6.3\n”,

fahr, (5.0/9.0)*(fahr-32)); }

000 -17.778020 -6.667040 4.444060 15.556080 26.667100 37.778