152

C Programming Language Quickstart Guide: Simplified Guide for Beginners

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: C Programming Language Quickstart Guide: Simplified Guide for Beginners
Page 2: C Programming Language Quickstart Guide: Simplified Guide for Beginners

ProgrammingLanguage

QuickStartGuide

Page 3: C Programming Language Quickstart Guide: Simplified Guide for Beginners

SimplifiedGuideforBeginners

By:

R.J.KHAN

Page 4: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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,

Page 5: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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.

Page 6: C Programming Language Quickstart Guide: Simplified Guide for Beginners

indirectly.

Respectiveauthorsownallcopyrightsnotheldbythepublisher.

Theinformationhereinisofferedforinformationalpurposessolely,andisuniversalasso.Thepresentationoftheinformationiswithoutcontractoranytypeofguaranteeassurance.

Thetrademarksthatareusedarewithoutanyconsent,andthepublicationofthetrademarkiswithoutpermissionorbackingbythetrademarkowner.Alltrademarksandbrandswithinthisbookareforclarifyingpurposesonlyandaretheownedbytheownersthemselves,notaffiliatedwiththisdocument.

TABLEOFCONTENTS

Page 7: C Programming Language Quickstart Guide: Simplified Guide for Beginners

Chapter1

Let’sC………………………………………………………………6

1.Background……………………………………………………………….6

2.ANSIC……………………………………………………………………...7

3.StrengthsofC……………………………………………………………8

4.ProgramminginC……………………………………………………..9

5.NothingisPerfect……………………………………………………..10

Page 8: C Programming Language Quickstart Guide: Simplified Guide for Beginners

Chapter2

TokensandSyntax…………………………………………..11

1.Preprocessors…………………………………………………………….11

2.Variables……………………………………………………………………14

3.Constants…………………………………………………………………..16

4.Keywords…………………………………………………………………..17

5.CharacterConstants……………………………………………………18

6.OperatorsandPunctuators…………………………………………23

7.PrecedenceandAssociativity………………………………………33

Page 9: C Programming Language Quickstart Guide: Simplified Guide for Beginners

Chapter3

DataTypes………………………………………………………………37

1.IntegralDataTypes……………………………………………………38

2.Floatingpoint……………………………………………………………38

3.Using‘typedef’……………………………………………………..……39

4.Storageclasses…………………………………………………………..39

5.DefaultInitializers…………………………………………………….43

Page 10: C Programming Language Quickstart Guide: Simplified Guide for Beginners

Chapter4

LoopsandDecisions………………………………………..44

1.Ifelse……………………………………………………………44

2.Switchcase…………………………………………………….46

3.Forloop………………………………………………………….48

4.Whileloop………………………………………………………50

5.Dowhileloop…………………………………………………….51

6.NestedLoops…………………………………………………….52

Page 11: C Programming Language Quickstart Guide: Simplified Guide for Beginners

Chapter5

Functions……………………………………….……………….54

1.FunctionDefinition……………………………………………54

2.FunctionPrototypes………………………………………….57

3.AlternativeDeclarations……………………………………..58

4.FunctionInvocation……………………………………………59

5.Environment……………………………………………………..60

6.Recursion………………………………………………………….61

7.Examples…………………………………………………………..62

Page 12: C Programming Language Quickstart Guide: Simplified Guide for Beginners

Chapter6

Arrays,StringsandPointers………………………………66

1.1-DArrays…………………………………………………………66

2.Pointers…………………………………………………………...68

3.Strings……………………………………………………………...72

4.2D-Arrays…………………………………………………………75

5.3D-Arrays…………………………………………………………76

Page 13: C Programming Language Quickstart Guide: Simplified Guide for Beginners

Chapter7

Structures……………………………………………………….77

1.Declaration……………………………………………………..77

2.MemoryAllocation………………………………………….78

3.MemberAccessoperators………………………………..79

4.Definition……………………………………………………….80

5.AbstractDataTypes…………………………………………81

Page 14: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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.

Page 15: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 16: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 17: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 18: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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>

Page 19: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 20: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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.

Page 21: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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.

Page 22: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 23: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 24: C Programming Language Quickstart Guide: Simplified Guide for Beginners

#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);

Page 25: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 26: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 27: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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);

Page 28: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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;

Page 29: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 30: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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);

Page 31: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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");

}

Page 32: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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.

Page 33: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 34: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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.

Page 35: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 36: C Programming Language Quickstart Guide: Simplified Guide for Beginners

sequence

Meaning

\\

\character

\'

'character

\"

"character

\?

?character

\a

Alertorbell

\b

Backspace

\f

Formfeed

\n

Newline

\r

Carriagereturn

\t

Page 37: C Programming Language Quickstart Guide: Simplified Guide for Beginners

Horizontaltab

\v

Verticaltab

\ooo

Octalnumberofonetothreedigits

\xhh..

HexadecimalnumberofoneormoredigitsThenwehaveASCIIcharacters,thatarelistedbelow:CharDecAction

NUL

0

Nullcharacter

SOH

1

Startofheading,=consoleinterruptSTX

2

Startoftext,maintenancemodeonHPconsoleETX

3

Endoftext

EOT

4

Page 38: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 39: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 40: C Programming Language Quickstart Guide: Simplified Guide for Beginners

Devicecontrol4

NAK

21

Negativeacknowledge

SYN

22

Synchronousidle

ETB

23

Endtransmissionblock,notthesameasEOT

CAN

24

Cancelline,MPEechoes!

EM

25

Endofmedium,ControlYinterrupt

SUB

26

Substitute

ESC

27

Page 41: C Programming Language Quickstart Guide: Simplified Guide for Beginners

Escape,nextcharacterisnotechoedFS

28

Fileseparator

GS

29

Groupseparator

RS

30

Recordseparator,block-modeterminatorUS

31

Unitseparator

TheaboveislistofallthecontrolASCIIcharacters.FollowingisthelistofprintableASCIIcharactersinASCII.

CharDecDescriptionSP

32Space

!

33Exclamationmark

"

34Quotationmark

Page 42: C Programming Language Quickstart Guide: Simplified Guide for Beginners

#

35Crosshatch(numbersign)

$

36Dollarsign

%

37Percentsign

&

38Ampersand

`

39Closingsinglequote(apostrophe)(

40Openingparentheses

)

41Closingparentheses

*

42Asterisk(star,multiply)

+

43Plus

,

44Comma

-

45Hyphen,dash,minus

Page 43: C Programming Language Quickstart Guide: Simplified Guide for Beginners

45Hyphen,dash,minus

.

46Period

/

47Slant(forwardslash,divide)

0

48Zero

1

49One

2

50Two

3

51

Three

4

52Four

5

53Five

6

54Six

7

55Seven

Page 44: C Programming Language Quickstart Guide: Simplified Guide for Beginners

55Seven

8

56Eight

9

57Nine

:

58Colon

;

59Semicolon

<

60Lessthansign

=

61Equalssign

>

62Greaterthansign

?

63Questionmark

@

64At-sign

A

65UppercaseA

B

Page 45: C Programming Language Quickstart Guide: Simplified Guide for Beginners

B

66UppercaseB

C

67UppercaseC

D

68UppercaseD

E

69UppercaseE

F

70UppercaseF

G

71

UppercaseG

H

72UppercaseH

I

73UppercaseI

J

74UppercaseJ

K

75UppercaseK

Page 46: C Programming Language Quickstart Guide: Simplified Guide for Beginners

L

76UppercaseL

M

77UppercaseM

N

78UppercaseN

O

79UppercaseO

P

80UppercaseP

Q

81UppercaseQ

R

82UppercaseR

S

83UppercaseS

T

84UppercaseT

U

85UppercaseU

Page 47: C Programming Language Quickstart Guide: Simplified Guide for Beginners

V

86UppercaseV

W

87UppercaseW

X

88UppercaseX

Y

89UppercaseY

Z

90UppercaseZ

[

91Openingsquarebracket

\

92Reverseslant(Backslash)

]

93Closingsquarebracket

^

94Caret(Circumflex)

_

95Underscorè

96Openingsinglequote

Page 48: C Programming Language Quickstart Guide: Simplified Guide for Beginners

a

97Lowercasea

b

98Lowercaseb

c

99Lowercasec

d

100Lowercased

e

101Lowercasee

f

102Lowercasef

g

103Lowercaseg

h

104Lowercaseh

i

105Lowercasei

j

106Lowercasej

k

Page 49: C Programming Language Quickstart Guide: Simplified Guide for Beginners

107Lowercasek

l

108Lowercasel

m

109Lowercasem

n

110Lowercasen

o

111Lowercaseo

p

112Lowercasep

q

113Lowercaseq

r

114Lowercaser

s

115Lowercases

t

116Lowercaset

u

117Lowercaseu

Page 50: C Programming Language Quickstart Guide: Simplified Guide for Beginners

v

118Lowercasev

w

119Lowercasew

x

120Lowercasex

y

121Lowercasey

z

122Lowercasez

{

123Openingcurlybrace

|

124Verticalline

}

125Closingcurlybrace

~

126Tilde(approximate)

DEL127Delete(rubout),cross-hatchbox

2.6OperatorsandPunctuatorsLikeeveryotherprogramminglanguage,Chas

Page 51: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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)

Page 52: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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:

Page 53: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 54: C Programming Language Quickstart Guide: Simplified Guide for Beginners

Multiply

Usedtomultiplytwonumbers

/

Divide

Usedfordivisionoftwonumbers

%

Modulus

Usedtofindremainderafterdivisionof2numbers~

Negation

Binaryoperator,usedtoinvertthebooleanvalue&

BitwiseANDUsedtoperformlogicalANDoneverybit|

BitwiseOR

UsedtoperformlogicalORoneverybit^

Power

Usedtocomputepowerofanumber

<<

LeftShift

Usedtoshiftbitstotheleft

>>

RightShift

Usedtoshiftbitstothetight

Letusnowseeanexampleofusingtheseoperatorsinaprogram:#include

Page 55: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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);

Page 56: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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.

Page 57: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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:

Page 58: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 59: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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);

Page 60: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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;

Page 61: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 62: C Programming Language Quickstart Guide: Simplified Guide for Beginners

++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");

Page 63: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 64: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 65: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 66: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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");

Page 67: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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)

Page 68: C Programming Language Quickstart Guide: Simplified Guide for Beginners

2.7PrecedenceandAssociativityAswediscussedearlieraswell,wehaverulesofprecedenceandassociativitythatareusedtodeterminehowcertainexpressionsareevaluated.LetusbrieflydiscusshowprecedencerulesareusedbyaCcompilertocomputetheuniqueandcorrectanswerofanexpression.

ThefollowingisatablerepresentingtheprecedenceofoperatorsinC.Theoperatorsatthetophavehighestprecedencewhiletheoperatorsatbottomhavetheleastprecedenceinanexpression.Theoperatorswithhigherprecedencearecomputedfirstinanexpression.

Category

Operator

Associativity

Postfix

()[]->.++--

Lefttoright

Unary

+-!~++--(type)*&sizeof

Righttoleft

Multiplicative*/%

Lefttoright

Additive

+-

Lefttoright

Shift

<<>>

Page 69: C Programming Language Quickstart Guide: Simplified Guide for Beginners

Lefttoright

Relational

<<=>>=

Lefttoright

Equality

==!=

Lefttoright

BitwiseAND

&

Lefttoright

BitwiseXOR

^

Lefttoright

BitwiseOR

|

Lefttoright

LogicalAND

&&

Lefttoright

LogicalOR

Page 70: C Programming Language Quickstart Guide: Simplified Guide for Beginners

LogicalOR

||

Lefttoright

Conditional

?:

Righttoleft

Assignment

=+=-=*=/=%=>>=<<=&=^=|=

Righttoleft

Comma

,

Lefttoright

Considerthefollowingcodeandtrytocomputetheresults.Wewilldiscusstheoutputbutitisbetterifyoutryityourselfbeforematchingourresults.

#include"iostream"

voidmain(void)

{

inta=20,b=10,c=5;

a=b=c+=2;

Page 71: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 72: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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.

Page 73: C Programming Language Quickstart Guide: Simplified Guide for Beginners
Page 74: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 75: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 76: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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.

Page 77: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 78: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 79: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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();

}

Page 80: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 81: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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;

Page 82: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 83: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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,

Page 84: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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");

Page 85: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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");

}

Page 86: C Programming Language Quickstart Guide: Simplified Guide for Beginners

}

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)

Page 87: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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.

Page 88: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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;

Page 89: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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();

Page 90: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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){…}

Page 91: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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;

Page 92: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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)

{

Page 93: C Programming Language Quickstart Guide: Simplified Guide for Beginners

{

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;

Page 94: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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';

Page 95: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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');

Page 96: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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++)

Page 97: C Programming Language Quickstart Guide: Simplified Guide for Beginners

{

printf("%d,",Two_D[i][j]);

}

}

system("pause");

}

Similarly,wecanusenestedloopsforawhileanddowhile.Youcannestdifferentloopstogetheraswell.

Decisionstatementsandloopsprovideflexibilitytotheprogrammertodevelopaprogramaccordingtohisunderstanding.Itleadstobetterdevelopmenttechniquesandencouragesprogrammertothinkofnewsolutionsinsteadofjustfollowingalreadyestablishedsolutions.

Page 98: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 99: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 100: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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);

Page 101: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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);

Page 102: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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.

Page 103: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 104: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 105: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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)

Page 106: C Programming Language Quickstart Guide: Simplified Guide for Beginners

{

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

Page 107: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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);}

Page 108: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 109: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 110: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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++)

Page 111: C Programming Language Quickstart Guide: Simplified Guide for Beginners

{

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:

Page 112: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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);

Page 113: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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();

Page 114: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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)

Page 115: C Programming Language Quickstart Guide: Simplified Guide for Beginners

{

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”

Page 116: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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++)

Page 117: C Programming Language Quickstart Guide: Simplified Guide for Beginners

{

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]);

Page 118: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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)

Page 119: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 120: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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)

Page 121: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 122: C Programming Language Quickstart Guide: Simplified Guide for Beginners

Iis1,andintegerisof4

bytes,theprogramaccessesthenextintegerratherthanjustnextbyte.

Now,wewillseeanexampleinwhichvaluesofanidentifierdefinedinourmainfunctionarechangedaftercallinganotherfunctionbypassingapointertoit.

voidchangeMe(int*p)

{

for(inti=0;i<10;i++)

{

p[i]=10;

}

}

voidmain(void)

{

inttable[10];

Page 123: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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");

}

Page 124: C Programming Language Quickstart Guide: Simplified Guide for Beginners

}

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

=

Page 125: C Programming Language Quickstart Guide: Simplified Guide for Beginners

=

"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");

Page 126: C Programming Language Quickstart Guide: Simplified Guide for Beginners

}

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++;

}

}

Page 127: C Programming Language Quickstart Guide: Simplified Guide for Beginners

}

}

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

Page 128: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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]

Page 129: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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];

Page 130: C Programming Language Quickstart Guide: Simplified Guide for Beginners

sum+=Three_D[i][j][k];

returnsum;

}

Page 131: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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:

Page 132: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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.

Page 133: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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;

Page 134: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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;

Page 135: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 136: C Programming Language Quickstart Guide: Simplified Guide for Beginners

“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

Page 137: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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.

Page 138: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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)

{

Page 139: C Programming Language Quickstart Guide: Simplified Guide for Beginners

{

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;

Page 140: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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];

Page 141: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

Page 142: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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();

Page 143: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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;

Page 144: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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

{

Page 145: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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;

Page 146: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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;

}

}

Page 147: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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.

Page 148: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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);}

Page 149: C Programming Language Quickstart Guide: Simplified Guide for Beginners

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);}

}

Page 150: C Programming Language Quickstart Guide: Simplified Guide for Beginners

}

elsereturn0;

}

Thesearchfunctionshownaboverecursivelymovesdownthetreeuntiliteitherreachesanodewithakeyvalueequaltothevalueforwhichthefunctionissearching.ThevaluebeingsearchedformaynotbestoredinthebinarytreeandhenceweandhencewemaintainaconditionwhensearchreachesanodewithNULLvalue,itisconcludedthatthekeyvalueleafisnotthereinthebinarytree.Itreturnsapointertothenodetothepreviousinstanceofthefunctionwhichcalledit.

Conclusion

Thebookisasimple,completeandquickreferenceforprogramminginC.Thebookpresentsthegeneralpurposelanguage,stepbystep.Itiswrittenfollowingaprogrammer’sapproachandisthereforeidealforusingasaquickguideandreferenceforpeoplewhoaimtocodeinC.

ThebookcoversallthebasicconceptsofprogrammingindetaillikeOperators,Functions,Pointers,Arrays,Strings,anddecisionmakingstatements.Thebookhastheflexibilitytohelpthereadersiftheyareinterestedinselectivestudy.Thechaptersarewrittenwithminimumpossibleinter-dependency.

Attheendofthebook,thereadermustbeanefficientprogrammerinCandwillbefamiliarwithfollowingconceptsofC:•Anoverviewofthelanguage

Page 151: C Programming Language Quickstart Guide: Simplified Guide for Beginners

befamiliarwithfollowingconceptsofC:•Anoverviewofthelanguage

•LexicalelementsofC

•Loops

•DecisionMakingstatements

•Arrays()

•Strings

•Pointers

•Functions

•Abstractdatatypes

•Stacks

•Queues

•Linkedlists

•BinaryTree

Ifyou’vefoundthebookhelpful,pleaseleaveareviewforitnow.AlsocheckoutmyotherbooksonKindle.

R.J.Khan

Page 152: C Programming Language Quickstart Guide: Simplified Guide for Beginners

CheckOutMyOtherBooks:

CProgrammingLanguageQuickStartGuide:SimplifiedGuideForBeginners

SCRUM:TheFastandSimplifiedGuideScrum–AgileProjectManagement(comingsoon)