ProgrammingLanguage
QuickStartGuide
SimplifiedGuideforBeginners
By:
R.J.KHAN
Introduction
Areyoulookingforasimple,completeandquickreferenceforprogramminginC?Ifyes,you’llfindthisbookmoreusefulthananyotherbookoutthere.Thebookpresentsthegeneral-purposelanguage,stepbystep.Thebookiswrittenfollowingaprogrammer’sapproachandisthereforeidealforusingasaquickguideandreference.
Thebookishighlyrecommendedforstudentsastheirfirstorsecondprogrammingcourse.ItcoversallthebasicconceptsofprogrammingindetaillikeOperators,Functions,Decisionmakingstatements,Pointers,ArraysandStrings.ThebestthingaboutthebookistheSourcecodealongwithoutputattheinitialstagesofbook.Otherthanstudents,thebookisprettyhelpfulforprofessionalsaswellsinceithasathoroughanddetailedindexingoftopicsineachchapter.
Thebookallowstheaudiencetobeselectivebyreducingtheinter-connectivityinthetopics.Westartwithanoverviewofwholelanguage,whichinvolvesbriefhistory,basicfeaturesofC,comparisonandcontrastwithotherlanguages.
ThenwemoveontofamiliarizingthereaderswithCprogramsandsyntax.Wediscusstheimportantcomponentsofsyntaxindividuallyandindetail.Thissectionhassourcecodeinit,whichhelpsbuildingtheinterest,andlearningoftheaudience.
WestudyindetailabouttheFunctionsinC.Thebookdiscussesthebuiltinfunctionsaswellasdescribestherulesandbasicsofwritingyourownfunctions.Thechapteralsoincludesprogrammingexamples.
Arrays,pointersandStringsarestrongpointsofClanguageandhencearediscussedseparatelyinonechapter.Thetopicsarecloselyrelated,hencecomparisonsandcontrastsareworththediscussion.
WehaveanentirechapterdedicatedtoBinaryTreesbecauseoftheirimportance.WediscussedAbstractDatatypesaswellasstudiedtheexamplesofStacks,QueuesandLinkedlists.
ThebookillustratesthegeneralpurposeuseofprogramminglanguageC,detaileddocumentationoffeaturesprovidedbyC,theworkingsourcecode,
detaileddocumentationoffeaturesprovidedbyC,theworkingsourcecode,alongwithcomparisonbetweenobjectorientedlanguage,C++.ThedifferencesbetweenANSIC
andtraditionallanguage“C”areelaboratedindetailaswell.
R.J.Khan
Copyright2015byR.J.KhanAllrightsreserved.
Thisdocumentisgearedtowardsprovidingexactandreliableinformationinregardstothetopicandissuecovered.Thepublicationissoldwiththeideathatthepublisherisnotrequiredtorenderaccounting,officiallypermitted,orotherwise,qualifiedservices.
Ifadviceisnecessary,legalorprofessional,apracticedindividualintheprofessionshouldbeordered.
-FromaDeclarationofPrincipleswhichwasacceptedandapprovedequallybyaCommitteeoftheAmericanBarAssociationandaCommitteeofPublishersandAssociations.
Innowayisitlegaltoreproduce,duplicate,ortransmitanypartofthisdocumentineitherelectronicmeansorinprintedformat.Recordingofthispublicationisstrictlyprohibitedandanystorageofthisdocumentisnotallowedunlesswithwrittenpermissionfromthepublisher.Allrightsreserved.
Theinformationprovidedhereinisstatedtobetruthfulandconsistent,inthatanyliability,intermsofinattentionorotherwise,byanyusageorabuseofanypolicies,processes,ordirectionscontainedwithinisthesolitaryandutterresponsibilityoftherecipientreader.Undernocircumstanceswillanylegalresponsibilityorblamebeheldagainstthepublisherforanyreparation,damages,ormonetarylossduetotheinformationherein,eitherdirectlyorindirectly.
indirectly.
Respectiveauthorsownallcopyrightsnotheldbythepublisher.
Theinformationhereinisofferedforinformationalpurposessolely,andisuniversalasso.Thepresentationoftheinformationiswithoutcontractoranytypeofguaranteeassurance.
Thetrademarksthatareusedarewithoutanyconsent,andthepublicationofthetrademarkiswithoutpermissionorbackingbythetrademarkowner.Alltrademarksandbrandswithinthisbookareforclarifyingpurposesonlyandaretheownedbytheownersthemselves,notaffiliatedwiththisdocument.
TABLEOFCONTENTS
Chapter1
Let’sC………………………………………………………………6
1.Background……………………………………………………………….6
2.ANSIC……………………………………………………………………...7
3.StrengthsofC……………………………………………………………8
4.ProgramminginC……………………………………………………..9
5.NothingisPerfect……………………………………………………..10
Chapter2
TokensandSyntax…………………………………………..11
1.Preprocessors…………………………………………………………….11
2.Variables……………………………………………………………………14
3.Constants…………………………………………………………………..16
4.Keywords…………………………………………………………………..17
5.CharacterConstants……………………………………………………18
6.OperatorsandPunctuators…………………………………………23
7.PrecedenceandAssociativity………………………………………33
Chapter3
DataTypes………………………………………………………………37
1.IntegralDataTypes……………………………………………………38
2.Floatingpoint……………………………………………………………38
3.Using‘typedef’……………………………………………………..……39
4.Storageclasses…………………………………………………………..39
5.DefaultInitializers…………………………………………………….43
Chapter4
LoopsandDecisions………………………………………..44
1.Ifelse……………………………………………………………44
2.Switchcase…………………………………………………….46
3.Forloop………………………………………………………….48
4.Whileloop………………………………………………………50
5.Dowhileloop…………………………………………………….51
6.NestedLoops…………………………………………………….52
Chapter5
Functions……………………………………….……………….54
1.FunctionDefinition……………………………………………54
2.FunctionPrototypes………………………………………….57
3.AlternativeDeclarations……………………………………..58
4.FunctionInvocation……………………………………………59
5.Environment……………………………………………………..60
6.Recursion………………………………………………………….61
7.Examples…………………………………………………………..62
Chapter6
Arrays,StringsandPointers………………………………66
1.1-DArrays…………………………………………………………66
2.Pointers…………………………………………………………...68
3.Strings……………………………………………………………...72
4.2D-Arrays…………………………………………………………75
5.3D-Arrays…………………………………………………………76
Chapter7
Structures……………………………………………………….77
1.Declaration……………………………………………………..77
2.MemoryAllocation………………………………………….78
3.MemberAccessoperators………………………………..79
4.Definition……………………………………………………….80
5.AbstractDataTypes…………………………………………81
Chapter8
BinarySearchTree…………………………………………..90
1.Composition……………………………………………………90
2.InsertFunction………………………………………………..91
3.SearchFunction……………………………………………….92
Conclusion
Chapter1:Let’sC
ThischaptergivesanoverviewoftheCprogramminglanguage.Westartwithabriefbackgroundanddiscussprosandconsofthegeneral-purposelanguage.Afterthat,aseriesofprogramsfollows,andtheelementsofeachprogramarecarefully,line-by-lineexplained.Weemphasizeonhowtousethebasicinput/outputfunctionsofC.AswediscussindetailthesimilaritiesbetweenCandC++,youcanfairlyassumethattheprogramswrittenaresyntacticallycorrectforboththelanguagesandtheconceptselaboratedarealsocommon.Ofcourse,theC++programmerhasmorecapabilitiesusingtheobjectorientedprogrammingconcepts.WerecommendthateveryonereadsthischapteroutsothattheyknowthebasicsaboutCandprogramminginC.Everyoneshouldreadthischaptereveniftheydon’tunderstandeverythingbecauseeverythingisexplainedindetaillateron,inthebookbuttheintroductioninthischapterisimportant.
1.1Background:
CisaproceduralprogramminglanguagethatwasoriginallydesignedbyDennisRitchieatBellin1972.UNIXoperatingsystemuseditasthesystemslanguage.CwasdesignedtoovercometheshortcomingsofaprogramminglanguageB,whichwasdesignedbyK.
ThompsonwhileworkingoninitialversionsofUNIX.BwasaprogramminglanguagebasedonBCPL,atypelesssystemsprogramminglanguage,developedbyMartinRichardsin1967.Itsbasicdatatypewasthemachineword,anditmadeheavyuseofpointersandaddressarithmetic.Itiscompletelydifferentfromtraditionalstructuralprogramming,whichinvolveduseoftypedcommands.AlthoughCinitiallyevolvedfromBandBCPL,butitincludedtyping.
Bytheearly1980s,thelanguagehastransformeditselfintowhatitlooksliketoday,commonlyknownasthetraditionalC.ANSIstandardCwasintroducedinthelaterpartofthesamedecade.Thecommitteeaddedthevoid,functionprototypes,anewfunctiondefinitionsyntax,andmorefunctionalityforthepreprocessor,andingeneralmadethelanguagedefinitionmoreprecise.
ANSICmaintaineditsstandardinanamazingwaythatitisstillusedinmanyprogramsasasystemlanguage.Itisoneofthemostcommonlyusedprogramminglanguagesoftheworld,anditisfoundincollegesanduniversitiesforlearningpurposes.ItismostlythefirstprogrammingcourseofferedtoanyITstudents.C++isanextensionofANSIstandardCwhichincorporatestheobjectorientedprogrammingparadigm,whichkindofrevolutionizedtheprogrammingworld.ThisbookdescribestheANSIversionoftheC
language,alongwithsometopicsinC++aswell.
1.2ANSIStandardC:
ANSIstandsfor"AmericanNationalStandardsInstitute."Thisinstituteisinvolvedinsettingstandardsfordifferentsystems,includingprogramminglanguages.Standards
areimportantinasensethateveryonecanhavehisownperspective.Forexample,whiletravellinginatrain,whatseemstobestationaryforyou,might
example,whiletravellinginatrain,whatseemstobestationaryforyou,mightbemovingforsomeoneoutsidethetrain.ANSICommitteeX3Jl1isresponsibleforsettingthestandardfortheprogramminglanguageC.Inthelate1980s,thecommitteecreateddraftstandardsforwhatisknownasANSICorstandardC.In1990,theInternationalOrganizationforStandardization(ISO)approvedthestandardforANSICaswell.
Thus,ANSIC,orANSI/ISOC,isaninternationallyrecognizedstandardforprogramminginC.ThestandardspecifiestheforminwhichprogramsarewritteninC
anddefinesthestandardsforhowtheseprogramsaretobeinterpreted.Thestandardizationresultsinbetterportability,reliability,maintainability,andefficientexecutionofClanguageprogramsondifferentmachines.Allthecompilersfollowthisstandardandhencethereisuniformityininterpretationofcode.
1.3StrengthsofC:
Theprogramminglanguagesthatarebeingusedtodayaresopowerfulthatnothingremainsimpossible.Butthispowerdependsdirectlyonhowvastalanguageis,whichisdeterminedbynumberofreservedkeywords.ChasfewerkeywordsthanPascal,butitismorepowerfulthanit.ThepowerofCliesintheunrestrictedstructureofprogramminginit.Although,Chasitslimitationslikeanyotherlanguagebutitcomesasthebestinitscapacity.BecauseCisasmalllanguage,henceitisidealtostartyourprogrammingcareerfromit.Itiseasytomasterwhencomparedwithotherlanguages.OnceyouhavemasteredC,youcantheneasilymoveontothemorepowerfulandvastlanguages.
WewillnowbrieflydiscussthestrongcharacteristicsofC,whichwillmotivatethereaderstoprograminC.
•UNIXisamajorinteractiveoperatingsystemonworkstations,servers,andmainframes.CisthebasiclanguageusedonUNIXplatform.Manywindowingpackages,databaseprograms,graphicslibraries,andotherlarge-applicationpackagesarewritteninC.
•Cisportable.Codewrittenononemachinecanbeeasilymovedtoanother.Theprogrammerisprovidedwithastandardlibraryoffunctionsthatworkindependentlyofmachines.Evenifthereisasystemdependentcode,theprogrammerisgiventhecapabilitytosingleitoutusingpreprocessorprovided
programmerisgiventhecapabilitytosingleitoutusingpreprocessorprovidedbyC.
•PersonalComputersusedCastheirprogramminglanguage.
•Cissmallbuthasaverypowerfulsetofoperators.Someoftheseoperatorsallowtheprogrammertoaccessthemachineatthebitlevel.Forexample,apowerfulincrementoperator“++”canmanipulatethemachineinthesamewayasmachinecodedoes.Thisresultsinhigherefficiencyasotherlanguagesrequiremultiplestatementstocompletetheequivalenttask.
•Cismodular.Cusestheexternalfunctions,forwhichargumentsarepassedusingcall-by-valuetechnique.Pointersareusedforpassingargumentsusingcall-by-referencetechnique.Thenestingoffunctionsisnotallowed.Usingthestorageclassstaticwithinfilesprovidesalimitedformofprivacy.Thesefeatures,alongwithtoolsprovidedbytheoperatingsystem,readilysupportuser-definedlibrariesoffunctionsandmodularprogramming.
•ClaidthebasisforC++andJava.Thiscanbeclearlyseenbyanalyzingthecommonattributesandfunctionalitiesoftheselanguages.C++andJavasupportthebasicstructureoffunctions,methodsorroutinesinC++orJava.Theprimitivedatatypesareretainedaswell.Thus,learningCpriortolearningC++
orJavaisagoodthing.
•CertainconstructsinCaredependentonmachines,implementationoftheseconstructsisuptotheprogrammertosupportthetargetedmachine(s).Thus,C
cansupportmultiplemachines.
1.4ProgramminginC:Programsaresetofinstructionsthatareexecutedbyacomputerprocessor.Programsare,atthelowestlevel,combinationsof0sand1s.Thesecombinationsarecommonlyknownasmachinecode.The0sand1sarecommonlyknownasbitsorbinarydigits.
Machinelanguageisclosesttomachinebutitisawayfromhumanbeingsinawaythatitisverydifficulttoremembersequencesof0sand1s.Thereforeweuselow-levellanguageslikeAssemblyLanguageandHighLevellanguageslike
uselow-levellanguageslikeAssemblyLanguageandHighLevellanguageslikeC,C++andJava.
Assemblylanguagehasshortlabelsforcertaincommandstodocertaintasks,forexampleADD,MOVetc.HighLevellanguagesaretheeasiestwayforaprogrammertocommunicatewithamachine.
Cisahighlevellanguage.Itisimportanttoknowthatcomputeronlyunderstandsmachinelanguage.AssemblylanguageandHigh-levellanguagesareusedforaidingprogrammersratherthancomputer.Thecodewrittenbyhumansinassemblyandhigh-levellanguagesistranslatedintoitsbinaryformsothatcomputercanunderstandit.
ThesourcecodeforCiswritteninsometexteditorandcompiler.CommonexamplesofsucheditorsareTurboC++,BorlandC++etc.WewillbeusingVisualStudio2012forcodingthroughoutinthisbook.
1.4.1FirstPrograminC
Firstofall,youneedtosetupyourIDE(IntegratedDevelopmentEnvironment).WerecommendBorlandC++.VisualStudioisforprosbutisnotagoodchoiceforstudentsbecauseofitshelpfulnature.Fromhereonwards,weassumethatyouhaveanIDEinstalledonyourcomputersystemandcancompileasourcecodeinC.
Youneedtocreateanewfilewith.cor.cppextension.Thisfilewillhaveyoursourcecode,whichwillbecompiledusingyourrespectivecompiler.Let’snameourfileas“myFirstProgram.c”.
In“myFirstProgram.c”:
#include<iostream>
voidmain(void)
{
printf("ThisismyfirstPrograminC\n");}
Beforegoinganyfurther,let’sjusttrytocompileandexecutethiscode.Ondoingso,you’llrealizethatablackscreenappearsforamillisecondandthendisappears.
Whatactuallyhappensis,thatthecomputerrunstheprogramandexitswhenthesourcecodeends.Soitexitsbeforeusseeinganyoftheoutput.Tostopourprogramfromdoingit,weneedtoaddanextralineattheendofourcode.
#include<iostream>
voidmain(void)
{
printf("ThisismyfirstPrograminC\n");
system("pause");
}
If
no
errors
are
made,
the
output
will
be
like
this:
Thefirstlineofourprogramincludesalibraryinourprogram.Thislibraryhasthefunctionslikeprintf,systemandsimilarlyotherswhichwecanuseinourprogram.
Thenextlinedeclaresourmainmethod.Themainmethodinanyprogramistheentrypointforourlogic.Programsstartfromexecutingthisfunction.Theword“void”isusedtoindicatethattheparameterunderconsiderationisnullandvoid.
Thefirstvoidrepresentsthatthemainfunctionreturnsnothing.Thenextvoidinsideparenthesisindicatesthatthemainfunctionispassednothingatthestart.
We’llseehowthesetwovoidtypescanbereplacedbyotherdatatypesasdemandedbyourprogramlogic.
Itisimportanttonotethatbracesareusedtorepresentblocksinourcode.Fornow,youneedtoknowthatthebodyofourmainfunctionlieswithinbraces.Anythingoutsidethesebracesisnotexecutedwhenmainfunctionisexecuted.
Insideourmainfunction,wehavetwostatements;printfandsystem.PrintftakesaString,astreamofcharactersasinputanddisplaysitonthescreen.The‘\n’attheendofourlineinprintfstatementindicatesthestartofnewline.Thenextlineusesthesystemtopausetheprogram,sothatwecanseetheoutputasexplainedearlier.
Asemi-colonendseachstatement.Semi-coloniscommonlyknownasstatementterminator.
So,westopherefornow.Codingorprogrammingisn’tadifficultthingatall.
So,westopherefornow.Codingorprogrammingisn’tadifficultthingatall.Allitdemandsisalittlepractice.WestronglybelieveyouwillbeanefficientcoderinC
afterfinishingthisbook.
1.5Nothingisperfect:Likeeveryotherlanguage,Chasitsshortcomings.Ithasacomplicatedsyntax.Forexample,acommonprogrammingerroristousedifferentoperatorinsteadoftheoperator==.Nevertheless,Cisstilladecentlanguage.Itdoesn’trestricttheprogrammertoaccessthemachine.Somecanconsidertheliftingofrestrictionsasanimperfection,butIpersonallythinkithasmoreprosthancons.Cattractsprogrammersbecauseofthese“imperfections”.Modularityinthesourcecodeisoftenconsideredcritical.InC,itisactuallydependentonprogrammers,whichalwayspreferthatthereisminimaldependencybetweenfunctions.ACprogrammerwelcomesexperimentationandinteractionaswell,dependinguponcertainsituations.
Chapter2:TokensandSyntax
Inthischapter,weexplainthesyntaxandlexicalelementsoftheCprogramminglanguage.Cisahighlevelprogramminglanguage.Likeotherhighlevellanguages,ithasrulesandprinciplesforputtingtogetherdifferentcomponentstocreatelegalandworkingprograms.Theserulesandprinciplesdefinethesyntaxofthelanguage.
TheprogramthatchecksonthelegalityofCcodeiscalledthecompiler.Thecompilertranslateseachlineofcodeintomachinelanguagetoseeifthereareanyerrors.Ifthereisanerror,thecompilerwillprintanerrormessageandstop.Ifthecompilerfindsnoerrors,thenthesourcecodeiscorrect,andthecodeistranslatedintoobjectcode.Theobjectcodeisusedbyloadertocreateanexecutablefile.
Aswediscussedearlier,thepreprocessorsareprocessedpriortoexecutionofremainingcode.Wecanthinkofthepreprocessorasbeingbuiltintothecompiler.Thisiswhatactuallyhappensonsomesystems,whereasonothersthepreprocessorisseparate.Thismightnotconcernusatthisstagebutwehavetobeaware,however,thatpreprocessorsandcompilercanbothcausevariouserrorsinourprograms.Letusdiscusspreprocessorsinabitofdetailnow.
2.1PreprocessorsCcompilerhasapreprocessorbuiltintoit.Linesthatbeginwitha#arecalledpreprocessors.Wehavesofarused#defineand#include.Thecompilerprocessesthesepreprocessorsbeforeactuallycompilingacode.Forexample,whenwedefinedaconstantusing#defineinsection2.2,thecompilerreplacedalltheinstancesofPIwiththevaluespecifiedatthestartbeforecompilingthecode.SuchconstantsareusuallyknownasSymbolicconstants.
Wewriteallthe#definestatementsatthetopofourfile.Itisaconventiontowriteallthelettersofaconstantincapital.FollowingthisconventionenablesprogrammerstoeasilyidentifySymbolicconstantsoranyotherconstantsaswell.Itisimportanttonotethatthough,thepreprocessorneverchangesthecontentsofquotedstrings.Forexample,inthefollowingstatement,onlysecondPIwillbereplacedbythevaluedefinedbypreprocessorPI.
printf("PI==%f\n",PI);
Theprogrambecomesmorereadablebyusingpreprocessors.Itmakeseasyto
Theprogrambecomesmorereadablebyusingpreprocessors.Itmakeseasytofollowtheflowofprogram.Moreimportantly,ifaconstanthasbeendefinedsymbolicallybymeansofthe#definefacilityandusedthroughoutaprogram,itiseasytochangeitlater,ifnecessary.Forexample,thelettercisuniversallyacceptedtobeusedtorepresentthe
speedoflight,whichisapproximately299792.458lan/sec.IfwewritethefollowingpreprocessorandthenusetheletterCthroughouttensofthousandsoflinesofcodetorepresentsymbolicallytheconstant299792.458,itwillbeeasytochangethecodewhenanewphysicalexperimentproducesabettervalueforthespeedoflight.Allthecodeisupdatedbysimplychangingtheconstantinthe#defineline.Sucharetheadvantagesofusingpreprocessors.
#defineC299792.458
#includefilename.hisapreprocessingdirectivethatcausesacopyofthefilefilename.htobeincludedatthepointinthefilewhenitiscompiled.A#includelinecanoccuranywhereinafile,thoughitistypicallyattheheadofthefileasaconvention.Itisnecessarytospecifythefilenameinquotesasitindicatesthatitisapredefinedfile.Thefilespecifiedinsuchdirectives,isalsocalledaheaderfile.Theseheaderfilescancontain#definelinesandother#includelines.Thenamesofheaderfilesendin.hextension.
TheCsystemprovidesanumberofstandardheaderfiles.Someexamplesarestdio.h,string.h,andmath.h.Thesefilescontainthedeclarationsoffunctionsinthestandardlibrary,macros,structuretemplates,andotherprogrammingelementsthatarecommonlyused.Commonexamplesofsuchheaderfilesareconio.h,stdio.h,stdfx.h,math.handothers.Thesefilescontaincertainsystemfunctionssuchasstdioprovidesthecoderwithfunctionsasprintfandscanf.Wemustincludethisheaderfilebeforewecanusethesefunctionsinourprogram.We,sofarhaveusediostream,whichisshortformofinput/outputstreamincludedusingthe#includedirective.
Letusjustseeanexampledemonstratinghowusingaheaderfileworks.Followingiscodewritteninaheaderfilenamedas“myFirstHeaderFile.h”
#include"iostream"
#definePI3.14159265359
#definePI3.14159265359
#defineLENGTH200
#defineWIDTH300
#defineHEIGHT400
#definePERIMETER2400
#defineOWNER"EMMAWATSON"
Thefollowingisthecodetobewrittenina.cppfilewhichincludesourheaderfileinit.
IfyouareusingVisualStudio,simplyaddtheheaderfileinthesameprojectasthe.cor.cpp)fileisin.
#include"myFirstHeaderFile.h"
voidmain(void)
{
floatArea=PI*LENGTH*HEIGHT*HEIGHT*WIDTH;
printf("ThisisaProgramtodemonstrateuseofHeaderFilesinC\n");
printf("ListofConstantstofollow\n");
printf("Owner:%s\n",OWNER);
printf("Length:%d\n",LENGTH);
printf("Width:%d\n",WIDTH);
printf("Height:%d\n",HEIGHT);
printf("PI:%f\n",PI);
printf("Areaofwhatevershapeitbecomesis:%f\n",Area);
system("pause");
}
Theoutputfortheaboveprogramisasfollows:
Asyoucansee,theprogramworksjustasthecodeintheheaderfilewaswritteninourcfile.Thisisjustasimpleexampletodemonstratetheuseofheaderfiles.Weactuallyuseheaderfilesbecauseprogramsbecometoocomplexandit’sbettertohandletheminsmallerfileswithlessercomplexity.Wedividethefunctionalityintodifferentcategoriesandwritecodeandfunctionsforeachcategoryinaseparatefile.Inthisway,itbecomeseasiertodigesteachsmallerchunkofacode.
ACprogramisasequenceofcharacters.Thissequenceofcharactersistransformedintoobjectcodebycompiler.Theobjectcodeistranslatedintoatargetlanguagedependinguponthemachine.Targetlanguage,onmostofthesystemsisthemachinelanguagethatcanbeinterrupted.Theprogrammustbecorrectinitssyntax.Thecompilertakeseachcharacterasatoken.Tokenisconsideredasthebasicunitofvocabularyinthelanguage.
InANSIC,therearesixkindsoftokens:keywords,identifiers,constants,stringconstants,operatorsandpunctuators.Wewilldiscusseachofthesetokensinthis
constants,operatorsandpunctuators.Wewilldiscusseachofthesetokensinthischapter.Theroleofacompileristocheckifallthetokenscanbetranslatedintoproperunderstandablestringsaccordingtothecompilerrequirements.Mostcompilersareverypreciseintheirrequirements.
Computersaredumb.We,thehumanshavethecapabilitytounderstandalinemoreefficientlyifanextrapunctuationmarkisusedinasentencebutcomputersontheotherhandwillnotbeabletounderstandasentenceifithasanextrapunctuationmarkcalledtoken,itisnotfamiliarwith.Hence,theprogrammermustbefamiliarwithwhichtokenscanbeusedandwhichcannotbe.
Intheremainingpartofthischapter,wewillbecoveringthebasicstructureelementsofanyCprogram.Everylargethingintheuniversecomprisesofsmallercomponents.
Thesesmallercomponentsmightnotbethateffectiveindividually,butassemblingtheminarightwaycertainlyleadstoagreatersuccess.
ThescenariomentionedaboveistrueforthelanguageCaswell.CconsistsofindividualcomponentscalledFunctions.FunctionsareconsideredasbasicstructuralelementinC
programming.TheFunctionsthemselvescompriseofsmallercomponentslikeVariables,constants,operatorsandotherfunctionsaswell.WewillstudyFunctionsindetailinanotherchapter.Inthischapter,wewilldiscusstheseindividualcomponentsonebyone.
2.2Variables
Avariablename,alsoknownasanidentifier,consistsofasequenceofletters,digits,andunderscores,butmaynotstartwithadigit.Thesevariablesareusuallydeclaredatthestartofprogrambutyoucandeclareoneanywhereinyourprogrambeforeusingit.Youcanstorevaluesinthesevariablesdependingupontheirdatatypesand“vary”thematanystageofyourprogram.Identifiersshouldbechosentoreflecttheiruseintheprogram.Inthisway,theyserveasdocumentation,makingtheprogrammorereadable.
Thereisacodeforeverythingwedoinlife.Similarly,wehaverulesforwritingvariablenameinC.Variablenamecanbecomposedofuppercaseand/or
variablenameinC.Variablenamecanbecomposedofuppercaseand/orlowercaseletters,digitsandonlyonespecialcharacterthatis‘_’.Thefirstletterofavariablemustbeeitheraletteroranunderscore.But,itisdiscouragedtostartvariablenamewithanunderscorethoughitislegalbecause,variablenamethatstartswithunderscorecanconflictwithsystemnamesandcompilermaycomplain.Thelengthofavariablenamehasnorestrictions.However,thefirst31charactersofavariablearediscriminatedbythecompiler.So,thefirst31lettersoftwovariablesinaprogramshouldbedifferentbyatleastonecharacter.
Letusgettoknowtheuseofvariablesbyquotingsomepracticalapplications.Hereisaprogramtocalculatesumoftwonumbers:#include<iostream>
voidmain(void)
{
intfirstNumber=10;
intsecondNumber=5;
intsum=firstNumber+secondNumber;
printf("ThisisaProgramtodemonstrateuseofvariablesinC\n");
printf("Firstnumberis:%d\n",firstNumber);
printf("Secondnumberis:%d\n",secondNumber);
printf("Theirsumis:%d\n",sum);
printf("Theirsumis:%d\n",sum);
system("pause");
}
Theoutputforaboveprogramisasfollows:
Someofyoumightbewonderingwhyusethevariableshereinsteadofjustusingthenumbers.Thatwouldbeeasybutitwillhavelimiteduseaswellasabadprogrammingapproach.Letusaddafewmorelinestotheabovecodetoprovethesetwopoints:#include<iostream>
voidmain(void)
{
intfirstNumber=10;
intsecondNumber=5;
intsum=firstNumber+secondNumber;
printf("ThisisaProgramtodemonstrateuseofvariablesinC\n");
printf("Firstnumberis:%d\n",firstNumber);
printf("Secondnumberis:%d\n",secondNumber);
printf("Theirsumis:%d\n",sum);
firstNumber=3;
firstNumber=3;
secondNumber=4;
sum=firstNumber+secondNumber;
printf("Firstnumberis:%d\n",firstNumber);
printf("Secondnumberis:%d\n",secondNumber);
printf("Theirsumis:%d\n",sum);
system("pause");
}
Asyoucanseethattheprintstatementsareduplicatedinthesecondcode,butthevaluesarechangedbyjustchangingthevariables.So,wecanusesamecodetogetdifferentoutputbyjustchangingvariables.Thisgivesusahugeadvantage.Forexample,considerascenariothatyouhavealistof300studentswiththeirobtainedmarksinauniformCprogrammingtest.Whatwouldbethebestwaytorepresenttotalmarksforthislist?Wouldyourecommendwritingtotalmarkswitheachentry?Absolutelynotbutjustconsiderforasecondthatyoudothatandthenyoufindoutthattotalmarksare50
insteadofhundred.Youareboundtomakeachangeieachentry.Toavoidallthis,youcouldjustassignavaluetoavariableandusethatvariableineachentry.Thisiswhatvariablesareactuallyusedfor.Variablesareacriticalcomponentofanyprogram.
2.3Constants
Aconstantissomethingwhosevaluedoesnotchangethroughouttheprogramexecution.Thesearefixedforapurposethough.Forexample,usingstandardvaluesforcertainentities,forhavingnottotypealongdigitorvaluelike3.141517...ormakingtheprogrameasytofollowbymentioningalltheconstantvaluesinoneplace.
LetusjustgothroughaCprogramusingconstants:
#include<iostream>
#definePI3.14159265359
voidmain(void)
{
intradius=10;
floatArea=PI*radius*radius;
printf("ThisisaProgramtodemonstrateuseofConstantsinC\n");
printf("Radiusofcircleis:%d\n",radius);
printf("Areaofcircleis:%f\n",Area);
system("pause");
}
Weusedpreprocessor#definetodeclareaconstantPIinthisprogram.ThisisaflexibleandrecommendedwaytouseconstantsinC.Thereisanotherwaytouseconstantsaswellusingthekeyword‘const’.Letusseehowthatworkstoo:#include<iostream>
voidmain(void)
{
intradius=10;
constfloatPI=3.14159265359;
floatArea=PI*radius*radius;
printf("ThisisaProgramtodemonstrateuseofConstantsinC\n");
printf("Radiusofcircleis:%d\n",radius);
printf("Areaofcircleis:%f\n",Area);
system("pause");
}
2.4Keywords
Keywordsarereservedwordsinanylanguage.Thesewordsarealreadyreservedforaparticularfunctionalitysoprogrammerscannotusethem.Thesekeywordsrepresentprimitivedatatypes,pre-builtfunctionsandotherprogrammingcomponents.
HereisalistofkeywordsinC,predefinedbyANSI:Keywords
Functionality
auto
Definesalocalvariableashavingalocallifetime.
break
Passescontroloutofthecompoundstatement.
case
UsedtoprogramalogicbaseddecisiononinputthroughSwitch.
char
Usedtodefineacharactertypevariable.
const
Makesvariablevalueorpointerparameterunmodifiable.
continue
Passescontroltothebeginningoftheloop.
default
Usedinswitch-casestatementsfordefiningdefaultoperation.
do
Thiskeywordalongwith‘while’isusedforaspecialkindofloop.
double
Thiskeywordisusedfordefiningavariableoftype‘double’.
else
Usedalongwith‘if’fordefininganalternateforacertaincondition.
enum
Definesasetofconstantsoftypeinteger.
extern
Usedtoindicatethatavariableisdefinedoutsidecurrentprogram.
float
Usedtodefineafloatingtypevariable.
for
Usedtoprograma‘for’loop.
goto
Usedtomovecompilerinaprogram,unconditionally.
if
Defineadecisionstatement.
int
Definesanintegertypevariable.
long
Definesalongtypevariableofrequiredtype,e.g.int.
register
TostoreavalueinavariableintoaCPUregisterreturn
returncontroltothepreviousblockinCPUregistershort
Usedtomodifyavariableofdatatypementionedwith‘short’.
signed
Usedasadatatypemodifier
sizeof
Returnsthesizeoftheexpressionortype.
static
Usedtosaveavariableevenafteritsscopeends.
struct
TodefineacustomizedDataStructureaccordingtorequirements.
switch
Usedasadecisionmakingstatement,Switch-case.
typedef
Definesanewdatatype.
union
Groupsvariablesthatsharesamestorage.
unsigned
Usedasadatatypemodifier.
void
Emptydatatype.
volatile
Oppositeofthekeyword,‘const’.
while
Usedtodefinerepetitionloops.
2.5CharacterConstantsThissectionaddressesthecharacterconstantswhichhaveacertainmeaningincertainsituations.Characterliteralsareenclosedinsinglequotes,e.g.,'a'andcanbestoredinasimplevariableofchartype.
Acharacterliteralcanbeaplaincharacter,anescapesequence,orauniversalcharacter.
Acloselyrelatedtopic,stringconstant,orastringliteralisasequenceofcharactersenclosedinapairofdouble-quotemarks,suchas“Khan”.Interestingly,astringconstantconsistsofmultiplecharactersbtistakenasasingletokenbycompiler.Stringsarestoredasarraysofcharacters.Itisimportanttonotethoughthatstringconstantsaredifferentfromcharacterconstants.Forexample,'a'and"a"arenotthesame.“a”
consistsoftwocharactersactually.Firstoneis‘a’andthenextoneis‘0/’.ThesecondonerepresentsNULL.
Clanguageprovidescertaincharacterconstantswhosemeaningsarepredefinedlikewehaveused“\n”anumberoftimestoindicatethetartofnewline.SuchcharactersareknownasEscapeSequences.Remember,thesecharactersandthesemeaningsareapplicablewhenwritteninsidedoublequotesasastring.Hereisalistofthecommonescapesequencecharacters:
Escape
sequence
Meaning
\\
\character
\'
'character
\"
"character
\?
?character
\a
Alertorbell
\b
Backspace
\f
Formfeed
\n
Newline
\r
Carriagereturn
\t
Horizontaltab
\v
Verticaltab
\ooo
Octalnumberofonetothreedigits
\xhh..
HexadecimalnumberofoneormoredigitsThenwehaveASCIIcharacters,thatarelistedbelow:CharDecAction
NUL
0
Nullcharacter
SOH
1
Startofheading,=consoleinterruptSTX
2
Startoftext,maintenancemodeonHPconsoleETX
3
Endoftext
EOT
4
Endoftransmission,notthesameasETB
ENQ
5
Enquiry,goeswithACK;oldHPflowcontrolACK
6
Acknowledge,clearsENQlogonhand
BEL
7
Bell,ringsthebell...
BS
8
Backspace,worksonHPterminals/computersHT
9
Horizontaltab,movetonexttabstopLF
10
LineFeed
VT
11
Verticaltab
FF
12
FormFeed,pageeject
CR
13
CarriageReturn
SO
14
ShiftOut,alternatecharacterset
SI
15
ShiftIn,resumedefaultncharactersetDLE
16
Datalinkescape
DC1
17
XON,withXOFFtopauselistings
DC2
18
Devicecontrol2,block-modeflowcontrolDC3
19
XOFF,withXONisTERM=18flowcontrolDC4
20
Devicecontrol4
NAK
21
Negativeacknowledge
SYN
22
Synchronousidle
ETB
23
Endtransmissionblock,notthesameasEOT
CAN
24
Cancelline,MPEechoes!
EM
25
Endofmedium,ControlYinterrupt
SUB
26
Substitute
ESC
27
Escape,nextcharacterisnotechoedFS
28
Fileseparator
GS
29
Groupseparator
RS
30
Recordseparator,block-modeterminatorUS
31
Unitseparator
TheaboveislistofallthecontrolASCIIcharacters.FollowingisthelistofprintableASCIIcharactersinASCII.
CharDecDescriptionSP
32Space
!
33Exclamationmark
"
34Quotationmark
#
35Crosshatch(numbersign)
$
36Dollarsign
%
37Percentsign
&
38Ampersand
`
39Closingsinglequote(apostrophe)(
40Openingparentheses
)
41Closingparentheses
*
42Asterisk(star,multiply)
+
43Plus
,
44Comma
-
45Hyphen,dash,minus
45Hyphen,dash,minus
.
46Period
/
47Slant(forwardslash,divide)
0
48Zero
1
49One
2
50Two
3
51
Three
4
52Four
5
53Five
6
54Six
7
55Seven
55Seven
8
56Eight
9
57Nine
:
58Colon
;
59Semicolon
<
60Lessthansign
=
61Equalssign
>
62Greaterthansign
?
63Questionmark
@
64At-sign
A
65UppercaseA
B
B
66UppercaseB
C
67UppercaseC
D
68UppercaseD
E
69UppercaseE
F
70UppercaseF
G
71
UppercaseG
H
72UppercaseH
I
73UppercaseI
J
74UppercaseJ
K
75UppercaseK
L
76UppercaseL
M
77UppercaseM
N
78UppercaseN
O
79UppercaseO
P
80UppercaseP
Q
81UppercaseQ
R
82UppercaseR
S
83UppercaseS
T
84UppercaseT
U
85UppercaseU
V
86UppercaseV
W
87UppercaseW
X
88UppercaseX
Y
89UppercaseY
Z
90UppercaseZ
[
91Openingsquarebracket
\
92Reverseslant(Backslash)
]
93Closingsquarebracket
^
94Caret(Circumflex)
_
95Underscorè
96Openingsinglequote
a
97Lowercasea
b
98Lowercaseb
c
99Lowercasec
d
100Lowercased
e
101Lowercasee
f
102Lowercasef
g
103Lowercaseg
h
104Lowercaseh
i
105Lowercasei
j
106Lowercasej
k
107Lowercasek
l
108Lowercasel
m
109Lowercasem
n
110Lowercasen
o
111Lowercaseo
p
112Lowercasep
q
113Lowercaseq
r
114Lowercaser
s
115Lowercases
t
116Lowercaset
u
117Lowercaseu
v
118Lowercasev
w
119Lowercasew
x
120Lowercasex
y
121Lowercasey
z
122Lowercasez
{
123Openingcurlybrace
|
124Verticalline
}
125Closingcurlybrace
~
126Tilde(approximate)
DEL127Delete(rubout),cross-hatchbox
2.6OperatorsandPunctuatorsLikeeveryotherprogramminglanguage,Chas
manycharacterswithcertainmeanings.
ExamplesincludetheArithmeticoperatorswhichstandfortheusualarithmeticoperationsofaddition,subtraction,multiplication,division,andmodulus,respectively.
Modulusinmathematicsreturnstheremainderafterdividinganumberbyanother.Forexample,thevalueof“amodulusb”isobtainedbytakingtheremainderafterdividingabyb.%isthecharacterusedforModulusopertioninC.Thus,15%7hastheanswer1,and7%5resultsin2.
Inaprogram,operatorscanbeusedtoseparateidentifiersthatareinvolvedinanexpression.Remember,anexpressionisastatementthatendswithasemicolon.Itisgoodpracticetogivewhitespacesbetweeneachidentifierandoperatorstogivebetterreadabilitybutitisnotnecessary.CompilerignoresWhitespacesunlesstheyarequotedinthecode.So,thefollowingstatementsareidenticaltothecompiler,X=A+B;
X=A+B;
Contextisveryimportantinalmosteverything.Symbolschangetheirmeaningdependinguponwhereandhowtheyareused.Forexampleconsiderthefollowingtwostatementswhichuse%symbolintwodifferentcontexts.
printf("Owner:%s\n",OWNER);
intx=15%4;
Thefirst%symbolisthestartofaconversionspecification,orformatwhichisrelatedtotheidentifierinthelaterpartoftheexpression,whereasthesecond%symbolrepresentsthemodulusoperatorofmathematics.
Examplesofpunctuatorsincludeparentheses,braces,commas,andsemicolons.
Considerthefollowingcode:
voidmain(void)
voidmain(void)
{
inta,b=2,c=3;
a=(b*(b+c));
}
Theparenthesisusedrightaftermainareusedasanoperator.Byrules,theyareusedtoindicatethatmainisafunction.Aftertheparenthesis,thesymbols“{”,“,”,“,”,“;”,“(”,“(”,“)”,“)”and“;”areallpunctuators.Bothoperatorsandpunctuatorsarecollectedbythecompilerastokens(characters),andalongwithwhitespace,theyservetoseparatelanguageelementslikeidentifiers,constants,functions,keywords,operatorsandothers.
Tokensdependontheircontextalot.Forexample,asexplainedinthepreviousparagraph,theparenthesesaresometimesusedtoindicateafunctionnamewhiletheycanbeusedaspunctuatorsaswell.AnotherexampleisgivenbytheexpressionsC=a+b;
++a;
a+=b;
Theyalluse+asacharacter,but++and+=areincrementandassignmentoperatorsrespectivelywhilethefirstoneisasimplearithmeticoperator.ThisdependencyofsymbolsmeaningoncontextleadstotheshortbutmoreeffectiveprogramminglanguageC.
Clanguagehasrulesofprecedenceandassociativityinoperators.Itiscriticalinnatureaswedonotwantonestatementtoresultintwodifferentoutputs.Theserulesdonotfullydetermineevaluationbecausewegiveuserthepowertoachievetheresultofdesirebymasteringtheserules.Sinceexpressionsinsideparenthesisareevaluatedfirst,parenthesescanbeusedtoclarifyorchangetheorderoperationsareperformed.
Considertheexpression:
Answer=30+(4*10/5-20);
Theoperator“(”hasthehighestparenthesisinthisexpressionsowedissectitbeforeanythingelse.Thenwehavethreeoperatorsinsideparenthesis.Multiplicationanddivisionhaveequalprecedencesoweperformwhatevercomesfirstintheexpression.Inthiscase,weperform4*10andhavearesultof40.Wedivide40by5andresultis8.
Wesubtract20from8andtheresultis-12.Nowthatparenthesisareclosed,wecomputetheoperationsoutsideit.Weadd-12to30andtheresultis18.
Humanswithgoodmathematicswillalwaysfindtheanswertobe18.Butguys,whoarenotfamiliarwithDMASrulewillhavedifferentanswers.Wewantourcomputertobegoodwithmathematics,sowehavemadeitfamiliarwiththeprecedenceofoperatorsinthestandardwaysoitalwaysleadstoonecorrectanswer.
LetusnowdiscussvarioustypesofoperatorsprovidedbylanguageC:2.6.1ArithmeticandBitwiseOperators
OperatorName
Operations
+
Add
Usedtoaddtwonumbers
-
Subtract
Usedtosubtracttwonumbers
*
Multiply
Multiply
Usedtomultiplytwonumbers
/
Divide
Usedfordivisionoftwonumbers
%
Modulus
Usedtofindremainderafterdivisionof2numbers~
Negation
Binaryoperator,usedtoinvertthebooleanvalue&
BitwiseANDUsedtoperformlogicalANDoneverybit|
BitwiseOR
UsedtoperformlogicalORoneverybit^
Power
Usedtocomputepowerofanumber
<<
LeftShift
Usedtoshiftbitstotheleft
>>
RightShift
Usedtoshiftbitstothetight
Letusnowseeanexampleofusingtheseoperatorsinaprogram:#include
Letusnowseeanexampleofusingtheseoperatorsinaprogram:#include"iostream"
voidmain(void)
{
intA=50,B=17;
boolAlive=false;
printf("ThisisaProgramtodemonstrateuseofArithmeticOperatorsinC\n");
printf("Sum:%d\n",A+B);
printf("Difference:%d\n",A-B);
printf("Product:%d\n",A*B);
printf("Division:%d\n",A/B);
printf("Modulus:%d\n",A%B);
printf("Negation:%s\n",~Alive?"true":"false");
printf("BitwiseAND:%d\n",A&B);
printf("BitwiseOR:%d\n",A|B);
printf("BitwiseXOR:%d\n",A^B);
printf("LeftShift:%d\n",A<<2);
printf("RightShift:%d\n",A>>2);
system("pause");
}
Thefirstfouroperatorsareprettycommonandstraightforwardsowe’llnotdiscussthemhere.Modulusreturnsustheremainderafterdividingonenumberbytheother.A%BreturnstheremainderafterdividingAbyB.Forinstance,theexampleinourcodedivides50by17,2isquotientwhile16istheremainder.Theremainderisreturnedandprinted.Remember,wecanalwaysassignthisvaluebyusingassignmentoperators.
Here,wejustusedthereturnedvaluetobeprintedonce.
Negationoperatorisusedtoinvertabinarynumberusing2’scomplementform.Iftheinputisboolean,asisinourprogram,theresultisinverted.
Thenwehave5Bitwiseoperators,startingwithBitwiseANDoperation.ItperformslogicalANDoneachbitofthenumbersprovided.Forexample,inourprogram,wehave50and17.Thebinaryconversionsofthesetwonumberswillbe00110010and00010001respectively.
00110010
00010001
00010000
Theanswer,afterconvertingtodecimalis16.
Similarly,BitwiseORoperationperformsORoneverybitofthenumbersprovided.Forexample,inourprogram50and17areoperatedandresultin51asexplainedasfollows.
00110010
00010001
00110001
Similarly,BitwiseXORoperationperformsXORoneverybitofthenumbersprovided.
InXOR,theresultishighbitonlyifthereareoddnumberofhighbitsintheoperation.
Forexample,inourprogram50and17areoperatedandresultin51asexplainedasfollows.
00110010
00010001
00100011
Theresult,whenconvertedintodecimalgivesus35.
Shiftoperatorsareusedtoshiftbinarydigitstotheleftorright.Byusingleftshiftoperators,theleftoperandsvalueismovedleftbythenumberofbitsspecifiedbytherightoperand.Forexample,inourprogramweusedA<<2.ItmeansthatbitsinAmustbeshiftedtoleftbytwodigits:
meansthatbitsinAmustbeshiftedtoleftbytwodigits:
00110010
00110010<<2
11001000
LeftShiftoperatorshiftsbitstotheleftandadd2zerostotherightandhencethevalueischangedto200asclearfromaboveexplanation.
Byusingrightshiftoperators,theleftoperandsvalueismovedrightbythenumberofbitsspecifiedbytherightoperand.Forexample,inourprogramweusedA>>2.ItmeansthatbitsinAmustbeshiftedtorightbytwodigits:00110010
00110010>>2
00001100
RightShiftoperatorshiftsbitstotherightandadd2zerostotheleftandhencethevalueischangedto12asclearfromaboveexplanation.
2.6.2AssignmentOperatorsOperatorEquivalentOperationsa=b
Equalto
Assignsthevaluestoredinbtoa
a+=b
a=a+b
Addsbintoaandstoresresultinaa-=b
a=a-b
Subtractsbfromaandstoresresultinaa*=b
a=a*b
Storesproductofaandbina
Storesproductofaandbina
a/=b
a=a/b
Dividesabbandstoresresultinaa%=b
a=a%b
Takesa%bandstorestheresultinaa&=b
a=a&b
PerformsbitwiseANDonaandb,storesinaa|=b
a=a|b
PerformsbitwiseORonaandb,storesinaa^=b
a=a^b
PerformsbitwiseXORonaandb,storesinaHere’saprogramtoshowtheuseoftheseassignmentoperatorswithoutput:#include"iostream"
voidmain(void)
{
intA=10,B=3,simpleAssignment=0;
simpleAssignment=A+B;
printf("ThisisaProgramtodemonstrateuseofAssignmentOperatorsinC\n");
printf("Simpleassignment:%d\n",simpleAssignment);
A+=B;
printf("PlusandEqualto:%d\n",A);
A=10,B=3;
A-=B;
printf("MinusandEqualto:%d\n",A);
A=10,B=3;
A*=B;
printf("MultiplyandEqualto:%d\n",A);
A=10,B=3;
A/=B;
printf("Modulusandequalto:%d\n",A);
A=10,B=3;
A%=B;
printf("BitwiseANDandequalto:%d\n",A);
A=10,B=3;
A&=B;
printf("BitwiseORandequalto:%d\n",A);
A=10,B=3;
A|=B;
printf("BitwiseXORandequalto:%d\n",A);
system("pause");
}
2.6.3IncrementDecrementOperatorsOperatorName
Operations
++a
Prefixincrement
Adds1tothevalueofa,beforeanyassignment--a
Prefixdecrement
Subtracts1tothevalueofa,beforeanyassignmenta++
PostfixincrementAdds1tothevalueofa,afteranyassignmenta--
PostfixdecrementSubtracts1tothevalueofa,afteranyassignment
Theincrementoperator++andthedecrementoperator--areunaryoperators.++and-
-canbeappliedtoidentifiers,butnottoconstantsorordinaryexpressions.Moreover,differenteffectsmayoccurdependingonwhethertheoperatorsoccurinprefixorpostfixposition.
Clearly,Incrementanddecrementoperatorscanbetrickytoworkwith.Insimplesituations,onecanconsider++and--asoperatorsthatprovideconcisenotationfortheincrementinganddecrementingofavariable.Inothersituations,carefulattentionmustbepaidastowhetherprefixorpostfixpositionisdesired.Theyareprettysimpleonceyouknowthepurposeanduseofeachandthebestwaytomakeyoufamiliarwithpurposeofeachoftheseoperatorsisthepractical.Sohereisaprogramwhichdescribesusageoftheseoperators:
#include"iostream"
voidmain(void)
{
intA=10;
printf("ThisisaProgramtodemonstrateuseofIncrementDecrementOperatorsinC\n");
printf("BeforePrefixIncrement,A=%d\n",A);
printf("PrefixIncrement,A=%d\n",++A);
printf("AfterPrefixIncrement,A=%d\n",A);
printf("BeforePostfixIncrement,A=%d\n",A);
printf("PostfixIncrement,A=%d\n",A++);
printf("AfterPostfixIncrement,A=%d\n",A);
printf("BeforePrefixDecrement,A=%d\n",A);
printf("PrefixDecrement,A=%d\n",--A);
printf("AfterPrefixDecrement,A=%d\n",A);
printf("BeforePostfixDecrement,A=%d\n",A);
printf("PostfixDecrement,A=%d\n",A--);
printf("AfterPostfixDecrement,A=%d\n",A);
system("pause");
}
So,theinitialvalueofAis10.Prefixincrementincrementsthevalueto11
So,theinitialvalueofAis10.Prefixincrementincrementsthevalueto11beforeassignmentsandthusprints11in3rdlineofoutput.FourthlinejustprintsandshowsthatAhasbeenassignedthevalue11.SixthlineofoutputhasapostfixincrementwhichmeansAwillbeincrementedafteranyassignmentsintheexpression.Thus,thesamevalue,11isprintedandthenAisincrementedto12whichcanbeseeninthenextline.
Prefixdecrementdecrementsthevalueto11beforeassignmentsandthusprints11in9thlineofoutput.NextlinejustprintsandshowsthatAhasbeenassignedthevalue11.
12thlineofoutputhasapostfixdecrementwhichmeansAwillbedecrementedafteranyassignmentsintheexpression.Thus,thesamevalue,11isprintedandthenAisdecrementedto10whichcanbeseeninthenextline.
2.6.4LogicalOperatorsLogicaloperatorsareusedtogetabinaryoutputdependinguponcertainoperationsbetweenoneormoreoperands.Theyarehandywhendevelopingdecisionstatements.
OperatorName
Operations
!a
Negative
Invertsthevalueofa
a&&b
LogicalANDReturnstrueifbotha,baretruea||b
LogicalOR
ReturnstrueifaorborbotharetrueFollowingisanexampleillustratingtheuseoftheselogicaloperators:#include"iostream"
voidmain(void)
{
boolA=true,B=false,C=true;
printf(!A?"True\n":"False\n");
printf((A&&B)?"True\n":"False\n");
printf((A&&C)?"True\n":"False\n");
printf((A||B)?"True\n":"False\n");
system("pause");
}
2.6.5ComparisonOperatorsThecomparisonoperatorsareusedtocomparetwonumbersorcharacters.Forbinaryandstringcomparisons,wehaveseparateoperatorsandfunctionssoavoidcomparingtwostringsorbinarynumbersusingtheseoperators.Itisnotrecommended.
OperatorName
Operations
a==b
Equals
Returnstrueifcontentsofaequaltothatofba!=b
a<b
Notequalto
Returnstrueifaisnotequaltothatofba>b
a<=b
Lessthan
Returnstrueifaislessthanb
a>=b
Greaterthan
Returnstrueifaisgreaterthanb
Lessthanorequalto
ReturnstrueifaislessthanorequaltobGreaterthanorequaltoReturnstrueifaisgreaterthanorequaltob
FollowingisanillustrationofusageofComparisonoperatorsinCwithoutput.
#include"iostream"
voidmain(void)
{
inta=10,b=5;
printf((a==b)?"True\n":"False\n");
printf((a==b)?"True\n":"False\n");
printf((a!=b)?"True\n":"False\n");
printf((a<b)?"True\n":"False\n");
printf((a>b)?"True\n":"False\n");
printf((a<=b)?"True\n":"False\n");
printf((a>=b)?"True\n":"False\n");
system("pause");
}
Theoutputisprettystraightforward,sowetrusttheaudienceforunderstanding.
2.6.6SpecialOperators
Theternaryoperator,theonewehaveconsistentlyusedinpreviousexamplesisquiteuseful.Itssyntaxisasfollows:
Condition?(Incaseoftrue):(Incaseoffalse)
So,ternaryoperatorchecksacertainconditionanddependinguponthebooleanoutput,selectsoneofthealternativecases.
Anotherusefuloperatoristypecastingoperator.Ittakesanoperandandconvertsitintothedesireddatatype.Itssyntaxisasfollows:(Type)operand;
Forexample,(int)3.14yields3.
Cprovidestheunaryoperatorsizeoftofindthenumberofbytesneededtostoreanobject.Ithasthesameprecedenceandassociativityasalltheotherunaryoperators.Thesyntaxofexpressionisasfollows:
sizeof(object)
2.7PrecedenceandAssociativityAswediscussedearlieraswell,wehaverulesofprecedenceandassociativitythatareusedtodeterminehowcertainexpressionsareevaluated.LetusbrieflydiscusshowprecedencerulesareusedbyaCcompilertocomputetheuniqueandcorrectanswerofanexpression.
ThefollowingisatablerepresentingtheprecedenceofoperatorsinC.Theoperatorsatthetophavehighestprecedencewhiletheoperatorsatbottomhavetheleastprecedenceinanexpression.Theoperatorswithhigherprecedencearecomputedfirstinanexpression.
Category
Operator
Associativity
Postfix
()[]->.++--
Lefttoright
Unary
+-!~++--(type)*&sizeof
Righttoleft
Multiplicative*/%
Lefttoright
Additive
+-
Lefttoright
Shift
<<>>
Lefttoright
Relational
<<=>>=
Lefttoright
Equality
==!=
Lefttoright
BitwiseAND
&
Lefttoright
BitwiseXOR
^
Lefttoright
BitwiseOR
|
Lefttoright
LogicalAND
&&
Lefttoright
LogicalOR
LogicalOR
||
Lefttoright
Conditional
?:
Righttoleft
Assignment
=+=-=*=/=%=>>=<<=&=^=|=
Righttoleft
Comma
,
Lefttoright
Considerthefollowingcodeandtrytocomputetheresults.Wewilldiscusstheoutputbutitisbetterifyoutryityourselfbeforematchingourresults.
#include"iostream"
voidmain(void)
{
inta=20,b=10,c=5;
a=b=c+=2;
printf("a=%d\n",a);
printf("b=%d\n",b);
printf("c=%d\n",c);
a=20,b=10,c=5;
a=++b-=c=2;
printf("a=%d\n",a);
printf("b=%d\n",b);
printf("b=%d\n",c);
system("pause");
}
Theinitialvaluesofa,bandcare20,10and5respectively.Theequivalentexpressionforthefirstexpressioncanbe:(a=(b=(c=c+2)));Theinnermostparenthesesassignsthevalue5toc.Theothertwoparenthesissimplyassignctobandbtoa.So,allthevariablescontain7aftertheexecutionoffirst
assignctobandbtoa.So,allthevariablescontain7aftertheexecutionoffirstassignment.
Then,wereinitializevaluesofa,bandcwith20,10and5respectively.Theequivalentexpressionforthesecondassignmentwouldbe:
(a=((b=b+1)=b-(c=2)));
Theinnermostparenthesisstores2invariablec.Thenextparenthesisthencomputeb-c,equivalentto10-2,andresults8whichisstoredinb.Thenbisincrementedby1
whichgivesbthevalue9.Thenaisassignedthevalueofb,whichis9.
Alltheoperatorsonagivenline,suchas*/%haveequalprecedencewithrespecttoeachother,buthavehigherprecedencethanalltheoperatorsthatoccuronthelinesbelowthem.Wehaveassociativityforalltheoperatorsintherightmostcolumn.Foreveryoperator,wewilldeclareitsprecedenceandassociativitysothatthereisastandardtocomputeamathematicalexpression.TheserulesaretoberememberedbyeveryCprogrammerforefficientprogramming.
IntraditionalC,theincrementanddecrementoperatorshavethesameprecedenceastheunaryoperators.InANSIC,howevertheyhavetheveryhighestpre-andleft-to-rightassociativityaspostfixoperators,andtheyhavethesamepre-astheotherunaryoperatorsandright-to-Leftassociativityasprefixoperators.
Chapter3:DataTypes
Datatypesrefertovariouscategoriesofdatathatistobemanipulated.Cprovidesseveraldefaultdatatypes.Weneedtodiscusslimitationsonwhatcanbestoredineachtype.
Thekeywordssignedchar,unsignedchar,char,signedlongint,signedshortint,signedint,unsignedint,unsignedshortint,unsignedlongint,float,double,andlongdoublearethedefaultdatatypesbutforprogrammers’ease,itisallowedtousetheshortforms.
ThenextparagraphhasthoselegalshortenedformsofdatatypesinC.
Fundamentaldatatypesincludelong,short,signedchar,unsignedchar,char,int,float,double,longdouble,unsigned,unsignedshortandunsignedlong.
Theseareallkeywordswhichmeansthattheycannotbeusedasnamesofvariables.
Usually,thekeywordsignedisnotused.Thereasonisthatthesignedintisequivalentofint,andbecauseshorternamesareeasiertotype,intisusedonmostoftheoccasions.
Thetypechar,however,isspecialinthisregardaswe’llseeinthelaterpartsofthis
chapter
Letusassumethatthecategorytypeisdefinedtobeanyoneofthetypesgivenintheprecedingparagraph.Usingthiscategory,wecanprovidethesyntaxofdeclaringavariableofanytype:
typeidentifier;
Forexample,thiscanrepresentintxordoubleaorcharalphabetetc.
Itisalwayseasytounderstandthingswhentheyaregrouped(exceptcats).Thedefaultdatatypescanalsobegroupedaccordingtotheirfunctionality.Theintegraltypescanbeusedtoholdintegervalues;thefloatinganddoubletypesarethosethatbeusedtoholdrealvaluesinthem.Thesebothcategories,whencombinedformArithmeticdatatypes.
IntegralDataTypesFloatingPointDataTypeschar
float
signedchar
double
unsignedchar
longdouble
short
int
long
unsignedshort
unsigned
unsignedlong
3.1IntegralDataTypesThedatatypeint,theshortforintegeristhemostusedintegraldatatypeinC.Thistype,alongtheotherintegraltypessuchaschar,short,andlong,isdesignedforworkingtheintegervaluesthatarerepresentableonamachine.Mathematicsdefineintegersaspositiveandnegativewholenumberssuchas-11,13,66etc.
Sincemachinesaredesignedwithinbounds,wecanhaveintegersuptoacertainlimit.
Typically,anintegerisstoredineither16bitsorin32bits.Thereareotherpossibilities,butthisiswhathappensinmostCsystems.OnolderPCs,anintegeristypicallystoredin16bitswhilenewerPCs,workstationsandmainframessupport32bitintegers.
Tocalculatetherangeweusethepowerrule.Ona16bitsystem,wecanhave2^16=
65536distinctvalues,halfofwhichwouldbenegativeifwearedealingwithsignednumbers.Similarlyona32bitsystem,wecanhave2^32=4294967296distinctvalues,halfofwhicharenegativeifwearedealingwithsignednumbers.
InC,thedatatypeintegerisconsideredthe"natural"or"usual"typeforworkingwithinteger.Thereareotherintegraltypessuchaschar,short,andlong.Thedatatypeshort,forexample,canbeusedinsituationswhereweneedtouselessnumberofbytestostoreourinteger,althoughitisnotrequiredtodosointoday’sadvancedworldaswedonothaveanystorageissuesnowadays.Inasimilarfashion,thetypelongmightbeinsituationswherelargeintegervaluesareneeded.Thecompilermayprovidestoragegreaterthanitisrequiredforanaturalinteger.Typically,shortisstoredin2bytesandalongisstoredin4bytes.Machineswith4bytesystemshaveequalsizedshortandlongdatatypes.
3.2FloatingPointDataTypesCprovidesthethreefloatingtypes:float,double,andlongdouble.Floatingpointvariablesareusedtostorerealvalueslike3.14,1.33334etc.Asuffixcanbeaddedtoafloatingconstanttospecifyitstype.Anyfloatingconstantwithoutsuffixisoftypedouble.TheworkingfloatingtypeforCisdoubleratherthanfloat.
Integerscanbeusedasfloatingconstants,buttheymustbewrittenwithadecimalpoint.Forexample,theconstants1.0and2.0arebothoftypedouble,whereasasintegers,theirvaluewillbe1and2respectively.
Thereisanothernotationtorepresentfloatingpointnumbersaswellwhichinvolvesexponent.Forexample,thenumber1.234567e-3callsforshiftingthedecimalpointthreetothelefttoobtaintheequivalentconstant0.001234567.Thisbecomeshandywhenyouhavetodealwithanumberofzerostostartrightafterdecimalpoint.Itiseasytorememberafloatingtypenumberlikethis.
Afloatingtypenumberconsistsoffourparts:anintegerpart,adecimalpoint,afractionalpart,andanexponentialpart(ifany).Afloatingtypenumbermustcontaineitheradecimalpointoranexponentialpartorboth.Ifadecimalpointispresent,eitheranintegerpartorfractionalpartorbothmustbepresent.Ifnodecimalpointispresent,thentheremustbeanintegerpartalongwithanexponentialparttoindicatethepossiblepositionofdecimalpoint.
Someexamplesoffloatingconstantsare3.14159,314.15ge-2,1333e-3etc.
3.3Using“typedef”
TheClanguageprovidestheprogrammertodefineadatatypeusingexistingdatatypesbutwithhisowncustomizednames.Thisisachievedthroughtypedefmechanism,whichallowstheprogrammertouseanidentifierofhischoicetorepresentcertaindatatypes.Someexamplesare
typedefintnumberOfStudents;
typedefdoublepercentage;
typedefshortintage;
Ineachofthesetypedefinitions,thenamedidentifierscanbeusedlatertodeclarevariablesorfunctionsinthesamewayordinarytypescanbeused.
numberOfStudentsStrength;
TheabovestatementdeclaresthevariableStrengthtobeoftype
TheabovestatementdeclaresthevariableStrengthtobeoftypenumberOfStudents,whichissynonymouswithintegerasperourdefinition.
Theadvantageofusingtypedefforcustomizeddatatypesisinabbreviatinglongdeclarations.AnotheradvantageishavingnamesthatreflecttheintendeduselikenumberOfStudents.
3.4StorageClassesVariablesandfunctionsinChavetwoattributes:typeandstorageclass.Youmusthavegatheredaroundthefirstattributesofar.Letusnowdiscussthestorageclassattribute.
Thestorageclassesareusedforcertainutilitiesofvariablesandfunctions.Themostcommonstorageclassisauto.Therearethreeotherstorageclassesdefinedbythesekeywords:
auto
extern
register
static
3.4.1TheStorageClassautoBydefault,Cvariablesdeclaredwithinfunctiondefinitionsareautomatic.Thus,automaticisthemostusedofthefourstorageclasses.Ifacompoundstatementstartswithabledeclarations,thenthesevariablescanbeactedonwithinthescopeofthe
enclosingcompoundstatement.Fordifferencebetweencompoundstatementsstartingwithdeclarationsandthosewhichdonotstartwithvariabledeclarations,weuseblockterminology.Ablockisacompoundstatementwithdeclarations.
Declarationswithinablockareautomaticallyofstorageclassauto.Wedon’tneedtoexplicitlystateautoforthesevariables.Thekeywordautoisrarelyused.Whentheprogramcontrolentersablock,thesystemallocatesmemoryforalltheautomaticvariablesenclosedintheblock.Thevariablesare“local”innature
theautomaticvariablesenclosedintheblock.Thevariablesare“local”innaturewithinthatblock.
Whentheprogramcontrolexitsablock,thesystemreleasesthememorythatwassetasidefortheautomaticvariables.Assoonastheblocksaregone,gonearethevariables.
Thatiswhythesevariablesarecalledlocal.
3.4.2StorageClassexternThecommunicationbetweenblocksiscritical.Onewayoftransmittinginformationacrossyourscopeisusingmethodstopassparameterstoanotherscope.But,thismethodisnotapplicableincertainsituations.Thestorageclassexternprovidesuswithanothermechanismforcommunicationbetweendifferentenvironmentsorscopes.
Declarationforavariableofexternclassisverysimilarnormalvariabledeclarationexceptthatvariablesaredeclaredoutsideanyblock.Thesevariablesactasglobalforallthefunctionswrittenaftertheirdeclaration.Anexamplefollowsforbetterunderstanding:
intglobalVariable=10;
voidprintMe()
{
printf("ValueofgloabalVariable=%d\n",globalVariable);}
voidmain(void)
{
printf("ValueofgloabalVariable=%d\n",globalVariable);
globalVariable+=10;
printMe();
}
NotethatwecouldhavewrittenthefollowingstatementastraditionalCdidnotallowitbutmodernANSIcompilersdonotcomplainaboutthisformatandalsoconsideravariableoutsideanyscopeofexternclassevenifexternkeywordisnotused:externintglobalVariable=10;
Suchvariablescannotbeofautomaticorregisterclassbuttheycanbestaticifrequiredasexplainedinstorageclassstaticsection.Thekeywordexternisusedtomakecompilerlookforthisvariableanywhereinthisfileorinanyotherfilefordefinitionanduse.
Anotherimportantpointtorememberisthatexternalvariablesarenotde-allocatedentirelythroughtheprogrambutthemaybehiddenifasimilaridentifierisredefinedinsideascope.Ifthishappens,thelocalvariableisaccessed,nottheglobalvariableinthatscope.
Aswementionedinthestart,Informationcanbepassedintoafunctiontwoways:byuseofexternalvariablesanduseoftheparametermechanism.Althoughthereareexceptions,itispreferredtousethesecondmethodforthispurposebecauseitleadstobettermodularityandconcisenessofcode.Usingexternalvariablescarelesslymayoftenresultinsurprisesandmagic.Globalvariablescascadetheirchangethroughouttheprogram,whichclearlycanbeharmfulforyourlogic.Themessageorparameterpassingtechniqueisfreefromthesehazardssincechangesarelocalized.Programsaretherefore,easiertowriteandmaintain.Allfunctionshaveexternalstorageclass.Thismeansthatwecanusethekeywordexterninfunctiondefinitionsandinfunctionprototypes.Forexample:
externdoublesum(doublea,doubleb);3.4.3StorageClassregisterTheregisterstorageclassmakesvariablestoworkashighspeedregister.Obviously,itmighthavehardwarebasedrestrictionssincetherearealimitednumberofregistersinphysicalspace.Becauseofphysicalrestrictions,variablesofthisclassareautomaticallyconvertedtoautotypewhenevercompilerfindsitimpossibletousethevariableasamemoryregister.
Registerclassisusedwhenfastexecutioniscritical.Whenspeedisaconcern,theprogrammermaychooseafewvariablesthatarefrequentlyaccessedanddeclarethemtobeofstorageclassregister.Registerstakelessernumberofclockcycleswhentheyareaccessedforuseormodificationthannormalmemory
cycleswhentheyareaccessedforuseormodificationthannormalmemorylocation.Sinceregistersstoreintegervalues,henceexternvariablesareintegerbydefaultaswell.Thereforefollowingtwodeclarationsareequivalent:externintvariable;
externvariable;
3.4.4StorageClassstaticStaticmeanssomethingwhichkeepsitsstateconstant.Staticclasshavetwobasicuses.
Theprimaryuseissimilartowhatthewordstaticmeans:fordeclaringvariableswhichretaintheirstatewhenblocksareenteredandexitedfrequently.Remember,normalvariablesarede-allocatedassoonastheblockisclosed.Theseconduseisitsusewithexternalclassdeclarations.
Hereisanexample:
voiddemo()
{
intnormalVariable=5;
staticintstaticVariable=5;
normalVariable+=10;
staticVariable+=10;
staticVariable+=10;
printf("Normal:%d\n",normalVariable);
printf("Static:%d\n",staticVariable);}
voidmain(void)
{
demo();
demo();
demo();
system("pause");
}
Asyoucanseeintheoutputofaboveprogram,staticvariableretainsitspreviousvalueforsecondandthirdfunctioncallaswell.Thestaticdeclarationofvariableisexecutedonlythefirsttimefunctioniscalled.Afterthat,thecompilerignoresit.Thenexttime,staticvariablehasvalue15and10isaddedintoitand25isprinted.Thethirdfunctioncallusestheretainedvalue25forstaticvariableandadds10toit.Ontheotherhand,normalvariableisinitializedagainandagainto5and10isadded.Eachofthethreefunctioncallscreatesanormalvariableofitsownwhilestaticvariableisonlygeneratedthefirsttimeandthenretainedforfuturereferences.
Letusnowdiscussthestaticexternalvariables.Externandstatictogetherprovidebetterprivacyoptionstotheprogrammer.Asyouknowthatglobalorexternalvariablesareaccessibleonlytothefunctionsdefinedaftertheirdeclaration.Thestaticvariableson
declaration.Thestaticvariableson
theotherhandaredependentontheirblocksthatcanbemoldedforusebyprogrammers.
Letususethisfacilitytoprovideavariablethatisglobaltoafamilyoffunctionsbut,atthesametime,isprivatetothefile.
Anotheruseofstaticisasastorageclasstospecifyfunctiondefinitionsandprototypes.
Thisusecausesthescopeofthefunctiontoberestricted.Staticfunctionsarevisibleonlywithinthefileinwhichtheyaredefined.Unlikeordinaryfunctions,whichcanbeaccessedfromotherfiles,astaticfunctionisavailablethroughoutitsownfile,butnoother.
3.5DefaultInitializationsInC,bothexternalvariablesandstaticvariablesthatarenotassignedanyvaluesatthetimeofdeclarationareautomaticallyinitializedwith0.Thisdefaultinitializationisapplicableonarrays,strings,pointers,structuresandunion.
Incontrasttothis,automaticandregistervariablesarenotautomaticallyinitializedbythesystem.Thismeanscompilereithergeneratesanerrororusesagarbagevalueifyouaccessanautomaticvariableorregistervariablewithoutinitializingit.
Chapter4:Loops&Decisions
Loopsrefertoprogrammingtoolsforrepetitiveexecution.Thisisextremelyusefulasitallowsprogrammertowritecodesthatareconcise.Forexample,
usefulasitallowsprogrammertowritecodesthatareconcise.Forexample,considerthatwewanttoprintastatementathousandtimes.Insteadofwritingthestatementathousandtimes,wecanjustprogramaloop.Sucharethebenefitsofusingaloop.
Csupportsallthebasicloopsprovidedbyotherhighlevellanguages.Theseincludeforloop,whileloopanddowhileloop.Wewilldiscusseachoftheseloopswithexampleinthischapter.
Computerworksonlogicdesignedbyhumansandisfedtoitbyprogrammersusingprogramminglanguages.Logicisbasedupondecisions.Decisionstatementsarerequiredfordefiningthesedecisions.Wewilldiscusstwotypesofdecisionstatementsinthischapter.
4.1IfelsestatementThemostbasicandmostcommonlyuseddecisionstatementinanyprogramminglanguageisifelsestatement.Thisstatementcanbeusedformultiplescenarios.Itcanbeusedforoneoranynumberofscenarios.Here’saprogramonlywithoneifstatement:
voidmain(void)
{
printf("Programstarts\n");
intx=0;
printf("Enteranumberandpressenter:");
scanf("%d",&x);
if(x==0)
{
printf("Ifexecutes\n");
printf("Ifexecutes\n");
}
printf("Programends\n");
system("pause");
}
Thisprogramtakesanintegralinputfromuserusingscanffunction.Iftheuserenters0,thenthelogicaloperationinifstatementholdstrueandthereforethebodyofifstatementisexecuted.Ifanyothernumberisentered,thebodyofifstatementisnotexecuted.
Letusnowseeanotherexamplewhichinvolvesifelsestatement:voidmain(void)
{
printf("Programstarts\n");
intx=0;
printf("Enteranumberandpressenter:");
scanf("%d",&x);
if(x==0)
{
printf("Ifexecutes\n");
}
}
else
{
printf("Elseexecutes\n");
}
printf("Programends\n");
system("pause");
}
Thisprogramhasanalternateconditionintheblockcoveredbyelsestatement.Elsestatementisalwaysusedwithifstatement.Inthecase,whenifstatementholdstrue,thecompilerjustignorestheelsestatement.Otherwise,whenifstatementisfalse,thebodyofelseblockisexecuted.
Followingisanexampleinvolvingmultipleifelsestatements:voidmain(void)
{
printf("Programstarts\n");
intx=0;
printf("Enteranumberandpressenter:");
scanf("%d",&x);
if(x==0)
if(x==0)
{
printf("1stIfexecutes\n");
}
elseif(x<10)
{
printf("2ndIfexecutes\n");
}
elseif(x<20)
{
printf("3rdIfexecutes\n");
}
else
{
printf("Elseexecutes\n");
}
printf("Programends\n");
system("pause");
}
4.2SwitchCasestatementSwitchcaseisanotherpopulardecisionmakingstatementinCprogramminglanguage.
TheuseisverysimilartoifelsestatementsbutinsteadofconditionswhichresultinBooleanvalues,thisdecisionmakingstatementhascertaincasesfordifferentvalues.
Letusseeanexampleforbetterunderstanding:
voidmain(void)
{
printf("Programstarts\n");
charx;
printf("Enterasmallalphabetandpressenter:");
x=getchar();
switch(x)
{
case'a':printf("Youentereda..!\n");break;
case'b':printf("Youenteredb..!\n");break;
case'c':printf("Youenteredc..!\n");break;
case'd':printf("Youenteredd..!\n");break;
default:printf("Youenteredsomethingelse..!\n");
}
printf("Programends\n");
system("pause");
}
Basedoninputfromuserwhichispassedasanargumentinswitchstatement,theprogramexecutesaparticularcase.Ifitcannotfindanycase,thedefaultcaseisexecuted.
Animportantthingtonoteisthebreakstatementattheendofeachcase.Breakstatementisusedtoleavethecurrentblockinanysituation.Forexample,ifyouareinforloop,youwillignorethecodeinsideforloopafterthebreakstatement.Here,breakstatementisnecessaryifwedonotwantmultiplecasestobeassociatedwithoneinput.
Forexample,seethefollowingprogram:voidmain(void)
{
printf("Programstarts\n");
charx;
printf("Enterasmallalphabetandpressenter:");
x=getchar();
switch(x)
{
case'a':printf("Youentereda..!\n");break;
case'b':printf("Youenteredb..!\n");
case'c':printf("Youenteredc..!\n");break;
case'd':printf("Youenteredd..!\n");break;
default:printf("Youenteredsomethingelse..!\n");
}
printf("Programends\n");
system("pause");
}
Intheaboveprogram,ifuserenterscharacterbasinput,twocasesareexecuted.Startingfromcase‘b’,compilerexecuteseverylineofcodeunlessitreachesabreakstatementorendofswitchcaseblock.
4.3ForLoopAswedescribedearlier,loopsareusedforrepetitiveexecutionofstatements.Whenweknowthenumberofiterations,forloopistheideallooptouseinaprogram.
Thegeneralformatisasfollows:for(initializationexpression;checkcondition;increment/decrement){…}
increment/decrement){…}
Hereisanexamplewhichusesforloop:voidmain(void)
{
printf("Programstarts\n");
charx;
for(inti=0;i<5;i++)
{
printf("Enterasmallalphabetandpressenter:");
x=getchar();
switch(x)
{
case'a':printf("Youentereda..!\n");break;
case'b':printf("Youenteredb..!\n");break;
case'c':printf("Youenteredc..!\n");break;
case'd':printf("Youenteredd..!\n");break;
default:printf("Youenteredsomethingelse..!\n");
}
}
printf("Programends\n");
system("pause");
}
Theaboveprogramexecutesthestatementswithinforloopfivetimes.Whencompilerreachesforloop,itfirstofallinitializesthevariableinvolved.Afterthat,conditionischecked.Ifconditionistrue,keepgoingelsestop.So,inthefirstexecutioncycle,Iisinitializedto0andconditionistrueas0islessthan5.Afterfirstexecutioncycle,incrementordecrementstatementattheendofforloopisexecutedandconditionischecked.Now,incrementoperatorgivesIthevalueof1,whichisagainlessthan5soloopkeepsgoing.Similarly,loopgoesonforthreemorecycles.Afteratotaloffivecycles,valueofIwillbe5.For6thpossiblecycle,valueofIiscomparedwith5andtheanswerwillbefalseas5isnotlessthan5.Hence,6thcyclewon’tbeexecutedandloopisterminated.
4.4WhileLoopThisloopusesonlyaconditiontodeterminehowmanyiterationsaretobecomputed.
Thereareno(necessary)initializationandincrementalchangeinvalueofavariable.
Therecanbeinitializationandchangeinawhileloopifitisrequiredbyprogramlogic.
Thegeneralsyntaxofwhileloopisasfollows:while(condition){….}
Hereisanillustrationforbetterunderstandingofwhileloop:voidmain(void)
{
{
printf("Programstarts\n");
charx='a';
printf("Enterasmallalphabetandpressenter:");
x=getchar();
while(x!='e')
{
switch(x)
{
case'a':printf("Youentereda..!\n");break;
case'b':printf("Youenteredb..!\n");break;
case'c':printf("Youenteredc..!\n");break;
case'd':printf("Youenteredd..!\n");break;
default:printf("Youenteredsomethingelse..!\n");
}
printf("Enteretoexit.Else,enteranothersmallalphabetandpressenter:");
x=getchar();
}
printf("Programends\n");
system("pause");
}
Thisprogramkeepsrepeatinguntiluserenters‘e’.Thus,userisgiventhecontrolofhowmanyiterationsaremadebyusingwhileloop.Thiscanbedonewithforlooptoo,butwhileisdesignedforthisparticularpurpose.Whileloopishighlyrecommendedifthenumberofiterationsrequiredareunknown.
4.5DoWhileLoopDowhileloopisalmostsimilartowhileloopexceptthatdowhilealwaysexecuteitsfirstcyclewithouttestinganycondition.Ontheotherhand,whileloopalwayschecksthattheconditiongivenistrue,evenforthefirstexecutioncycle.
Considerfollowingexampleandcompareitwiththewhileloopexample:voidmain(void)
{
printf("Programstarts\n");
charx='a';
do
{
printf("Enterasmallalphabetandpressenter:");
x=getchar();
switch(x)
{
case'a':printf("Youentereda..!\n");break;
case'b':printf("Youenteredb..!\n");break;
case'c':printf("Youenteredc..!\n");break;
case’d’:printf("Youenteredd..!\n");break;
default:printf("Youenteredsomethingelse..!\n");
}
}while(x!='e');
printf("Programends\n");
system("pause");
}
4.6NestedLoopsNestedloopsrefertoloopswithinloops.Theyareusuallyusefulwhendealingwith2-D
arrays.Hereisanexampleinwhicha2-Darrayisinitializedusinganestedforloop:voidmain(void)
{
intTwo_D[10][10];
for(inti=0;i<10;i++)
{
for(intj=0;j<10;j++)
{
Two_D[i][j]=i+j;
}
}
for(inti=0;i<10;i++)
{
for(intj=0;j<10;j++)
{
printf("%d,",Two_D[i][j]);
}
}
system("pause");
}
Similarly,wecanusenestedloopsforawhileanddowhile.Youcannestdifferentloopstogetheraswell.
Decisionstatementsandloopsprovideflexibilitytotheprogrammertodevelopaprogramaccordingtohisunderstanding.Itleadstobetterdevelopmenttechniquesandencouragesprogrammertothinkofnewsolutionsinsteadofjustfollowingalreadyestablishedsolutions.
Chapter5:Functions
Afunction,alsoknownasamethodorroutine,issimplytheprogrammingunitwhichperformsanoperationonpossibleinputsandreturns(ifrequired)theoutputs.
Afunctionisanassemblyofstatementstoperformaparticulartask.CisafunctionorientedlanguagehenceeveryCprogramisbasedononeormorefunctions.ThereisatleastonemethodinanyCprogram,calledmainfunction.Mainfunctionistheentrypointintoanyprogram.
Theconceptoffunctionscomefromtheneedtodividelargeandcomplextasksintosmallerandsimplerproblems.Itisalwayseasytomanagesmallertasks.Functionsareentirelyup-tothewillofprogrammer,butitisrecommendedthateachfunctionhasaspecificanduniquetasks.Assemblyofeveryindividualfunctionsolvesthebasicproblem.Forexample,inaCalculatorapplication,thereshouldbeafunctionforeveryoperationsothatcodinganddebuggingiseasy.
TheuseofFunctionsgiveusmanyadvantagessuchasreusability,modularity,readability,simplicityandmaintainability.
ThebasicstructuringelementofCprogramsisFunction.ThestandardClibraryitself,providesmanybuiltinfunctionssuchassqrt,absetc.Wewillseesomeofthesefunctionsinthischapter.
InC,wehavetwoterminologiesregardingFunctions.OneisFunction-DeclarationandtheotheroneisFunctionDefinition.FunctionDeclarationmeansthatthefunctionisregisteredwithcompilerwhileFunctionDefinitionactuallycontainsthebodyandfunctionalityofthefunction.
5.1FunctionDefinitionThefunctiondefinitionistheactualcodewhichisexecutedwheneverthatparticularfunctionisexecuted.
Afunctiondefinitionstartswiththetypeofoutputafunctionprovides.Ifnovalueisreturned,thenthetypeshouldbevoid.Thedefaultreturntypeisint.Ifthetypeisotherthanvoid,thenavalueofthattypeistobereturned.Ifthereisamismatchbetweentherequiredtypeandactuallyreturnedtype,someconversionsmaybenecessary.Afterthat,wehaveafunctionname.The
conversionsmaybenecessary.Afterthat,wehaveafunctionname.Theparameters,enclosedwithinparenthesis,actasalistofinputsthatcomewithafunctionwhenitiscalled.Thebodyincludesthefunctionalitycore,theactualoperationsontheinputtogenerateoutput.
Remember,Functiondeclarationissomethingdifferentwhichwewilldiscusslateron.Afunctiondefinitionhasthefollowinggeneralform:
typefunctionName(parameterlist)
{body}
Thefirstlinerepresentstheheaderofafunction.Secondlinehererepresentsthebodyofafunctionenclosedinbracesbyconvention.Theparameterlistreferstoapossiblemultipleinputs.functionNameisthenameoffunctionwhiletyperepresentstheoutputofthefunction.
Anexampleofafunctiondefinitionis:intsum(inta,intb)
{
sum=a+b;
returnsum;
}
Intheprogramabove,therearetwointegerinputswhosesumisreturnedasanoutput.
Thefirstintrepresentsthereturntype.Then“sum”isthenameoffunction.Alistofparameterspassedorinputs(bothintegertype)isenclosedinsideparenthesis.Then,thebodyisenclosedwithinbraces.Thelaststatementhasthekeyword“return”,whichisusedforreturninganoutputinspecifiedformatandalongwiththat,programcontrolalsoreturnstothepointfromwheresum(a,b)arecalled.
Thefollowingaretwowaystocalculatesumoftwonumbers.Oneinvolvesuse
Thefollowingaretwowaystocalculatesumoftwonumbers.Oneinvolvesuseoffunctionandtheotherdoesnot.Pleaseseethedifferencestounderstandtheutilityoffunctions:
1.WithoutFunction:
voidmain(void)
{
inta=20,b=10,c=5;
a=b=c+=2;
printf("a=%d\n",a);
printf("b=%d\n",b);
printf("c=%d\n",c);
a=20,b=10,c=5;
a=++b-=c=2;
printf("a=%d\n",a);
printf("b=%d\n",b);
printf("b=%d\n",c);
a=20,b=10,c=5;
printf("%d",(a=((b=b+1)=b-(c=2))));
a=20,b=10,c=5;
printf("%d",((b=b+1)=b-(c=2)));
system("pause");
}
2.WithFunction:
intsumAndPrint(inta,intb)
{
intanswer=a+b;
printf("Answer=%d\n",answer);
returnanswer;
}
voidmain(void)
{
inta=10,b=20,c=30,d=10,e=30,f=30,answer;
answer=sumAndPrint(a,b);
answer=sumAndPrint(c,d);
answer=sumAndPrint(e,f);
system("pause");
}
OneofthedifferencesbetweentraditionalCandANSICistheformatoffunctiondefinition.TraditionalCdeclaresthetypeofinputparametersaftertheparenthesisendbutidentifiersofparametersarewritteninsideparenthesis.Anexampleis
voidfunctionANSI(a,b,c,d,e)inta,b,c;doubled,e;{functionbody}
Theorderinthedeclarationofparametersdoesnotmatter.SinceANSIstandardallowsmostofthefeaturesprovidedbytraditionalC,henceCcompilernowadaysacceptbothformatsfordefinitionoffunctions.
5.1.1ThereturnstatementWhenareturnstatementisexecuted,thecurrentprogramfinishesitsexecutionandreturnstotheenvironmentfromwhichitwascalled.Ifthereturnstatementisfollowedbyanexpressionsuchas++b;ora;thenavalueisreturnedtothecallingenvironmentwhichcanbestoredandusedforfurtherprocessing.Moreover,thisvaluewillbeconverted,ifnecessary,tothetypeofthefunctionasspecifiedinthefunctiondefinition.
Afunctioncanhavezeroormorereturnstatements.Iftherearenoreturnstatementsinafunction,itcompletesitsexecutionattheendofbracesandthenreturntopreviousenvironment.Anillustrationisfollowedforbetterunderstanding:voidsumAndPrint(inta,intb)
{
intanswer=a+b;
printf("Answer=%d\n",answer);
return;
printf("AgainAnswer=%d\n",answer);}
Now,theabovefunctionprintsthesumonlyonceandreturnstopreviousenvironmentwithoutexecutingthelaststatement.Iftherewerenoreturnstatementinthecode,theanswerwouldhavebeenprintedtwice.Ofcourse,thisexamplewasjusttoillustratetheuseofreturnstatement,butyouoftencomeacrosssituationsinpracticalproblemsthatyoudon’tneedtofullyexecuteafunction.
5.2TheFunctionPrototypesFunctionprototypesrefertoFunctionDeclarations.Functionsshouldbedeclaredbeforetheyareused.ANSICprovidesforanewfunctiondeclarationsyntaxcalledthefunctionprototype.FunctionPrototypesareusuallywrittenatthetopofmainprogram.
Afunctionprototypedeclareshowafunctionistobeusedbyspecifyingthe
Afunctionprototypedeclareshowafunctionistobeusedbyspecifyingthefunctionname,inputparameterlistalongwiththeirdatatypesandthereturntype.Inputparameterlistmayormaynotcontainidentifiers.Anexampleis:intsum(int,int);
Ifsomeoneunderstandstheprototypes,hecanusethefunctioninhisprogram.Forexample,theabovefunctionprototypetellsusthatweneedtoinputtwonumbersand(mostprobably)theirsumwillbereturned.Hence,IcanwritethefollowingstatementeventhoughIhavenotwrittenthesumfunctionmyself:Answer=sum(a,b);
Functionprototypesallowthecompilertocheckthecodeinmoredetailbyspecifyingallthefunctionsthatareusedinyourprogram.Aswementionedearlier,thetypeofparametersmayneedconversion.Functionprototypesmakeiteasierforthecompilertoimplementtheseconversions.Forexample,ifwecalloursumfunctionlikethis:Answer=sum(2.5,4.3);
Ifwehaveusedprototypes,compilerknowsthatsumfunctionneedstwointegersratherthandoubleandthereforeeitherconvertstheinputparametersintointegersorgeneratesanerrorofinputtypemismatch.
5.2.1FunctionPrototypesinC++
InC++functionprototypes,theuseofvoidintheparametertypelistinbothfunctionprototypesandfunctiondefinitionsisoptional.ThisisdifferentfromtraditionalC.Forexample:
voidfunc(void);
voidfunc();
InC++,bothoftheseprototypesrepresentsamething:therearenoinputparametersbutintraditionalC,thefirstprototypeisillegalandsecondfunctionprototyperefersthattherecanbeanynumberofparametersforthisfunction.VoidisnotakeywordintraditionalCandhencecannotbeusedinfunctiondeclarationanddefinition.
5.3AlternativeStyleforDeclarationsSomeofyoumayhavenoticedthatwe
havenotusedfunctionprototypesintheprogramofsection4.1.Instead,wedefinedthefunctionsabovethemainfunction.Thisisanalternativeforprototypes,acceptablebyANSICcompilers.Wewritethepreprocessors,followedbyallthefunctiondefinitionsandthenfinallyourmainprogram.Thisisrecommended,ifyouhaveonlyonefiletoworkwith.Forexample,pleaserefertotheexamplesinsection4.1.
5.4FunctionInvocationThissectionisintendedtomakeyoufamiliarwithhowafunctioncallworks.EveryC
programisstructuredupononeormoreprograms,oneofwhichismainfunction.Mainfunctionistheentrypointinaprogramsoexecutionstartsfrommainfunction.Whenafunctioniscalledorinvoked,theprogramcontrolisshiftedfrommainprogramtothe
calledfunctionbody.Once,theexecutionofinvokedfunctioniscompleted,programcontrolisreturnedtopreviousenvironment(mainprograminthiscase).
FunctionsmustbecalledbyprovidingthevalidinputparametersasdefinedbyFunctiondeclarationanddefinition.Compilergeneratesanerrorifamismatchisfoundbetweenparameterspassedandparametersrequired.Thecompilerenforcestypecompatibilitywhenfunctionprototypesareused.
"Call-by-value"isatermassociatedwithpassedparametersinC.Itmeansthatwhenyoucallafunctionandpassitparameters,theactualparametersarenotpassedtotheotherfunction.Insteadtheirvaluesarecopiedandanothervariableiscreatedinthebodyofinvokedfunction.Thismeansthateachargumentisevaluated,anditsvalueisusedlocallyinitsownenvironment.Thus,ifavariableispassedtoafunction,thestoredvalueofthatvariableinthecallingenvironmentwillnotbechangedbecausethecallingenvironmentandcalledenvironmenthavetheirowncopyofarguments.
Followingisanexample,demonstratingtheconceptof“callbyvalue”:voidchangeValue(inta)
{
a=a+10;
printf("InsidechangeValuefunction:Valueofa=%d\n",a);}
voidmain(void)
{
inta=10;
printf("Insidemainfunction,beforechangeValueiscalled:Valueofa=%d\n",a);
changeValue(a);
printf("Insidemainfunction,beforeafterchangeValueiscalled:Valueofa=%d\n",a);
system("pause");
}
So,asyoucansee,thechangeValuefunctionadds10tothevalueofpassedparameterbutthechangeisnotvisibletothevariable“a”inmainprogram.Thechangeismade
onlytothelocalvariable,initializedbymakingacopyofvariableinmainfunctioninchangeValuefunction.
TheothercommontechniqueusedinCispassedbyreferencewhichuses
TheothercommontechniqueusedinCispassedbyreferencewhichusespointers.Wewilldiscusspointersandthismechanismindetailinoneofthefollowingchapters.
5.5Environment
Whatisanidealwaytoworkinagroup?Theidealwaytoworkinagroupistoplayanassignedolewithincertainlimitsandboundaries.Everyonehashisprivilegesandcertainlimitations.Ifeveryonepokesintoeachother’sworkwithoutnecessity,itwillleadthegrouptoadisaster.TheCstructurefollowsthesebasicprinciplesforthesuccessofeveryprogram.Aswediscussedearlier,Cprovideslocalityofvariablesinfunctions.Atthesametime,Cgivestheprogrammertochoosethescopeofavariablebyhimself.Ifaprogrammerwantssomethingtobesharedbymultiplefunctions,C
providesmultipleoptionstodoso.Forexample,useofpointersorglobalvariables.
Thebasicruleofscopingisthatvariablesareaccessibleonlywithintheblockoftheirdeclaration.Theyareunknownoutsidetheboundariesofthatblockunlessspecifiedotherwiseusingspecialtechniques.Thisisaneasyruletobefollowedbutprogrammersseemtousesameidentifiersindifferentenvironments.Forexample,seethesecondexampleinExamplessectionattheendofthischapter.Theprogrammerusedtheidentifier‘a’torepresentmultiplevariablesindifferentscope.IftherewerenorulesforScoping,thecompilercouldnothavedifferentiatedbetweentheseidentifiers.Letusseeanotherexample:
intglobalVariable=10;
voidchangeValue(inta)
{
a=a+10;
printf("InsidechangeValuefunction:ValueoflocalVariable=%d\n",a);
printf("InsidechangeValuefunction:ValueofgloabalVariable=%d\n",globalVariable);}
voidmain(void)
{
intlocalVariable=20;
changeValue(localVariable);
printf("InsidechangeValuefunction:ValueofloclVariable=%d\n",localVariable);
for(intx=1;x<=5;x++)
{
printf("%d,",x);
}
printf("\n");
printf("%d,",x);
system("pause");
}
Theaboveprogramusesfourscopes.Thefirstoneisglobalwhichmeansitcanbeaccessedanywhereandchangesmadetoitinoneplacearevisibletoeveryoneelse.Alltheothersarelocalscopeswhichmeantheyarevisibleonlytotheirscope.Theidentifiers“localVariable”,“a”and“x”areallvariablesdefinedinlocalscope.Thefirsttwovariablesfollowthegeneralrulesofscopebutxviolatesit.Thisprogramfailstocompilebecausevariablex,declaredinthe“for”loopisaccessedoutsideitsscope.Thecompilerisunabletoidentifyx
the“for”loopisaccessedoutsideitsscope.Thecompilerisunabletoidentifyxasanidentifieroutsideforloop.Tomakethisprogramwork,justdeletethesecondlaststatementinmainprogram.
5.6Recursion
Recursionisatechniqueinwhichafunctioncallsitselfinordertoachieveacertaingoal.
Recursionisaveryimportantasitprovidesawayformoreefficientandconcisecodefordifficultprogram.
Afunctionissaidtoberecursiveifitcallsitselfwithinitsbodybasedonadecisionstatementusually.Hereisanexampleforbetterillustration:voidmain(void)
{
printf("Thisprogramisnevergoingtoend..!\n");main();
system("pause");
}
Followingisanotherexample,whichkeepscallingitselfunlessacertaincondition(n<=1)ismet.
intfactorial(intn)
{
if(n<=1)
return1;
else
return(n*factorial(n-1));
}
voidmain(void)
{
intf=factorial(5);
printf("Factorial=%d\n",f);
system("pause");
}
5.7Examples
5.7.1Equalizers
voidprintTable(int);
voidprintHeading();
voidmain(void)
{
printHeading();
intx=1;
for(x=1;x<=10;x++)
{
printTable(x);
}
system("pause");
}
voidprintTable(inta)
{
for(intx=1;x<=10;x++)
{
printf("%d\t",x*a);
}
printf("\n");
}
voidprintHeading()
{
printf("-----------------------------TableofTables-----------------------------\n\n");}
5.7.2MultipleFilesInafileheader.h:
voidfunc(inta);
voidfuncSquare(inta);
voidfuncCube(inta);
InafileImplementation1.c:
voidfunc(inta)
{
printf("Iamfunc.Ihavetoprint:a=%d\n",a);}
InafileImplementation2.c
voidfuncSquare(inta)
{
printf("IamfuncSquare.Ihavetoprint:a=%d\n",a*a);}
voidfunc(inta)
{
printf("IamfuncCube.Ihavetoprint:a=%d\n",a*a*a);}
Inafilemain.c
#include"header.h"
voidmain(void)
{
printf("ThisisourmainProgram.Let'sstart...\n");
func(5);
funcSquare(5);
funcCube(5);
funcCube(5);
printf("ThisisourmainProgram.Let'sfinish...\n");
system("pause");
}
5.7.3MultipleFilesvoiddemo()
{
intnormalVariable=5;
staticintstaticVariable=5;
normalVariable+=10;
staticVariable+=10;
printf("Normal:%d\n",normalVariable);
printf("Static:%d\n",staticVariable);}
voidmain(void){
demo();
demo();
demo();
system("pause");
}
5.7.4Pointers
voidswap(intp,intq)
{
inttmp;
tmp=*p;
*q=tmp;
}
voidmain(void){
inta=10,b=20;
printf(“a=%d,b=%d\n”,a,b);
swap(&a,&b);
printf(“a=%d,b=%d\n”,a,b);
system("pause");
}
5.7.5BubbleSortvoidbubble(inta[],intn)
{
inti,j;
for(i0;i<n;++i)
for(jn1;j>i;-j)
if(a[j1J>a[j])
swap(&a[j-1],&a[jJ);
}
Chapter6:Arrays,PointersandStrings
Cprovidesadatastructurethatcanstoremultiplevaluesofsametypeinitbyassociatingeachvaluetoasubscript.Itisextremelyusefulincommonprogramming.
Forexample,youneedtostoremarksof50students,insteadofdeclaring50separatevariables,youcansimplyuseanarraywithsize50.Eachelementcanbeaccessedbyspecifyingitsindexorsubscript.
Anarrayisarandomaccessdatastructure,whereeachelementcanbeaccesseddirectlyandinconstanttime.Atypicalillustrationofrandomaccessisabook-eachpageofthebookcanbeopenindependentlyofothers.
ArraysinCconsistofcontiguousmemorylocationswhichmeansthattheyareplacedinmemorytogether.Thelowestmemberofarrayhasthelowestaddressandlastmemberofarrayhasthehighestmemoryaddressassignedtoit.
InC,arraysandpointersarecloselyrelatedconcepts.Interestingly,anarraynameitselfactsasapointer,andpointers,likearrays,canbeindexed.“Callbyreference”
mechanismisbasedonpointers.Thismechanismallowsprogrammertochangethevalueofalocalvariableinonescopefromanotherscope.Cusespointersforspecifyingparametersinfunctiondefinitionstoaccomplishthis.Stringsarealsoone-dimensionalarraysofcharacters.Theywillbediscussedinthenextchapter.
6.11-DArrays
1-Darraysrefertoonedimensionalarrays.Sucharrayscanbeconsideredasasingleroworcolumncontainingafixednumberofelements.Theyhaveonlyoneindex.Anarrayisjustlikeanormalvariableexceptforindex.Indexalwaysstartfrom0andendat(arraySize-1).
AgeneralformatforarraydeclarationinCisasfollows:TypearrayName[arraySize];Typereferstothedatatypeofarray,followedbyidentifierandintheendarraysizeenclosedinbrackets.
Arraysmaybeofstorageclassautomatic,staticorexternbutnotregister.ANSIC
supportstheinitializationofallthreetypesofarraysusinganinitializerbuttraditionalC
onlyalloweditforstaticorexternregisters.
Thegeneralformatforinitializing1-Darraysisasfollows:
Typeidentifier[size]={listofelementsseparatedbycommas}
Hereisanillustrationofusinga1-Darray,usinginitializer:voidmain(void)
{
inttable[10]={5,10,15,20,25,30,35,40,45,50};
//printingelementsofarray
for(inti=0;i<10;i++)
{
printf("5x%d=%d\n",i+1,table[i]);
}
system("pause");
}
Hereisanillustrationofusinga1-Darray,usingaloopforinitializationratherthancommoninitializer:
voidmain(void)
{
inttable[10];
//initializationofarray
for(inti=1;i<=10;i++)
{
table[i-1]=i*5;
}
//printingelementsofarray
for(inti=0;i<10;i++)
{
printf("5x%d=%d\n",i+1,table[i]);
printf("5x%d=%d\n",i+1,table[i]);
}
system("pause");
}
Output:Sameforbothprograms
6.2Pointers
Asimplevariableinaprogramisstoredinacertainnumberofbytesatamemorylocation,oraddress,inthemachine.Pointersarebasicallyvariablesthatholdtheseaddressesratherthanactualvalues.Theseaddresscanbeaccessedandhencetheactualvaluescanalsobeaccessedvia“reference”ofpointers.Pointersareusedinprogramstomemoryandmanipulateaddresses.Ifiisavariable,then&iistheaddressormemorylocationwherevalueofiisstored.Thisaddresscanbestoredintoapointervariableofsametype.Theaddressoperator&isunaryandhasthesameprecedenceandrighttoleftassociativityastheotherunaryoperators.
Pointervariablescanbedeclaredinprogramsandthenusedtotakeaddressesforinitialization.Thedeclarationisasfollows:int*p;
intx=5;
p=&x;
Theabovelinesdeclareapointervariablepofintegertypewhichstoresaddressofamemorylocationspecifiedbyanotherintegervariablex.Followingisaprogramwhichusespointerstoaccessothervariables:voidmain(void)
programwhichusespointerstoaccessothervariables:voidmain(void)
{
int*p;
intx=5;
p=&x;
printf("Valueofx:%d\n",x);
printf("Addressofx:%d\n",&x);
printf("Valueofp:%d\n",p);
printf("Addressofp:%d\n",&p);
printf("ppointstovalueviareference:%d\n",*p);
system("pause");
}
Normalvariablehastwonumbersassociatedwithit:anaddressofvariable,a
Normalvariablehastwonumbersassociatedwithit:anaddressofvariable,avaluestoredonthisaddress.Thevariablenameaccessesthevaluewhileampersandwithvariablenameaccessestheaddress.Apointervariablehasthreenumbersassociatedwithit:anaddressofpointervariableitself,avaluestoredinitafterinitialization,avaluepointedbyvaluestoredinthepointervariable.Thefirsttwoareaccessedusingvariablenameandampersandvariablename,justlikenormalvariables.Thethirdvalueassociatedwithpointersisaccessedusing*signwithidentifier.
Followingisanexamplewhichusespointerstoaccessarraysbetweentwofunctionstoclarifythe“callbyreference”mechanismaswell:voidprintMe(int*p)
{
intarr[10];
for(inti=1;i<=10;i++)
{
arr[i-1]=*(p+i-1);
}
//printingelementsofarray
for(inti=0;i<10;i++)
{
printf("5x%d=%d\n",i+1,arr[i]);
}
}
voidmain(void)
voidmain(void)
{
inttable[10];
//initializationofarray
for(inti=1;i<=10;i++)
{
table[i-1]=i*5;
}
printMe(table);
system("pause");
}
So,wepassedjustthestartingaddressofanarrayasapointertoanothermethodandwewereabletoaccessthearraydefinedinanotherfunction.Notethattheidentifierrepresentinganarray,ifwrittenwithoutanindexisequivalenttothestartingaddressofarray(&identifier[0]).*(p+i)isusedforindexing.IfvalueofIis1,andintegerisof4
Iis1,andintegerisof4
bytes,theprogramaccessesthenextintegerratherthanjustnextbyte.
Now,wewillseeanexampleinwhichvaluesofanidentifierdefinedinourmainfunctionarechangedaftercallinganotherfunctionbypassingapointertoit.
voidchangeMe(int*p)
{
for(inti=0;i<10;i++)
{
p[i]=10;
}
}
voidmain(void)
{
inttable[10];
inttable[10];
//initializationofarray
for(inti=1;i<=10;i++)
{
table[i-1]=i*5;
}
printf("---BeforeFunctioncall---\n");
for(inti=0;i<10;i++)
{
printf("5x%d=%d\n",i+1,table[i]);
}
changeMe(table);
printf("---AfterFunctioncall---\n");
for(inti=0;i<10;i++)
{
printf("5x%d=%d\n",i+1,table[i]);
}
system("pause");
}
}
So,weaccessedanarraydefinedinourmainfunctioninsideanotherfunctionandchangedallofitsvaluesto10.Thechangewasvisibleinourmainprogram.Thisiswhat“callbyreference”mechanismisusedfor.Themechanismisclearlypossible,onlyduetopointers.
Althoughpointersandarraysarealmostsynonymousintermsofhowtheyareusedtoaccessmemory,asisclearfromaboveexampleaswell,therearedifferences,andthesedifferencesaresubtleandimportant.Apointervariablecantakedifferentaddressesasvalueswhichmeanstheycanberedefinedatanypointoftime.Thisisnotthecasewitharrays.Anarraynameisanaddress,orpointer,thatisfixed.
6.3Strings
Stringsareone-dimensionalarraysoftypechar.Youmaybewonderingifstringsarearraysofchartype,whydoweneedtodiscusstheseparately.TheprimarydifferencebetweenStringsandcharacterarraysisthatStringscanhavevariablelengthwhereaschararrayshaveafixedsize.
Asstringscanhaveavariablelength,wehaveamechanismtoidentifytheendofastring.Everystring,bydefaultendsinthenullcharacter\0.Thesizeofastringmustincludethestorageneededfortheend-of-stringcharacteraswell.Itisprogrammer’sjobtoneveraccessacharacterfromastringthatoverrunsthesizeofstring.
Incontrasttochararrayswhicharerepresentedinsinglequotes,stringsareinitializedwithdoublequotes.Forexample,"abc"isastringofsize4,withthelastelementbeingthenullcharacter\0.
Although,charconstantsandstringsseemcloselyrelatedbuttheyarenotsame.Forexample,"a"and'a'arenotthesame.“a”hastwocharactersoneofwhichis‘a’andtheotheroneis\0.
Astringisconsideredbythecompilerasapointer.Itsvalueisthebaseaddressofthestring.Considerthefollowingcode:char
*pointer
=
=
"abc";
printf(“%s%s\n”,pointer,pointer+1);Thepointervariableisassignedthestartingvalueofstring.Thefirststringisprintedstartingfrom‘a’.Thesecondstringmovesitsaddressbyoneunit(charisof1byte,usually)andhencestartsfrom‘b’.So,theoutputforabovelinesofcodewillbe:abcbc
Asstringscanbeconsideredaspointers,statementslike*(“abc”+2)and“abs”[2]arelegalincompilers.
Letusnowseeanexamplewhichusesachararrayaswellasastring.Youcanseetheconvenienceinusingstrings:
voidmain(void)
{
char*s="aString";
charcharacters[10]={'c','h','a','r','a','c','t','e','r','s'};
for(inti=0;i<10;i++)
printf("%c",characters[i]);
printf("\n%s\n",s);
system("pause");
}
Fortechnicalreasons,itisbetternottoprintnullcharacters.Stringsdonotprintnullcharacterunlessweusepointertoaccessthelastcharacterofthestring.
Now,wewriteaprogramtocountnumberofwordsinastringtogetbetterunderstandingofstrings.Theprogramusesamacro,isspace()whichreturnstrueinacasewhenthespecifiedcharacterisaspace.Itreturnsfalseotherwise.
intnumberOfWords(constchar*str)
{
intcount=0;
while(*str!='\0')
{
while(isspace(*str))
{
++str;
if(*str!='\0')
{
count++;
}
}
}
}
return++count;
}
Astringorpointertocharacterarrayispassedasanargument.Weconsiderspacesaswordseparator.Weincrementthewordcountvariableforallthewordsseparatedbyspaces.Weincrementitagainattheagain,sothatthelastwordisalsocounted.
ANSICprovidestheprogrammerwithpre-definedfunctionstohandlestrings.Thissectiondemonstrateshowtousesomeofthesefunctions.Thefunctionprototypesforstring-handlingfunctionsaregiveninthestandardheaderfilestring.h.Theseprototypesusecharacterpointersandstringsforcertainparameters.Remember,thesecanbeusedinterchangeably.
FunctionName
Description
charstrcat(chars1,canstchar*s2);Concatenatessecondstringtotheendoffirststringandreturnsit.
intstrcmp(constchars1,constchars2);Comparestwostrings.Itreturnsavaluelessthan0iffirststringislessthansecond,avaluegreaterthan0iffirststringisgreaterthansecondandreturns0ifbothareequal.
char*strcpy(chars1,constchars2);Strings1isoverwrittenbyStrings2ands1isreturned.
size_tstrlen(constchar*s)
Returnsnumberofcharactersinstrings,excludingtheendingcharacter.
Thesefunctionscanbewrittenbyprogrammersaswell.Itisrecommendedtousetheseastheyaremoreefficientbecausetheyuseregisterclassvariables.
6.42-DArrays
Eventhougharrayelementsarestoredcontiguouslyoneaftertheother,itisusuallyconvenienttothinkofatwo-dimensionalarrayasatableofelementswithrowsandcolumns.Thishelpsinbetterunderstandingof2-Dimensionalarrays.Forexample,todeclareanarrayoftwentyelementswithfiverowsand4columns,weusethefollowingstatement:
intTwo_D[5][4];
Nestedloopsareusuallyusedfordealingwith2-Dimensionalarrays.
Theseelementscanberepresentedas:Two_D[0][0]Two_D[0][1]
Two_D[0][2]
Two_D[0][3]
Two_D[1][0]
Two_D[1][1]
Two_D[1][2]
Two_D[1][3]
Two_D[2][0]
Two_D[2][1]
Two_D[2][2]
Two_D[2][3]
Two_D[3][0]
Two_D[3][1]
Two_D[3][2]
Two_D[3][3]
Two_D[3][3]
Two_D[4][0]
Two_D[4][1]
Two_D[4][2]
Two_D[4][3]
6.53-DArrays
Arraysofdimensionhigherthantwoworkinasimilarfashion.Letusdescribehowthree-dimensionalarrayswork.IfwedeclareIntThree_D[5][3][2];
Thecompilerallocates5*3*2memoryaddressforintegertype.ThebaseaddressisThree_D[0][0][0].
Hereisafunctionthataddstheelementsofathreedimensionalarrayandreturnsthetotal.
intsum(intThree_D[5][3][2])
{
inti,j,k,sum=0;
for(i=0;i<7;++i)
for(j=0;j<9;++j)
for(k=0;k<2;++k)
sum+=Three_D[i][j][k];
sum+=Three_D[i][j][k];
returnsum;
}
Chapter7:Structures
Cisaneasilyextensiblelanguage.Itcanbeextendedusingheaderfilesandstandardlibrariestousecertainfunctionsandmacros.Itcanalsobeextendedbydefiningdatatypesthatareconstructedfromthefundamentaltypessuchasanarraywhichisagroupofdefaultdatatypevariables.
Thestructuretypeisusedtorepresentheterogeneousdata.Astructurehascomponents,calledmembers.Structuresaredesignedforprogrammer’seasesothattheycandefineadatatypeoftheirownwhichmaycontainmorethanonemembers.Eachmembercanbeeitheradefaultdatatypeoranotherstructure.Becausethecomponentsofastructurecanbeofvarioustypes,theprogrammercandesignthemasperhisrequirements.
7.1DeclarationThestructuresallowprogrammertointegratedifferenttypeofvariablestogether.
Arraysareusedforstoringvariablesofsametype.Asasimpleexample,letusdefineastructurethatdescribesastudent.AstudenthasvariousattributesofdifferenttypessuchasName,Course,Section,CGPAandID.AstudentcanbedefinedasastructureinC.Wecandeclarethestructuretypeforstudentusingthekeywordstructasfollows:structStudent
{
char*Name;
intCourse,ID;
charSection;
doubleCGPA:
};
Thisdeclarationcreatesthederiveddatatypestructstudent.Itisauserdefineddatatype.Thestructuresonedefinedcanbeusedtodefineidentifiersofthisuser-definedtype.Thetagnameoridentifieralongwithkeywordstructisusedtodeclarevariablesoftypestudent:
todeclarevariablesoftypestudent:
StructStudents1,s2,s3;
Theabovedeclarationsforstructvariablesallocatesstoragefortheidentifiers,whichnowrepresentaStudent.Analternativewaytodeclaretheseidentifiersisasfollows:
structStudent
{
char*Name;
intCourse,ID;
charSection;
doubleCGPA:
}s1,s2,s3;
Anotherwayofdeclaration,whichishighlyrecommendedasitshortensthedeclarationofidentifiersofthestructure,isasfollows:typedefstruct
{
char*Name;
intCourse,ID;
charSection;
doubleCGPA:
}Student;
7.2MemoryAllocationAlthoughmemoryisallocatedtothesevariablesatthetimeofdeclarationbutthesevariableshavebeenassignednothing.Nostudenttypevariablehasdetailssavedinit.
Here’showeachcomponentofastructtypevariableisinitialized:
s1.Name=“RKhan”
s1.Course=18;
s1.ID=786;
s1.Section=‘A’;
s1.CGPA=3.74;
7.3MemberAccessOperatorsWecanaccessamemberofastructvariableintwoways.Theaboveexampleusesthememberaccessoperator“.”.Wewillnowgivefurtherexamplesofitsuseandintroducetheothermemberaccessoperator“->”.Bothoperatorsareusedforsamepurpose.Thedifferenceliesinthecaller.Thedotoperatorisusedbyastructurevariablewhilearrowisusedbyapointertostructurevariable.
typedefstruct
{
char*Name;
intCourse,ID;
charSection;
doubleCGPA;
}Student;
voidprintUsingPointer(Student*s){
printf("%s%d%d%c%f\n",s->Name,s->ID,s->Course,s->Section,s->CGPA);}
voidmain(void)
{
Students1,s2;
s1.Name="RKhan";
s1.Course=18;
s1.ID=786;
s1.Section='A';
s1.CGPA=3.74;
s2.Name="AliKhan";
s2.Course=18;
s2.ID=890;
s2.Section='A';
s2.CGPA=3.14;
printf("%s%d%d%c%f\n",s1.Name,s1.ID,s1.Course,s1.Section,s1.CGPA);
printUsingPointer(&s2);
system("pause");
}
Followingareafewstatementsandequivalentaccessmethodsarelistedaswell:structstudents,*p=&s;s.Section=='A';s.Name="Khan";s.student_id=786;
ExpressionEquivalentExpressionValues.grade
p->grade
‘A’
s.Name
p->Name
“Khan”
(*p).ID
p->ID
786
*p->Name+1
(*(p->Name))+1
D
*(p->Name+2)
(p->Name)[2]
S
7.4DefinitionAllexternalandstaticvariables,includingstructvariables,areinitializedbytheprogrammerareautomaticallyinitializedbythesystemtozero,unlessspecifiedotherwise.IntraditionalC,onlyexternalandstaticvariablescanbeinitialized.ANSIC
allowsautomaticvariables,includingstructures,tobeinitializedaswell.Thesyntaxforinitializingstructuresisquitesimilartothatforinitializingarraysasstructuresalsotakevaluesinbraces.
Astructurevariableinadeclarationcanbeinitializedbyfollowingitwithanequalsignandalistofconstantscontainedwithinbraces.Ifnotenoughvaluesareusedtoassignallthemembersofthestructure,theremainingmembersareassignedwithvalue0.
Someexamplesare:
Students1={“Mashal”,18,123,‘A’,3.79};Paira[3][3]={{{1.0,-10},{20.0,0.2},{3.5,0.3}},{{4.7,-0.4},{2.0,0.5},{6.0,1.6}}};7.5AbstractDataTypesThetermabstractdatatype(ADT)referstoadatastructuretogetherwithitsoperations,withoutspecifyinganimplementation.Supposewewantedanew
integertype,onethatcouldholdarbitrarilylargervaluesthanthedefaultvalue.ThenewintegertypetogetherwithitsarithmeticoperationswillbeanADT.TheideaofADTcomesfromvarietyofrequirementsthatkeepsgrowingwithinnovativeapplications.Nativetypessuchaschar,int,anddoublearealreadyimplementedbytheCcompilerandcannotbealtered.
So,weneedamechanismtodefineourownDatatypeswithcertainoperations.
7.5.1StacksAnADTstackisacontainerofobjectsthatfollowsthelast-infirst-out(LIFO)principle.
Itmeansthatyoucanaccessonlythelatestelementyouhaveentered.Astackisalimitedaccessdatastructure-elementscanbeaddedandremovedfromthestackonlyatthetop.Foraccessingotherelements,youneedtoremovetheobjectsontopofthem.
Onlytwoprimaryoperationsarenecessaryforstackimplementation:pushandpop.
Pushreferstoaddinganelementtothetopofstackwhilepopremovestheitematthetopofthestack.Ahelpfulanalogyistothinkofastackofdumbbellsonasteelrod;youcanremoveonlythetopdumbbell,alsoyoucanaddanewdumbbellonthetop.
NowwedevelopandimplementtheADTstack,oneofthemostusefulstandarddatastructures.Thetypicaloperationsthatcanbeimplementedforastackarepush,pop,top,empty,full,andreset.Thepushandpopoperationsarediscussedearlier.TheemptyoperatortestsifthestackisemptyornotandresultsinaBooleanvalue.Thefulloperatortestsifthestackisfull,whichalsoreturnsaBooleanvalue.Theresetoperatorremovesalltheelementsofstackandinitializesit.
Wewilluseafixed-lengthchararraytostorethecontentsofthestack.Thetopofthestackwillbeaninteger-valuedmembernamedtop.Thevariousstackoperationsdiscussedinthepreviousparagraphwillbeimplementedasfunctions,eachofwhoseparameterlistsincludesaparameteroftypepointertostack.Usingapointerresultsinbetterefficiencybyavoidingtocopylargestackvalues.
values.
HereisacompleteCprogram,whichimplementsvariousfunctionsofstack:#defineMAX_SIZE50
intstack[MAX_SIZE];
voidpush();
intpop();
intis_empty();
intpeek();
intTOP=-1;
intmain()
{
intelement,choice;
while(1)
{
printf("StackOperations.\n");printf("1.Insertintostack(Pushoperation).\n");printf("2.Deletefromstack(Popoperation).\n");printf("3.Printtopelementofstack.\n");
printf("4.Checkifstackisempty.\n");printf("5.Exit.\n");
printf("Enteryourchoice.\n");scanf("%d",&choice);
switch(choice)
{
{
case1:
if(TOP==MAX_SIZE-1)
printf("Error:Overflow\n\n");else{
printf("Enterthevaluetoinsert.\n");scanf("%d",&element);
push(element);
}
break;
case2:
if(TOP==-1)
printf("Error:Underflow.\n\n");else{
element=pop();
printf("Elementremovedfromstackis%d.\n",element);}
break;
case3:
if(!is_empty()){
element=peek();
printf("Elementatthetopofstackis%d\n\n",element);}
else
printf("Stackisempty.\n\n");break;
case4:
if(is_empty())
printf("Stackisempty.\n\n");else
printf("Stackisnotempty.\n\n");break;
case5:
exit(0);
}
}
}
voidpush(intvalue)
{
TOP++;
stack[TOP]=value;
}
intpop()
{
intelement;
if(TOP==-1)
returnTOP;
element=stack[TOP];
TOP--;
returnelement;
}
intis_empty()
{
if(TOP==-1)
return1;
else
return0;
}
intpeek()
{
returnstack[TOP];
}
7.5.2QueuesAqueueisacontainerofobjects(alinearcollection)thatfollowsthefirst-infirst-out(FIFO)principle.AnexampleofqueuesisanyreallifequeuelikeinaBank,orATMorAirport.Anewelementorobjectisaddedtothebackofthequeue,whileremoval(orserving)happensfromthefront.Inthequeueonlytwooperationsareallowed.Theseareenqueueranddequeuerfunctions.Firstonemeanstoinsertanitemintothebackofthequeueanddequeuereferstoremovinganitemfromthefront.
Thedifferencebetweenstacksandqueuesisinremoving.Inastackweremovethelastitemthatwasaddedwhereasinaqueue,weremovetheitemthathasbeeninthequeuemorethananyoneelse.
HereisacompleteprogramillustratingtheuseofQueues:#defineMAX_SIZE50
50
intqueue_array[MAX_SIZE];
intrear=-1;
intfront=-1;
voidmain(void)
{
intchoice;
while(1)
{
printf("1.Insertelementtoqueue\n");printf("2.Deleteelementfromqueue\n");printf("3.Displayallelementsofqueue\n");printf("4.Quit\n");
printf("Enteryourchoice:");scanf("%d",&choice);
switch(choice)
{
case1:
insert();
break;
case2:
delete();
break;
case3:
display();
display();
break;
case4:
exit(1);
default:
printf("Wrongchoice\n");
}
}
}
voidinsert()
{
intadd_item;
if(rear==MAX-1)
printf("QueueOverflow\n");
else
{
if(front==-1)
front=0;
printf("Insettheelementinqueue:");scanf("%d",&add_item);
rear=rear+1;
queue_array[rear]=add_item;}
}
voiddelete()
{
if(front==-1||front>rear){
printf("QueueUnderflow\n");return;
}
else
{
printf("Elementdeletedfromqueueis:%d\n",queue_array[front]);front=front+1;
}
}
voiddisplay()
{
inti;
if(front==-1)
printf("Queueisempty\n");
else
{
printf("Queueis:\n");
for(i=front;i<=rear;i++)printf("%d",queue_array[i]);printf("\n");
}
}
7.5.3LinkedListsAlinkedlistisasequentialaccessdatastructure,whereeachelementcanbeaccessedonlyinparticularorder.Atypicalillustrationofsequentialaccessfindingaparticularfilefromanunorganizedpileoffiles.Itislikeaclotheslineonwhichthedatastructureshangsequentially.Aheadpointeraddressesthefirstelementofthelist,andeachelementpointsatasuccessorelement,withthelastelementhavingaNULLvalue.
Here’sacodethatimplementsalinkedlist.Linkedlistconsistsofadjacentnodeswitheachhavingtheaddressofnextnode.Startingfromhead,wecantraversethroughthewholelistbyusingthepointernextineachnode.Wecantakeanotherpointerinnodewhichcanholdaddressforpreviousnodeaswell.
structNode
{
intval;
structNode*next;
};
typedefstructNodeelement;
voidmain()
{
elementcurr,head;
inti;
head=NULL;
for(i=1;i<=10;i++)
{
curr=(element*)malloc(sizeof(element));curr->val=i;
curr->next=head;
head=curr;
}
curr=head;
while(curr){
printf("%d\n",curr->val);curr=curr->next;
}
}
Chapter8:BinaryTrees
Atreeisafinitesetofelements,oftenknownasnodes.Everytreehasauniquestartingnode,calledtherootnode,whereastheremainingnodesareadisjointcollectionofsubtreesofthisrootnode.Eachnodekeepstrackofitsparentsor/andchildrensothattraversalcanbemadepossible.Anodewithnochildreniscalledaleafnodeoraterminalnode.
Abinarytreeisatreewhosenodescanhaveamaximumoftwochildren.Abinarytreeisadatastructurewhichcomprisesoftwopossiblesub-elementsofeverynode,calledleftchildandrightchild.Ifanodedoesnothavealeftorrightchild,theyareassignedNULLvalues.EachlinkmustpointatanewobjectnotpointedatorbeNULL.
Thegeneralformanodeinabinarytreeisasfollows:structnode
{
Charvalue;
Nodeleft,right;
};
Thebinarytreeisausefuldatastructureforrapidlystoringsorteddataandrapidlyretrievingstoreddata.Thisresultsinanimmenseincreaseinefficiencyofsearchingandsorting.
8.1CompositionAbinarytreeiscomposedofparentnodes,orleaves,eachofwhichstoresdataandalsolinkstouptoatmosttwochildnodes.Itistherelationshipbetweentheleaveslinkedtoandthelinkingleaf,alsoknownastheparentnode,whichmakesthebinarytreesuchanefficientdatastructure.
Generally,theleftnodehasalesservaluethanparentwhilerightchildhasagreaterkeyvaluethanitsparents.Duetothesetwosimplerules,theefficiencyoftreesisenormous.
Asaresult,theleavesonthefarthestleftofthetreehavethelowestvaluesandwealreadyknowthatsoifwewanttogetthelowestvalue,weonlyneedtotraversetothelowermostleafnodetotheleftinsteadofgoingthrougheveryelementofthetree.
Similarly,theleavesontherightofthetreehavethegreatestvaluesandthereforeifweneedtofindthehighestnumber,wejustneedtotraversetoonesideofthetreeandwe
canreachthedestinationmuchquickerthanaprogramwhichusedsortingandsearchingalgorithmstoaccomplishthistask.
Moreimportantly,aseachleafconnectstotwootherleaves,itisthebeginningofanew,smaller,binarytree.Duetothisreason,itispossibletoeasilyaccessandinsertanytypedatainabinarytreeatanypointoftime,usingsearchandinsertfunctionsrecursivelycalledonsuccessiveleavesandmaintainingtheorderoftreeaswell.Thenewlyinsertednodealwaysgoestotherightplace.
8.2InsertFunctionThefollowinginsertfunctioninsertselementsinatree.Iftreeisnotcreated,theelementcreatesitaswell.Itusespointerstopointersinordertohandlethecaseofatreethatmightnotexist.Bytakingapointertoapointer,itispossibletoallocatememoryiftherootpointerisNULL.
voidinsert(intkey,structnode**terminal){
if(*terminal==0)
{
*terminal=(structnode*)malloc(sizeof(structnode));(*terminal)->key_value=key;(*terminal)->left=0;
(*terminal)->right=0;
}
elseif(key<(*terminal)->key_value){
insert(key,&(*terminal)->left);}
insert(key,&(*terminal)->left);}
elseif(key>(*terminal)->key_value){
insert(key,&(*terminal)->right);}
}
Theinsertfunctionfollowsthetwobasicrulesofabinarytree.Foranycurrentnode,moveleftifyouhavealowervaluetoenterandmoverightforagreatervalue,untilitreachesaNULLnode,whichitallocatesmemoryforandinitializeswiththenewkeyvalue.ThepointerstothesecondlastnodeareupdatedandpointersfornewlyinitializednodearesettoNULL.Once,theelementhasbeenadded,theinsertfunctionwillstopcallingitselfandreturnprogramcontroltonormalenvironmentforexecution.
8.3SearchFunctionHereisasearchfunctionforabinarytree.Ittakesakeyvalueandastartingnodeandsearchesthekeyvalueinthetreerecursively.Ifleafnodeisfound,itisreturnedelsewise0isreturned.
structnodesearch(intkey,structnodeterminal){
if(terminal!=0)
{
if(key==terminal->key_value){
returnterminal;
}
elseif(key<terminal->key_value){
returnsearch(key,terminal->left);}
else
{
returnsearch(key,terminal->right);}
}
}
elsereturn0;
}
Thesearchfunctionshownaboverecursivelymovesdownthetreeuntiliteitherreachesanodewithakeyvalueequaltothevalueforwhichthefunctionissearching.ThevaluebeingsearchedformaynotbestoredinthebinarytreeandhenceweandhencewemaintainaconditionwhensearchreachesanodewithNULLvalue,itisconcludedthatthekeyvalueleafisnotthereinthebinarytree.Itreturnsapointertothenodetothepreviousinstanceofthefunctionwhichcalledit.
Conclusion
Thebookisasimple,completeandquickreferenceforprogramminginC.Thebookpresentsthegeneralpurposelanguage,stepbystep.Itiswrittenfollowingaprogrammer’sapproachandisthereforeidealforusingasaquickguideandreferenceforpeoplewhoaimtocodeinC.
ThebookcoversallthebasicconceptsofprogrammingindetaillikeOperators,Functions,Pointers,Arrays,Strings,anddecisionmakingstatements.Thebookhastheflexibilitytohelpthereadersiftheyareinterestedinselectivestudy.Thechaptersarewrittenwithminimumpossibleinter-dependency.
Attheendofthebook,thereadermustbeanefficientprogrammerinCandwillbefamiliarwithfollowingconceptsofC:•Anoverviewofthelanguage
befamiliarwithfollowingconceptsofC:•Anoverviewofthelanguage
•LexicalelementsofC
•Loops
•DecisionMakingstatements
•Arrays()
•Strings
•Pointers
•Functions
•Abstractdatatypes
•Stacks
•Queues
•Linkedlists
•BinaryTree
Ifyou’vefoundthebookhelpful,pleaseleaveareviewforitnow.AlsocheckoutmyotherbooksonKindle.
R.J.Khan
CheckOutMyOtherBooks:
CProgrammingLanguageQuickStartGuide:SimplifiedGuideForBeginners
SCRUM:TheFastandSimplifiedGuideScrum–AgileProjectManagement(comingsoon)