C语言基础(英文版)361_第1页
C语言基础(英文版)361_第2页
C语言基础(英文版)361_第3页
C语言基础(英文版)361_第4页
C语言基础(英文版)361_第5页
已阅读5页,还剩356页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Lecture1

IntroductionCProgrammingLanguageOutlineGeneralCourseInformationHardwareandSoftwareProgrammingLanguagesHistoryandFeaturesofCFirstLookAbouttheCourseTotalcredithours:64Lecturehours:40Labworkhours:24IndependentStudyhour:80GradingAttendance+Coursework:30%

MiddleTermExam:30%

FinalExam:40%SuggestionsBelieveyourself:Yes,YouCan!Findyourownwaytolearn,tostudy,toenjoy…Makenotestohelpyou.Practiceasmoreasyoucan.ReadingListKernighan,B.W.,D.M.Ritchie,TheCProgrammingLanguage,2nded.,PrenticeHallPTRRoberts,E.S.,TheArtandScienceofC:ALibrary-BasedIntroductiontoComputerScience,AddisonWesleyHorton,I.,BeginningC:FromNovicetoProfessional,4thed.,SpringerKing,K.N.,CProgramming:AModernApproach,2nded.,W.W.Norton&Company王曙燕,C语言程序设计教程,人民邮电出版社ThinkAbout...Whatcomputerscandoforus?Howcomputerssolveproblems/work?ComputerHardwareAcomputersystemisconstructedbytwopartshardwaresystem(visible)CPU,Memory,storagessoftwaresystem(invisible)ComputerHardwareComputerHardwareCPU(CentralProcessingUnit),isthemostimporthardwaredeviceofacomputer.CPUisabletoprocessinstructionssuchasarithmeticaloperations,movingdatatoandfromotherdevicesetc.EachtypeofCPUhasitsownspecificinstructionset.ComputerHardwareMemorycanstoredatatemporary.Thewholememoryisdividedintosmallunitslogically,andeachunithasaspecificaddress.Normally,thecapacityofoneunitisonebyte,whichiseightbits.CPUneedtoread/writedataonmemorybyusingaddresses.ComputerHardwareHarddisks,flashdisks,opticaldisksarecommonlyusedpersistentstorages.Datatobestoredonpersistentstoragesareorganizedastheformatofafile.Filenamesareusedtoidentifydifferentfilesandtooperatethedatabelongstoagivenfile.SoftwareandProgramSoftwareisonthehardware,bythehardware,andforthehardware.softwareisdividedintotwocategories:systemsoftwareapplicationsoftwareComputerSoftwareSoftwareandProgramAserialofinstructionscanberegardedasapieceofprogram.ThepurposeofprogrammingisjusttomakeouttheinstructionserialforprocessingbyCPU.Itishardtocomposeinstructionsbyhandsdirectly.Programminglanguagescanhelpustodoit.ProgrammingLanguagesProgramminglanguageshelpprogrammerstocommunicatewithcomputers.EarlierprogramminglanguagesaresimpleModernprogramminglanguagearewell-designedandwithsimilarsyntaxandsemantictoournaturallanguage.ProgrammingLanguagesDevelopmentofprogramminglanguages1G:Machinelanguage2G:Assemblylanguage3G:High-Levellanguage4G?5G?ProgrammingLanguagesDifferentprogramminglanguageshavedifferentwaystorepresentdataandprocessdata.SomesyntaxoftheCprogramminglanguageissimilartootherprogramminglanguages,butsomeothersmaytotallydifferent.ProgrammingLanguagesHistoryandDevelopmentofCHistoryBornin1972attheBellLaboratories.Itwasnamed"C"becauseitsfeatureswerederivedfromanearlierlanguagecalled"B".DevelopmentOriginal:ClassicalCLater:StandardCorC89newly:C99FeaturesofCStructuredprogrammingmethodologyHighefficiencywithagilecodesProductiveandgoodqualityPortabilityondifferentplatformIrreplaceableonsystem-levelandembeddeddevicesprogrammingFewkeywords,simplesyntax,easytolearnFuturesofCCprogramminglanguagekeepsitslivingnesssinceitscreationtillnow.Basedonthefastdevelopmentofembeddedsystemsandmobilesystems,itcanbeforecastedthattheCprogramminglanguagewillstillkeepitsincreasedtrendinthefuture.Doyouknow...WhatcanCdo?WhatCcan’tdo?WhatdoesCprogramlooklike?FirstLook#include<stdio.h>main(){printf("hello,world.\n");}ProgrammingStepseditsourcecodefile(.c)byaneditorcompiletogetobjectfile(.obj)byacompilerlinktogetexecutablefile(.exe)byalinkerruntheexefiletoseeifitiscorrectornotdebugsourcecodetofixbugscompile/link/runagain…sourcefile:Hello.cObjectfile:Hello.objlibrary&systemcodeexecutablefile:Hello.execompilelinkProgrammingStepsTipsErrorswilloccurwhenyoubegintowriteprograms.Noonecanavoidthis.Thebestwaytolearnalanguage,notonlyahumanlanguage,butalsoacomputerlanguage,istouseitasmoreasyoucan.Theerrorswillbecorrectedasyoukeeplearningandimproving.Question?Suggestion?HomeworkGetadictionary.ReadAppendixD“IntroductiontoDevelopmentEnvironments”ofthetextbookasmoreasyoucan.Lecture2

LanguageBasicsCProgrammingLanguageOutlineKeyConceptsTypesVariablesConstantsprintfandscanfFirstExample#include<stdio.h>main(){printf("hello,world.\n");}KeyConceptsIdentifierFunctionFunctionDefinitionFunctionCallFileinclusioncommandStatementSecondExample#include<stdio.h>main(){intx,y,z;intsum;printf("inputthreeintegers:");

scanf("%d,%d,%d",&x,&y,&z);sum=x+y+z;printf("sum=%d\n",sum);}KeyConceptsVariableTypeExpressionThirdExample0203.cKeyConceptsACprogrammaycontainmorethanonefunctionThefunctionmainistheentrypointCommentsTypesTypesintfloat/doublecharModifiersshort/longsigned/unsignedVariablesVariabletypeaddressnamevalueVariablesmustbedefinedbeforeusing.VariablesDefinitiontypevariable_name_list;

inta,b,c;floatx;doubley;charz;VariablesVariableNamingRulessequenceofLETTERandNUMBER,and_startingwithLETTERor_cannotbethesameasKEYWORDSorSYSTEMFUNCTIONNAMESSomeKeyWordsint,float,double,char,short,longif,else,do,while,for,switch,case,breakVariablesInitializationinti=0;inta,b=2,c=3;floatx=1.2E-5;doublee=2.718281828;charc=‘H’;VariablesInitializationIfyoudonotinitializeavariable,doseithasavalue?ConstantsConstantsarefixedvaluesthatdirectlyhardcodedinthesourcecodes.Constantshavetypesintvalue:120longvalue(endwithL/l):120Ldoublevalue:3.14,1.23E-2,3.45e3floatvalue(endwithF/f):1.234Fcharvalue:'A''b'string:“helloworld”ConstantsOctalvalue(startwith0):015Hexadecimalvalue(startwith0X,0x): 0X15,0xaaEscapesequences:'\n''\t' Anotherformat:'\ooo'or'\xhh'e.g.'\101'isanotherwaytorepresent'A',and'\x62'isthesameas'b'printfandscanfprintfandscanfaretwofunctionsthatprovidedbythestandardlibrary.printfistoprintoutvalues,andscanfistoscanfvaluesYouareabletocallthembyincludingaheaderfilestdio.hprintfusage

printf("output_sequence",value_list);

examplesprintf("hello,world.\n");printf("sum=%d",sum);printf("%d+%d=%d",a,b,a+b);printfConversionspecificationsareusedtorepresentdifferenttypesofdata.%d integer %ld long%f float %lf double%e float/double(scientificnotation)%c character %s string Example4printfTherearesomemodifierscanbeputinsideoftheconversionspecificationstoaddmoreformatfordatatobeoutputted.Example5scanfusage

scanf("input_sequence",address_list)

;

examplesscanf("%d",&a);scanf("%d,%d,%d",&x,&y,&z);scanf("%d%d%d",&x,&y,&z);Question?Suggestion?HomeworkPage26:Exercises1,2,3,4Lecture3

Operatorsand

ExpressionsCProgrammingLanguageOutlineArithmeticOperatorsAssignmentOperatorsIncrement/DecrementOperatorssizeofOperatorPrecedenceandOrderofEvaluationTypeConversionsArithmeticOperators+ additionoperator 3+2- subtractionoperator 3-2* multiplicationoperator 3*2/ divisionoperator 3/2% modulusoperator 3%2ArithmeticOperatorsModulusoperatoristocalculatetheremainderofadivisionoperationbytwointegers.e.g.5%2is14%2is0theremainderofapositivedividendispositive,nomatterthedivisorispositiveornegative.Andtheremainderofanegativedividendisnegative,nomatterthedivisorispositiveornegative.ArithmeticOperatorsSomerules:Operandsformodulusoperatorcanonlybeinttype.Operandsforadditionoperator,subtractionoperator,multiplicationoperatoranddivisionoperatorcanbeanytypesofnumbers.Theoutcomeoftheevaluationwillbethesametypeasitsoperandsifthetwooperandshavethesametype.ArithmeticOperatorsIfthetwooperandsareofdifferenttypes,apromotionwillbeperformedbeforedoingevaluating.Theoutcomeofadivisionoperationbytwointegernumberswillbealsoanintegernumber.Iftheoriginalquotientofthedivisionoperationisnotaninteger,thefractionpartwillbeomitted(NOTrounded)toformanintegeroutcome.AssignmentOperators=isassignmentoperator

sum=x+y+z;ave=average(a,b,c);shorthandassignmentoperators+= a+=1;isthesameasa=a+1;-=*=/=%=Increment/DecrementOperatorsIncrementoperator++istoincrease1toitsoperand,whiledecrementoperator--istodecrease1foritsoperand.Incrementanddecrementoperatorscanbeputbeforetheoperand(prefixformat),oraftertheoperand(postfixformat).++i,i++,--i,andi--arefourexamples.Increment/DecrementOperatorsTherearenodifferencesforprefixformatandpostfixformatifyouuseincrementanddecrementoperatorsindividuallyIfincrementanddecrementoperatorsareusedaccompanywithotheroperators,prefixformatandpostfixformatwillcausedifferenteffects(alsocalledsideeffects)Example1sizeofOperatorsizeofisanoperatortogetthesizeofmemorythatanobjectisoccupied.Syntax:

sizeof(type)or sizeofobjectExample2Precedence&OrderofEvaluationTherearerulesforevaluatingexpressionscomposedbymorethanoneoperation.Forexample1+2*3/4-5Precedencehigh/low()hasthehighestprecedenceOrderofEvaluationlefttorightrighttoleftTypeConversionsTypeconversionhappenswhileevaluatinganexpressionwhichoperandsarenotinthesametype.Twokindsoftypeconversionsautomatictypeconversion(promotion)explicittypeconversionTypeConversionsPromotion:thelowertypeispromotedtothehighertypeautomaticallybeforetheoperationproceeds.Levelsoftypes:

double>float>int>charPromotionissafeasitwillnotlosedatainformation.TypeConversionsExplicittypeconversion:tocastthetypebyforce,maylosesomeinformation. Syntax:use(type)beforeobjects.Example3Question?Suggestion?HomeworkPage37:Exercises1,3,4Lecture4

ProgramControlFlowsCProgrammingLanguageOutlineThreeControlFlowsFlowChartNSDiagramContinuationControlFlowAlgorithmsThinkabout...Howtowriteaprogramtocheckauser’spassword?ThreeControlFlowsTherearedifferentwaystocontroltheflowofaprogramContinuationcontrolflowSelectioncontrolflowLoopcontrolflowFlowChartAflowchart(orcontrolflowdiagram)isatypeofdiagramthatrepresentsaprocessandshowingthestepsbyconnectingvariouskindsoffigureswitharrows.Thisdiagrammaticrepresentationcangiveastep-by-stepsolutiontoagivenproblem.Flowchartshelpustoanalysisproblemsanddesigntheprocessofsolutionsbeforewebegintowritecodesofprograms.FlowChartNYProcessProcessSelectionStartInputEndOutputFlowChartNSDiagramNSdiagramisshortforNassi-Shneidermandiagram,tomemorizethecreatorsofthediagram,IsaacNassiandBenShneiderman.Itisanotherusefuldiagramtodescribetheprogramcontrolflows.Comparetoflowcharts,NSdiagramsomitthearrows,andusetable-likenotations,whichmakesthediagrammorecompactandneat.NSDiagramNSDiagramContinuationControlFlowTheprogramsofcontinuationcontrolflowaresimpleandstraightforward,butitstillcanperformsomeusefultasks.Thesewillbethefundamentalsformorecomplexprograms.Example1Example2AlgorithmsTheterm“algorithm”isusedinmathematicsandcomputerscience.Analgorithmisamethodexpressedasafinitelistofinstructionsforaspecifictask.Insimplewords,analgorithmdescribesastep-by-stepprocedureforacertainoperation.AlgorithmsanalgorithmtoswapthevaluesoftwovariablesBesidesthetwotargetvariables(namedvariable_a,andvariable_b),defineathirdtemporaryvariablewiththesametype(namedvariable_t).Assignthevalueofvariable_atovariable_t.Assignthevalueofvariable_btovariable_a.Assignthevalueofvariable_ttovariable_b.AGoodHabitBeforewritingthecode,thinkaboutthecontrolflow(algorithm)ofthewholeprogramDrawadiagramtohelpyoumakeitclearQuestion?Suggestion?HomeworkPage45:Exercise1,2,3Lecture5

SelectionICProgrammingLanguageOutlineRelationalOperatorsLogicalOperatorsif-elseselectionif-elseif-elseselectionNestedif-elseselectionRelationalOperatorsTherearesixrelationaloperatorsprovidedbytheCprogramminglanguage>>=<

<===!=RelationalOperatorsRelationaloperatorsareusedtoevaluatetherelationoftwoobjects.Allrelationaloperatorstaketwooperandstomakeanexpression,suchasm<n,x==y.Theoutcomeofevaluatingarelationalexpressioniscalledalogicalvalue.RelationalOperatorsTwologicalvalues:TRUE:Yes,Right,1FALSE:No,Wrong,0printf("outcome=%d",x==y);printf("outcome=%d",(x<y)+1);printf("outcome=%d",x<y+1);RelationalOperatorsPleasenotewedoNOTuseoperator==tocompareiftwofloatingpointnumbersareequalsornot.printf("%d",0.1==(1.0-0.9));LogicalOperatorsThreelogicaloperatorsusedintheCprogramminglanguageare:&&||!LogicalOperatorsLogicaloperatorsareusedtoperformlogicaloperationsbycomposinglogicalexpression.Boththeoperandsandtheoutcomesoflogicalexpressionsarelogicalvalues.Normallytheoperandsoflogicalexpressionsareactedasrelationalexpressions.suchas(x>3)&&(x<5).LogicalOperatorsIntheCprogramminglanguageyouarefreetouseanyobjects(variables,constants,orexpressions)astheoperandsforlogicalexpressions.Number0isregardedasanoperandofFalse,andanynone-zerovalueisregardasanoperandofTrue.LogicalOperatorsTrueTableoprandvalueaba&&ba||b!aTRUETRUE110TRUEFALSE010FALSETRUE011FALSEFALSE001LogicalOperatorsPleasenote:Thelogicaloperators&&and||evaluatedfromlefttoright,andevaluationstopsassoonasthetruthorfalsehoodoftheresultisknown.e.g.(x>5)&&(x<10)or(x>5)||(x<10)StatementsandBlocksStatement:anexpressionfollowedbyasemicolonBlock:groupofstatementsbybraces,alsocalledcompoundstatementif-elseselectionsyntax

if(expression) statement1 else statement2Example1,2

S1S2NYexptrue?if-elseselectionsyntax

if(expression) statement1Example3S1NYexptrue?if-elseif-elseselectionsyntaxif(exp1)S1elseif(exp2)S2……elseif(expm)SmelseSnif-elseif-elseselectionexp2?exp1?Sn

S1

S2

Sm…YNYNNYexpm?Example4,5,6Nestedif-elseselectionAselectionisabletonestwithinanotherselection.Example7,8Nestedif-elseselectionAbadnestedselection.

intx=2,y=-1,z=2;

if(x<y)

if(y>0)z=0;

elsez+=1;

printf("z=%d",z);Question?Suggestion?HomeworkPage65:Exercise1,2,3,4Lecture6

SelectionIICProgrammingLanguageOutlineReviewswitch-caseSelectionConditionalExpressionsReviewRelationalOperatorsLogicalOperatorsif-elseselectionif-elseif-elseselectionNestedif-elseselectionswitch-caseSelectionswitch-caseisausefulpatternformulti-branchselectionsbasedonavalue-matchingmechanism,whichisquitedifferentwithif-elseselection.switch-caseSelectionswitch(exp){casevalue_1:statement_1casevalue_2:statement_2……casevalue_n:statement_ndefault:statement}switch-caseSelectionswitch(a){case1:printf(“Monday”);case2:printf(“Tuesday”);……case7:printf(“Sunday”);default:printf(“InputError”);}switch-caseSelectionusebreakstatementtojumpoff switch-caseselectionwhennecessary.Whenabreakstatementoccurswithinaswitch-casepattern,theexecutionwilljumpoutoftheswitch-casefromthatpoint.switch-caseSelectionExample3-5TipsFlagsarewidelyusedtokeepspecificstatusforfurtherprocessing.ConditionalExpressionsConditionalexpressions(?:),providesanalternatewayforif-elseselection.max=(a>b)?a:b;if(a>b) max=a; else max=b;Question?Suggestion?HomeworkPage66:Exercise5,6,7,8Lecture7

LoopsCProgrammingLanguageOutlinewhileLoopsdo-whileLoopsforLoopsLoopsControlNestedLoopsAlgorithmPatternsgotoLoopsLoopsarewidelyusedtodealwithrepeatedworkwithspecificpatterns.Threetypesofloopswhiledo-whileforwhileLoopssyntax

while(exp)statement;Example1,2NYexpistrue?statementwhileLoopsBeforewritingaloopstructure,thinkabouthowmanytimedoyouwanttorepeat?howtostarttheloop?howtoendit?And…DonotmaketheloopendlessDonotrepeattheloopstatementonetimemore,oronetimelessdo-whileLoopssyntax

dostatement;while(exp);Example1’,2’NYstatementexpistrue?forLoopssyntax

for(exp1;exp2;exp3)statement;

Example1’’,2’’NYexp1

statementexp3exp2istrue?forLoopspleasenotethethreeexpressionswithintheforstatementcanbeomitted.Butthesemicolonsmustremain.for(;n<=100;n++)for(;n<=100;)for(;;)Practicewriteaprogramtocalculatethefactorialofanintegerx,whichisinputtedbyusers.LoopsControlbreak;andcontinue;statementscanbeusedtochangetheflowofloops.break; exitloopdirectly.continue; stoprunningtheremainstatementsofaloopandstartnextround.willchecktheloopconditionasnormalwillrunexp3inforloops

LoopsControlfor(i=1;i<5;i++){if(i%2==0)break;printf(“i=%d\n”,i);}for(i=1;i<5;i++){if(i%2==0)continue;printf(“i=%d\n”,i);}ThinkAbout...writeaprogramtoasktheusertoinputanintegerx,checkifxisaprimenumberornot.EndlessLoopsfor(;;)isaendlessloop,likewhile(1)Sometimesendlessloopsareuseful,butyoumustendtheloopproperly.Example2’’’NestedLoopsThestatementofaloopisanotherloopstructure.Therearetwo-layerloops,three-layerloops,orloopswithmorelayers.NestedLoopsHowtocalculate1!+2!+3!+…+10!NestedLoopsAnotherwaytocalculate1!+2!+3!+…+10!Donotusenestedloop.NestedLoopsHowtofindallprimenumbersbetween100and200?NestedLoopsWhatelsecannestedloopsdo?Example3,4AlgorithmPatternsOuterloopInnerloopSelection(flowcontrol)gotoandlabelsCprovidesgotostatementtojumpoff,andlabelstobranchto.if…goto…structureisabletoaccomplishaloopstructure.usinggotoisnotrecommended.Example5Question?Suggestion?HomeworkPage85:Exercises1,2,3,4,5,6,7CourseWork1TwoOptionsDrawingatreebyusingstars.Checkingdateformatlikeyyyy-mm-dd.Lecture8

ArraysICProgrammingLanguageOutlineArrayBasicsOne-DimensionalArraysArrayInitializationArraysandLoopsArrayBasicsAnarraypacksagroupofvalueswiththesametypeElementsofanarrayhaveindextoidentifyeachotherElementsofanarrayareallocatedwithconsequentmemoryonebyoneOne-DimensionalArraysyntaxTypeName[Capacity]; inta[5]; chars[100];Useindextoreferanarrayelement a[0]a[1]a[2]a[3]a[4] s[0]s[1]s[2]s[3]s[4]…s[98]s[99]One-DimensionalArrayRemembertheindexstartsfrom0,andendwithCapacity-1.Outofrangeindexisaveryseriouserror.

Bothconstantsandvariablescanbeusedastheindextoreferanarrayelement a[0]=1; a[i]=5;ArrayInitializationsyntax

TypeName[Capacity]={value_list};inta[3]={1,2,3};chars[5]={‘a’,‘b’,‘c’,‘d’,‘e’};inta[5]={1,2};

inta[]={1,2,3};ArraysandLoopsOperationsofarraysarecommonlycombinedwithloops.for(i=0;i<5;i++) scanf(“%d”,&a[i]); for(i=4;i>=0;i--) printf(“%d”,a[i]);ArraysandLoopsHowtofindthebiggestonefromanarray?inta[6]={15,21,13,18,25,16};ArraysandLoopsHowtofindthebiggestthreescoresfromallscoresofaclass?Question?Suggestion?HomeworkExercises1,4Lecture9

ArraysIICProgrammingLanguageOutlineSortingAlgorithmsSelectionsortingConstantsdefinitionBubblesortingInsertionsortingArraysandLoopsPracticeWriteaprogramtoasktheusertoinputthestudents’scoresofaclass.Findthehighestthreescoresandoutputthem. (Numberofstudentsisnomorethan30)ThinkAbout...sortinganarrayfrom{15,21,13,18,25,16};to{25,21,18,16,15,13};AnPossibleAlgorithmUseanewarrayasthedestination.Findthebiggestelementfromoriginalarrayandputittothenewarray.removethiselementfromoriginalarrayKeepdoingtheabovetwostepstilltheoriginalarrayisempty.SortingSortingalgorithmsSelectionsortingBubblesortingInsertionsortingSortingordersascendingorderdescendingorderalphabetorderSelectionsortingfindthebiggestonefromwholearrayswapitwiththefirstelementfindthebiggestoneexceptfirstelementswapitwiththesecondelementfind…swap…SelectionsortingThereareanotherwaytodotheselectionsortingConstantsdefinitionsyntax

#defineNameValue

#definePI3.14

#defineN30

s=PI*r*r; for(i=0;i<N;i++)BubblesortingFirstRoundcompare1stand2ndelement, if1st>2nd,swapthemcompare2ndand3rdelement, if2nd>3rd,swapthemcompare…swap…SecondRound…InsertionsortingBothselectionsortingandbubblesortingusethealgorithmpatternlikecompare-swap.Whileinsertionsortingusesthepatterncompare-insert.Insertionsortingisusefulforsortingthedatawhileinputtingthem.InsertionsortingForthefirstdatainputted,putitinthefirstpositionofthearray.Forthelaterinputteddata,itmustcomparewiththepreviousdatatofinditspositioninthearray.Itmayneedtomovesomedatabackwardtoputthenewdata.Anothersortingalgorithmusetwoarraysinsteadofone:Findthemaximumelementfromtheoriginalarrayandcopyittothefirstemptypositionofthedestinationarray.Removethiselementfromtheoriginalarray.Keepdoingtheabovetwostepstilltheoriginalarrayisempty.Question?Suggestion?Homeworkstudythesortingalgorithmsyouhavelearnedandkeeponeofthembyheart.Page108:Exercise5,6Lecture10

ArraysIIICProgrammingLanguageOutlineTwo-DimensionalArraysMulti-DimensionalArraysCharacterArraysandStringsTwo-DimensionalArraysTwo-DimensionalarraysusetwoindexestoidentifyanelementYoucanregardthetwo-dimensionalarrayasatablewithrowsandcolumns,eachrowisaone-dimensionalarrayExample1Two-DimensionalArraysInitializationsintA[3][4]={1,2,3,4,3,4,5,6,5,6,7,8};intB[3][4]={{1,2,3},{4,5},{6}};intC[][4]={1,2,3,4,3,4,5,6,5,6,7,8};intD[][4]={{1,2,3},{4,5},{6}};Example2,3Multi-DimensionalArraysUsemultiindexestoreferanelement. inta[3][4][5]; for(i=0;i<3;i++) for(j=0;j<4;j++) for(k=0;k<5;k++) a[i][j][k]=i+j+k;CharacterArraysCharacterArraycontainselementswithcharactertype,forexample:chara[5];charb[2][3];a[0]=‘A’;a[1]=‘B’;b[0][0]=‘C’;Example4CharacterArraysandStringsInClanguage,characterarraysareusedtoholdstrings.Atthattime,thecharacterarraysmustendwithacharacter‘\0’.Initialization

chara[6]={'C','h','i','n','a','\0'}; charb[6]=“China”; charc[]=“hello,world!”;ThinkAbout...What’sthedifferencesofthefollowingobjects:1,‘1’,“1”CharacterArraysandStringsForfunctionprintf/scanf,%sisusedasconversionspecificationtooutput/inputastring.Becausestringisalsochararrays,sowecanuse%ctoinput/outputeachcharacterofthestringindividually.Example5CharacterArraysandStringsNoticesinstatementscanf("%s",c);operator&isnotusedbeforethenameofthearrayc.youcannotinputastringcontainsblanks,suchas“helloworld”,bycallingfunctionscanf,becausetheblankswillbeconsideredastheseparatorsfordifferentvaluestobeinputted.StringOperationsLibraryfunctions(string.h)gets/putsstrlenstrcpystrcatstrcmpDemo&Example6Two-DimensionalCharacterArraysTwo-Dimensionalcharacterarraysarecommonlyusedtoholdalistofstringscharname[3][10]={"Alex","Mike","Tom"};Example7ThinkAbout...Howtosortingsomestrings?Question?Suggestion?HomeworkPage108:Exercises7,8,11,12Lecture11

FunctionsCProgrammingLanguageOutlineBasicsofFunctionsFunctionDefinitionFunctionCallRecursionsFunctionPrototypeDeclarationsStandardLibraryWhyfunctions?TomakeprogramsEasytounderstandMorereliableandefficientEasytore-useFunctionBasicsFunctionsareessentialelementoftheCprograms.mainisafunction,aspecialfunctionFourelementsofaFunctionNameArgumentsReturn_typeBodyFunctionBasicsFunctionDefinitionSyntax:Return_typeName

(Arguments){ …… statements ……}FunctionBasicsintadd

(inta,intb,intc){intsum; sum=a+b+c;returnsum; }FunctionBasicsKeyword:returnReturnavaluetothecallerExitthecalledfunctionFunctionCallAfunctionwillexecuteonlyifitisbecalledbyastatementofanotherfunction(caller).Whenafunctioniscalled,thecallerpausesforexecutingatthepointofthefunctioncall.Theexecutionoftheprogramwilljumptothecalledfunctiontoexecutethestatementsinitsbody.Afterthecalledfunctionisexecuted,itwillbacktothecaller.FunctionCallFunctionCallDifferentfunctioncallsnoreturnvalueandargument(Example1)noreturnvaluebutwithargument(Example2)withreturnvalueandargument(Example3)Pleasenote:thedefaultreturntypewillbeintifyoudonotdefineone.FormalArgument&ActualArgumentOneimportantprocessofthefunctioncallisthattheActual

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论