Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
ControlStatements
IndranilSenGupta
Dept.ofComputerScience&Engg.IndianInstituteofTechnology
Kharagpur
Autumn Semester2019 Programming and DataStructure 2
Whatdotheydo?
• Allowdifferentsetsofinstructionstobeexecuteddependingontheoutcomeofalogicaltest.– WhetherTRUEorFALSE.– Thisiscalledbranching.
• Someapplicationsmayalsorequirethatasetofinstructionsbeexecutedrepeatedly,possiblyagainbasedonsomecondition.– Thisiscalledlooping.
Autumn Semester2019 Programming and DataStructure 3
Howdowespecifytheconditions?
• Usingrelationaloperators.– Fourrelationoperators: <,<=,>,>=– Twoequalityoperators: ==,!=
• Usinglogicaloperators/connectives.– Twologicalconnectives: &&,||– Unarynegationoperator: !
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))
Autumn Semester2019 Programming and DataStructure 5
Theconditionsevaluateto…
• Zero– IndicatesFALSE.
• Non-zero– IndicatesTRUE.– TypicallytheconditionTRUEisrepresentedbythevalue‘1’.
Autumn Semester2019 Programming and DataStructure 6
Branching:TheifStatement
• Diamondsymbol(decisionsymbol)- indicatesdecisionistobemade.– ContainsanexpressionthatcanbeTRUEorFALSE.– Testthecondition,andfollowappropriatepath.
• Single-entry/single-exitstructure.
• Generalsyntax:if(condition) {……..}
– Ifthereisasinglestatementintheblock,thebracescanbeomitted.
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
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);}
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
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) { ……………… }
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.
Autumn Semester2019 Programming and DataStructure 12
if ( grade >= 60 ) printf ("Passed\n");
elseprintf ("Failed\n");
grade >= 60 print “Passed”truefalse
print “Failed”
Autumn Semester2019 Programming and DataStructure 13
Nestingofif-elseStructures
• Itispossibletonestif-elsestatements,onewithinanother.
• Allifstatementsmaynotbehavingthe“else”part.– Confusion??
• Ruletoberemembered:– An“else”clauseisassociatedwiththeclosestprecedingunmatched“if”.
– Someexamplesshownnext.
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
?
Autumn Semester2019 Programming and DataStructure 15
ife1s1 ife1s1elseife2s2 elseife2s2
ife1s1 ife1s1elseife2s2 elseife2s2elses3 elses3
ife1ife2s1 ife1ife2s1elses2 elses2elses3 elses3
ife1ife2s1 ife1ife2s1elses2 elses2
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);}
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);}
Autumn Semester2019 Programming and DataStructure 18
TheConditionalOperator?:
• Thismakesuseofanexpressionthatiseithertrueorfalse.Anappropriatevalueisselected,dependingontheoutcomeofthelogicalexpression.
• Example:interest = (balance>5000) ? balance*0.2 : balance*0.1;
Returnsavalue
Autumn Semester2019 Programming and DataStructure 19
• Examples:
x = ((a>10) && (b<5)) ? a+b : 0
(marks>=60) ? printf(ʺPassed \nʺ) : printf(ʺFailed \nʺ);
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
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;
}
Autumn Semester2019 Programming and DataStructure 22
ThebreakStatement
• Usedtoexitfromaswitchorterminatefromaloop.– Alreadyillustratedinthepreviousexample.
• Withrespectto“switch”,the“break”statementcausesatransferofcontroloutoftheentire“switch”statement,tothefirststatementfollowingthe“switch”statementblock.
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ʺ);
}
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ʺ);}
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
Autumn Semester2019 Programming and DataStructure 26
• The“switch”statementalsoconstitutesasingle-entry/single-exitstructure.
switch statement
ALookBackatArithmeticOperators:theIncrementandDecrement
Autumn Semester2019 Programming and DataStructure 28
Increment(++)andDecrement(--)
• Bothoftheseareunaryoperators;theyoperateonasingleoperand.
• Theincrementoperatorcausesitsoperandtobeincreasedby1.– Example: a++, ++count
• Thedecrementoperatorcausesitsoperandtobedecreasedby1.– Example: i--, --distance
Autumn Semester2019 Programming and DataStructure 29
• Operatorwrittenbeforetheoperand(++i,--i)– Calledpre-incrementoperator.– Operandwillbealteredinvaluebefore itisutilizedforitsintendedpurposeintheprogram.
• Operatorwrittenaftertheoperand(i++,i--)– Calledpost-incrementoperator.– Operandwillbealteredinvalueafter itisutilizedforitsintendedpurposeintheprogram.
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.
ControlStructuresthatAllowRepetition
TypesofRepeatedExecution
• Loop:Groupofinstructionsthatareexecutedrepeatedlywhilesomeconditionremainstrue.
Howloopsarecontrolled?
SentinelControlled
CounterControlled Condition
Controlled
Autumn Semester2019 32Programming and DataStructure
Autumn Semester2019 Programming and DataStructure 33
• Counter-controlledrepetition– Definiterepetition– knowhowmanytimesloopwillexecute.
– Controlvariableusedtocountrepetitions.
• Condition-controlledrepetition– Loopexecutesaslongassomespecifiedconditionistrue.
• Sentinel-controlledrepetition– Indefiniterepetition.
– Usedwhennumberofrepetitionsnotknown.
– Sentinelvalueindicates“endofdata”.
Autumn Semester2019 Programming and DataStructure 34
Counter-controlledRepetition
• Counter-controlledrepetitionrequires:– name ofacontrolvariable(orloopcounter).– initialvalue ofthecontrolvariable.– condition thattestsforthefinalvalueofthecontrolvariable(i.e.,whetherloopingshouldcontinue).
– increment(ordecrement) bywhichthecontrolvariableismodifiedeachtimethroughtheloop.
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
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);
Autumn Semester2019 Programming and DataStructure 37
whileStatement
• The“while”statementisusedtocarryoutloopingoperations,inwhichagroupofstatementsisexecutedrepeatedly,aslongassomeconditionremainssatisfied.
while (condition)statement_to_repeat;
while (condition) {
statement_1;...
statement_N;}
Autumn Semester2019 Programming and DataStructure 38
C
statement(s)
true
falseSingle-entry/single-exitstructure
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);
}
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
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
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 );
Autumn Semester2019 Programming and DataStructure 43
C
statement(s)
true
false
Single-entry/single-exitstructure
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 );
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;
}
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);
Autumn Semester2019 Programming and DataStructure 47
Single-entry/single-exitstructure
expression2
statement(s)
true
false
expression1
expression3
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
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
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
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
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.
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!
Autumn Semester2019 Programming and DataStructure 54
Specifying“InfiniteLoop”
while (1) {statements
}
for (; ;){
statements
}
do {statements
} while (1);
Autumn Semester2019 Programming and DataStructure 55
The“break”StatementRevisited
• Breakoutoftheloop{}– canusewith
• while• dowhile• for• switch
– doesnotworkwith• if• else
• Causesimmediateexitfromawhile,do/while,for orswitchstructure.
• Programexecutioncontinueswiththefirststatementafterthestructure.
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++;
}}
Autumn Semester2019 Programming and DataStructure 57
The“continue”Statement
• Skipstheremainingstatementsinthebodyofawhile,forordo/while structure.– Proceedswiththenextiterationoftheloop.
• whileanddo/while– Loop-continuation testisevaluatedimmediatelyafterthecontinuestatementisexecuted.
• forstructure– expression3 isevaluated,thenexpression2 isevaluated.
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;}
SomeExamples
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
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
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
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
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);
}
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);
}
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);
}
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”);
}
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
Autumn Semester2019 Programming and DataStructure 69
ShortcutsinAssignments
• Additionalassignmentoperators:+=,– =,*=,/=,%=
a+=b isequivalenttoa=a+ba*=(b+10) isequivalenttoa=a*(b+10)
andsoon.
Moreaboutscanfandprintf
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.
Autumn Semester2019 Programming and DataStructure 72
– Commonlyusedconversioncharacters:c singlecharacterd decimalintegerf floating-pointnumbers stringterminatedbynullcharacterX hexadecimalinteger
– Wecanalsospecifythemaximumfield-widthofadataitem,byspecifyinganumberindicatingthefieldwidthbeforetheconversioncharacter.Example:scanf(ʺ%3d%5dʺ,&a,&b);
Autumn Semester2019 Programming and DataStructure 73
Writingoutputdata::printffunction
• Generalsyntax:printf(controlstring,arg1,arg2,…,argn);
– “controlstringreferstoastringcontainingformattinginformationanddatatypesoftheargumentstobeoutput;
– theargumentsarg1,arg2,…representtheindividualoutputdataitems.
• Theconversioncharactersaresameasinscanf.• Canspecifythewidthofthedatafields.
– %5d,%7.2f,etc.
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.
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
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