c fundamentals & formatted input/outputopen.gnu.ac.kr/lecslides/2017-2-introprog/knk_c_01... ·...
TRANSCRIPT
Program:PrintingaPun• Thefilenamedoesn’tmatter,butthe.c extensionisoftenrequired.• forexample:pun.c
• tocompile
• torun
#include <stdio.h> // directive
int main(void) // function{ /* statements begin */printf("To C, or not to C: that is the question.\n");return 0;
} /* statements end */
% cc -o pun pun.c % gcc -o pun pun.cor
3
% ./pun
TheGeneralFormofaSimpleProgram
4
ThreekeylanguagefeaturesofCprograms
statements
directives
int main(void){
}
1
2
3begin
end
Example:#include <stdio.h>
TheGeneralForm:Directives
• BeforeaCprogramiscompiled,itisfirsteditedbyapreprocessor.• Commandsintendedforthepreprocessorarecalleddirectives.
• <stdio.h> isaheader containinginformationaboutC’sstandardI/Olibrary.• Directivesalwaysbeginwitha# character.• Bydefault,directivesareonelinelong;• there’snosemicolonorotherspecialmarkerattheend.
5
ThreekeylanguagefeaturesofCprograms
directives1 Example:#include <stdio.h>
TheGeneralForm:Directives
• Libraryfunctionsare providedaspartoftheCimplementation.• Themain functionismandatory.• main isspecial:itgetscalledautomaticallywhentheprogramisexecuted.• main returnsastatuscode;thevalue0indicatesnormalprogramtermination.
• Ifthere’snoreturn statementattheendofthemain function,manycompilerswillproduceawarningmessage.
6
ThreekeylanguagefeaturesofCprograms
int main(void){
# of statementsreturn x + 1;
}
2 aseriesofstatementsthathavebeengroupedtogetherandgivenaname.
Afunctionthatcomputesavalueusesareturn statementtospecifywhatvalueit“returns”:
TheGeneralForm:Statements
• pun.c usesonlytwokindsofstatements.• Oneisthereturn statement;theotheristhefunctioncall.
• Askingafunctiontoperformitsassignedtaskisknownascalling thefunction.• pun.c callsprintf todisplayastring:printf("To C, or not to C: that is the question.\n");
7
statements3
ThreekeylanguagefeaturesofCprograms
acommandtobeexecutedwhentheprogramruns.Crequiresthateachstatementendwithasemicolon.
PrintingStrings:printf• Whentheprintf functiondisplaysastringliteral—charactersenclosedindoublequotationmarks—itdoesn’tshowthequotationmarks.
• printf doesn’tautomaticallyadvancetothenextoutputlinewhenitfinishesprinting.
• Tomakeprintf advanceoneline,include\n (thenew-linecharacter)inthestringtobeprinted.
printf("To C, or not to C: that is the question.\n");
printf("To C, or not to C: ");printf("that is the question.\n");
printf("Brevity is the soul of wit.\n --Shakespeare\n");
Sameeffect
8
moreonprintf onfollowingsection
Comments• Acomment beginswith/* andendwith*/./* This is a comment */
• Commentsmayappearalmostanywhereinaprogram,eitheronseparatelinesoronthesamelinesasotherprogramtext.
• Commentsmayextendovermorethanoneline./* Name: pun.c
Purpose: Prints a bad pun.Author: K. N. King */
• InC99,commentscanalsobewritteninthefollowingway:// A comment, which ends automatically at the end of a line
• Advantagesof// comments:• Safer:there’snochancethatanunterminatedcommentwillaccidentallyconsumepartofaprogram.
• Multilinecommentsstandoutbetter.
9
VariablesandAssignment• Mostprogramsneedtoawaytostoredatatemporarilyduringprogramexecution.
• Thesestoragelocationsarecalledvariables.
• Tousevariablesandassignments,youneedtoknow1. type2. declaration3. initialization
10
int height = 183;1 32
VariablesandAssignment:Types• Everyvariablemusthaveatype.• Chasawidevarietyoftypes,includingint andfloat.
• Avariableoftypeint (shortforinteger)canstoreawholenumbersuchas0,1,392,or–2553.
• Avariableoftypefloat (shortforfloating-point)canstoremuchlargernumbersthananint variable.• Also,afloat variablecanstorenumberswithdigitsafterthedecimalpoint,like379.125.
• Drawbacksoffloat variables:• Slowerarithmetic
• Approximatenatureoffloat values
11
VariablesandAssignment:Declarations• Variablesmustbedeclared beforetheyareused.
• Botharelegal
• Whenmain containsdeclarations,thesemustprecedestatements:
int height;float profit;
int height, length, width, volume;float profit, loss;
int main(void){
declarationsstatements
}
12
VariablesandAssignment:Assignment(1/2)• Avariablecanbegivenavaluebymeansofassignment:height = 8; // Thenumber8 issaidtobeaconstant.
• Beforeavariablecanbeassignedavalue—orusedinanyotherway—itmustfirstbedeclared.
• Aconstantassignedtoafloat variableusuallycontainsadecimalpoint:profit = 2150.48;
• It’sbesttoappendtheletterf toafloating-pointconstantifitisassignedtoafloat variable:profit = 2150.48f;
Failingtoincludethefmaycauseawarningfromthecompiler.
13
VariablesandAssignment:Assignment(2/2)• Anint variableisnormallyassignedavalueoftypeint,andafloatvariableisnormallyassignedavalueoftypefloat.• Mixingtypes(suchasassigninganint valuetoafloat variable)ispossiblebutnotalwayssafe.
• Onceavariablehasbeenassignedavalue,itcanbeusedtohelpcomputethevalueofanothervariable:
• Therightsideofanassignmentcanbeaformula(orexpression, inCterminology)involvingconstants,variables,andoperators.
height = 8;length = 12;width = 10;volume = height * length * width; // volume is now 960
14
VariablesandAssignment:Initialization• Somevariablesareautomaticallysettozerowhenaprogrambeginstoexecute,butmostarenot.• Avariablethatdoesn’thaveadefaultvalueandhasn’tyetbeenassignedavaluebytheprogramissaidtobeuninitialized.
• Accessingthevalueofanuninitializedvariablecausesanunpredictableresult.• Withsomecompilers,worsebehavior—evenaprogramcrash—mayoccur.
• Theinitialvalueofavariablemaybeincludedinitsdeclaration:int height = 8; // The value 8 is said to be an initializer.
int height = 8, length = 12, width = 10;
int height, length, width = 10; // initializes only width
15
PrintingtheValueofaVariable• printf canbeusedtodisplaythecurrentvalueofavariable.• Towritethefollowingmessage,we’dusethefollowingcallofprintf:
• %d isaplaceholderindicatingwherethevalueofheight istobefilledin.
• There’snolimittothenumberofvariablesthatcanbeprintedbyasinglecallofprintf:printf("Height: %d Length: %d\n", height, length);
16
Detailsofprintf onfollowingsection
Height: h
printf("Height: %d\n", height);
ReadingInput• scanf istheClibrary’scounterparttoprintf.• scanf requiresaformatstringtospecifytheappearanceoftheinputdata.
• Exampleofusingscanf toreadanint value:scanf("%d", &i); /* reads an integer; stores into i */
• The& symbolisusually(butnotalways)requiredwhenusingscanf.
17
Detailsofscanf onfollowingsection
DefiningNamesforConstants• Usingafeatureknownasmacrodefinition,wecannamethisconstant:#define INCHES_PER_POUND 166
• Whenaprogramiscompiled,thepreprocessorreplaceseachmacrobythevaluethatitrepresents.
• Duringpreprocessing,thestatement
willbecome
• Thevalueofamacrocanbeanexpression:#define RECIPROCAL_OF_PI (1.0f / 3.14159f)
• Ifitcontainsoperators,theexpressionshouldbeenclosedinparentheses.
18
weight = (volume + INCHES_PER_POUND - 1) / INCHES_PER_POUND;
weight = (volume + 166 - 1) / 166;
Itiscommonconventiontouseonlyupper-caselettersinmacronames
Identifiers• Identifiers: Namesforvariables,functions,macros,andotherentities• Letters,digits,andunderscores,butmustbeginwithaletterorunderscore:
• Cplacesnolimitonthemaximumlengthofanidentifier.
• Examplesofillegalidentifiers:10times get-next-char
• Ciscase-sensitive
19
allaredifferentjob joB jOb jOB Job JoB JOb JOB
times10 _done symbol_table current_page
symbolTable currentPage
Keywords• Thefollowingkeywords can’tbeusedasidentifiers:
• Keywords(withtheexceptionof_Bool,_Complex,and_Imaginary)mustbewrittenusingonlylower-caseletters.
• Namesoflibraryfunctions(e.g.,printf)arealsolower-case.
20
autobreakcasecharconstcontinuedefault
dodoubleelseenumexternfloatfor
gotoifintlongregister
returnshortsignedsizeofstaticstructswitch
typedefunionunsignedvoidvolatilewhile
inline*restrict*_Bool*_Complex*_Imaginary**C99only
LayoutofaCProgram(1/2)• ACprogramis
aseriesoftokens.• Tokensinclude:• Identifiers• Keywords• Operators• Punctuation• Constants• Stringliterals
• Thestatementprintf("Height: %d\n", height);
consistsofseventokens:
printf Identifier( Punctuation"Height: %d\n" Stringliteral, Punctuationheight Identifier) Punctuation; Punctuation
21
LayoutofaCProgram (2/2)• Statementscanbedividedoveranynumberoflines.
• Spacebetweentokens(suchasbeforeandaftereachoperator,andaftereachcomma)makesiteasierfortheeyetoseparatethem.
• Indentation canmakenestingeasiertospot.
• Blanklines candivideaprogramintologicalunits
22
Theprintf Function(1/3)• Theprintf functionmustbesuppliedwithaformatstring,followedbyanyvaluesthataretobeinsertedintothestringduringprinting:
• Theformatstringmaycontainbothordinarycharactersandconversionspecifications,whichbeginwiththe% character.
• Aconversionspecificationisaplaceholderrepresentingavaluetobefilledinduringprinting.• %d isusedforint values• %f isusedforfloat values
24
printf(format_string, expr1, expr2, …);
Theprintf Function (2/3)• Ordinarycharactersinaformatstringareprintedastheyappearinthestring;conversionspecificationsarereplaced.
• Example:
25
int i, j;float x, y;
i = 10;j = 20;x = 43.2892f;y = 5527.0f;
printf("i = %d, j = %d, x = %f, y = %f\n", i, j, x, y);
i = 10, j = 20, x = 43.289200, y = 5527.000000Result:
Theprintf Function (3/3)• Compilersaren’trequiredtocheckthatthenumberofconversionspecificationsinaformatstringmatchesthenumberofoutputitems.
• Compilersaren’trequiredtocheckthataconversionspecificationisappropriate.• Anincorrectspecificationwillproducemeaninglessoutput:
26
printf("%d %d\n", i); /*** WRONG ***/printf("%d\n", i, j); /*** WRONG ***/
int i;
float x;
printf("%f %d\n", i, x); /*** WRONG ***/
ConversionSpecifications(1/2)
27
%m.pXminimumfieldwidth precision
conversionspecifier
optional optional
%5.3f%8d%-8d
12345.678912345.678
1234512345
%d - Integer%e - Exponentialformat%f - Fixeddecimal%g - Eitherexponentialformator
fixeddecimalformat
ConversionSpecifications(1/2)
28
Formatspecifier Description Supporteddatatypes
%c Character charunsigned char
%d SignedInteger
shortunsigned shortintlong
%e or %E Scientificnotationoffloatvalues
floatdouble
%f Floatingpoint float
%g or %G Similaras%eor%E
floatdouble
%hi SignedInteger(Short)
short
%hu UnsignedInteger(Short)
unsigned short
%i SignedInteger
shortunsigned shortintlong
%l or %ld or %li SignedInteger long
%lf Floatingpoint double%Lf Floatingpoint long double
%lu Unsignedinteger unsigned intunsigned long
Formatspecifier Description Supporteddatatypes
%lli, %lld SignedInteger long long
%llu UnsignedInteger unsigned long long
%o OctalrepresentationofInteger.
shortunsigned shortintunsigned intlong
%p Addressofpointertovoidvoid*
void *
%s String char *
%u UnsignedInteger unsigned intunsigned long
%x or %XHexadecimalrepresentationofUnsignedInteger
shortunsigned shortintunsigned intlong
%n Printsnothing
%% Prints%character
EscapeSequences(1/2)• The\n codethatusedinformatstringsiscalledanescapesequence.• Escapesequencesenablestringstocontainnonprinting(control)charactersandcharactersthathaveaspecialmeaning(suchas").
• Apartiallistofescapesequences:
Alert(bell) \a
Backspace \b
Newline \n
Horizontaltab \t
• Astringmaycontainanynumberofescapesequences:
29
printf("Item\tUnit\tPurchase\n\tPrice\tDate\n");
Item Unit Purchase
Price Date
EscapeSequences(2/2)• Astringmaycontainanynumberofescapesequences:
• Anothercommonescapesequenceis\",whichrepresentsthe" character:
• Toprintasingle\ character,puttwo\ charactersinthestring:
30
printf("Item\tUnit\tPurchase\n\tPrice\tDate\n");
Item Unit Purchase
Price Date
printf("\"Hello!\""); /* prints "Hello!" */
printf("\\"); /* prints one \ character */
Thescanf Function• scanf readsinputaccordingtoaparticularformat.
• Ascanf formatstringmaycontainbothordinarycharactersandconversionspecifications.
• Theconversionsallowedwithscanf areessentiallythesameasthoseusedwithprintf.
• Inmanycases,ascanf formatstringwillcontainonlyconversionspecifications:
• Sampleinput:scanf willassign1,–20,0.3,and–4000.0toi,j,x,andy,respectively.
31
int i, j;float x, y;scanf("%d%d%f%f", &i, &j, &x, &y);
1 -20 .3 -4.0e3
scanf(format_string, &var1, &var2, …);
HowscanfWorks(1/4)• scanf triestomatchgroupsofinputcharacterswithconversionspecificationsintheformatstring.
• Foreachconversionspecification,scanf triestolocateanitemoftheappropriatetypeintheinputdata,skippingblankspaceifnecessary.
• scanf thenreadstheitem,stoppingwhenitreachesacharacterthatcan’tbelongtotheitem.• Iftheitemwasreadsuccessfully,scanf continuesprocessingtherestoftheformatstring.
• Ifnot,scanf returnsimmediately.
32
HowscanfWorks (2/4)• Asitsearchesforanumber,scanf ignoreswhite-spacecharacters• space,horizontalandverticaltab,form-feed,andnew-line
• Acallofscanf thatreadsfournumbers:scanf("%d%d%f%f", &i, &j, &x, &y);
• Thenumberscanbeononelineorspreadoverseverallines:
• scanf “peeks”atthefinalnew-linewithoutreadingit.
33
1-20 .3
-4.0e3••1¤-20•••.3¤•••-4.0e3¤ssrsrrrsssrrssssrrrrrr
(s =skipped;r =read)
HowscanfWorks(3/4)• Whenaskedtoreadaninteger,scanf firstsearchesforadigit,aplussign,oraminussign;itthenreadsdigitsuntilitreachesanondigit.
• Whenaskedtoreadafloating-pointnumber,scanf looksfor• aplusorminussign(optional),followedby• digits(possiblycontainingadecimalpoint),followedby• anexponent(optional).Anexponentconsistsofthelettere (orE),anoptionalsign,andoneormoredigits.
• %e,%f,and%g areinterchangeablewhenusedwithscanf.
• Whenscanf encountersacharacterthatcan’tbepartofthecurrentitem,thecharacteris“putback”tobereadagainduringthescanningofthenextinputitemorduringthenextcallofscanf.
34
HowscanfWorks (4/4)• Sampleinput:
1-20.3-4.0e3¤
• Thecallofscanf isthesameasbefore:
scanf("%d%d%f%f", &i, &j, &x, &y);
• Here’showscanf wouldprocessthenewinput:• %d :Stores1intoi andputsthe- characterback.• %d :Stores–20intoj andputsthe. characterback.• %f :Stores0.3intox andputsthe- characterback.• %f :Stores–4.0× 103intoy andputsthenew-linecharacterback.
35
OrdinaryCharactersinFormatStrings• Whenitencountersoneormorewhite-spacecharactersinaformatstring,scanf readswhite-spacecharactersfromtheinputuntilitreachesanon-white-spacecharacter(whichis“putback”).
• Whenitencountersanon-white-spacecharacterinaformatstring,scanfcomparesitwiththenextinputcharacter.• Iftheymatch,scanf discardstheinputcharacterandcontinuesprocessingtheformatstring.
• Iftheydon’tmatch,scanf putstheoffendingcharacterbackintotheinput,thenaborts.
• Examples:• Iftheformatstringis"%d/%d" andtheinputis•5/•96,scanf succeeds.• Iftheinputis•5•/•96 ,scanf fails,becausethe/ intheformatstringdoesn’tmatchthespaceintheinput.
• Toallowspacesafterthefirstnumber,usetheformatstring"%d /%d"instead.
36
Confusingprintf withscanf (1/2)• Althoughcallsofscanf andprintfmayappearsimilar,therearesignificantdifferencesbetweenthetwo.
• Onecommonmistakeistoput& infrontofvariablesinacallofprintf:
• Incorrectlyassumingthatscanf formatstringsshouldresembleprintfformatstringsisanothercommonerror.
• Considerthefollowingcallofscanf:
• scanf willfirstlookforanintegerintheinput,whichitstoresinthevariablei.
• scanf willthentrytomatchacommawiththenextinputcharacter.• Ifthenextinputcharacterisaspace,notacomma,scanf willterminatewithoutreadingavalueforj.
37
printf("%d %d\n", &i, &j); /*** WRONG ***/
scanf("%d, %d", &i, &j);
Confusingprintf withscanf (2/2)• Puttinganew-linecharacterattheendofascanf formatstringisusuallyabadidea.
• Toscanf,anew-linecharacterinaformatstringisequivalenttoaspace;bothcausescanf toadvancetothenextnon-white-spacecharacter.
• Iftheformatstringis"%d\n",scanf willskipwhitespace,readaninteger,thenskiptothenextnon-white-spacecharacter.
• Aformatstringlikethiscancauseaninteractiveprogramto“hang.”
38