Beruflich Dokumente
Kultur Dokumente
c
E-BOOK
Page 2 of 260
UNIT - 1
Introduction to Programming
Page 3 of 260
Introduction to programming
8/7/2015 scormcontent
Introduction
Problemdefinition:
Aproblemdefinitioninvolvestheclearidentificationoftheproblemintermsofavailableinput
parametersanddesiredsolution.
Approachtowardssolvingtheproblem:
Afteraproblemisidentified,theuserneedstoimplementastepbystepsolutionintermsof
algorithms.
Graphicalrepresentationofproblemsolvingsequence:
Thisstepinvolvesrepresentingthestepsofalgorithmpictoriallybyusingaflowchart.
Eachcomponentoftheflowchartpresentsadefiniteprocesstosolvetheproblem.
Convertingthesequenceinaprogramminglanguage:
Converting the graphical sequence of processes into a language that the user and the
computercanunderstandanduseforproblemsolvingiscalledprogramming.
After the program is compiled the user can obtain the desired solution for the problem by
executingthemachinelanguageversionoftheprogram.
Page 4 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit1/assets/2.html 1/1
Introduction to programming
8/7/2015 scormcontent
Algorithm
Asequentialsolutionofanyprogramthatwritteninhumanlanguage,calledalgorithm.
Algorithmisfirststepofthesolutionprocess,aftertheanalysisofproblem,programmerwrites
thealgorithmofthatproblem.
SampleAlgorithm
Algorithmtoreversethedigitsofaninteger
Everyproblemhassomeinputinformationandsomedesiredresultstobeobtained.
Theimportantaspectistodetermineiftheinformationavailableisreallysufficienttosolvethe
problem at hand, and if it is so what are the procedures that should be applied to the given
informationordatasothattherequiredresultcanbeobtained.
Thedevelopmentofaproperproceduretosolvetheproblemiscalledanalgorithm.
Page 5 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit1/assets/3.html 1/3
Introduction to programming
8/7/2015 scormcontent
The operations that can be included in an algorithm are constrained by the possibility of a
computercarryingthemout.
Eachoperationmustbeunambiguousabouttheprocesstosolvetheproblem.
Thestepsintheprocessmustbeeffectiveenoughtobetheoreticallydoneinafiniteamountof
timeandmemory.
Analgorithmterminatesinareasonablyshorttime.
SampleAlgorithm:
Gotobusstop.
Catchbusno.M7B.
Purchaseaticket.
Getdownatthemarketbusstop.
ExampleofAlgorithm
Findoutnumberisoddoreven
Whatispseudocode?
PseudocodeisasimplewayofwritingprogrammingcodeinEnglish.
Pseudocodeisnotanactualprogramminglanguage.
Pseudocodeshouldnotincludekeywordsinanyspecificcomputerlanguage.
Itshouldbewrittenasalistofconsecutivephrases.
The user should not use flowcharting symbols but he can draw arrows to show looping
processes.
Page 6 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit1/assets/3.html 2/3
Introduction to programming
8/7/2015 scormcontent
Indentationcanalsobeusedinpseudocodetoshowthelogic.
The purpose of using pseudo code is that it is easier for humans to understand than
conventionalprogramminglanguagecode,andthatitisacompactandlanguageindependent
descriptionofthekeyprinciplesofanalgorithm.
Pseudocodeisusedtoquicklydrawtheoutlineofaprogram.
Itcanuseanyhumanlanguage.
Exampleofpseudocode:
Thisispseudocode.
Itwouldnotworkifyouranitthroughaccompiler,butitexplainsthestructureofthecodeand
howusersareplanningtoimplementit.
Page 7 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit1/assets/3.html 3/3
Introduction to programming
8/7/2015 scormcontent
Whatisaflowchart?
Aflowchartisapictorialrepresentationofthestepsthatareinvolvedintheprocedure.
Aflowchartalsoshowsthelogicalsequenceinwhichthestepsaretobeperformed.
Aflowchartconsistsofboxescalledthesymbolsandarrowscalledtheflowlines.
Theboxdepictstheprocessandtheflowlineindicatesthenextsteptobeperformed.
Elementsofaflowchart
TerminalBox
Thissymbolisusedtoindicatethebeginningortheendofaflowchart.
WhenthissymbolisusedforSTART,noflowlinescanenterit.
Onlyoneflowlinecanleavethisbox.
When the terminal box is used for STOP, no flow lines can leave this box and any number of
flowlinescanenterthisbox.
TherecanbeonlyoneSTARTsymbolineachflowchart.
HowevertherecanbemorethanoneSTOPsymbolinaflowchart.
ProcessBox
Page 8 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit1/assets/4.html 1/3
Introduction to programming
8/7/2015 scormcontent
Theshapeoftheprocessingboxisarectangle.
This symbol represents one or more instructions that perform a processing function in a
program.
Input/outputBox
Theinput/outputboxisrepresentedbyaparallelogram.
Thissymbolindicatesanyfunctionofaninput/outputdevicesuchaskeyboardorprinter.
Aninput/outputboxmakesdataavailableforprocessingordisplaystheresultofprocessingon
thescreen.
DecisionBox
Theshapeofadecisionboxisarhombus.
Thisboxisusedwhentwoquantitiesneedtobecompared.
Thedecisionboxisalsousedforatestingcondition.
Decisionboxresultsintwoalternativeanswerstothecondition:trueorfalse.
The equality, less than, less than or equal to, greater than, greater than or equal to, and not
equaltooperatorscanbeusedinthedecisionbox.
ExampleofAlgorithmandflowchartforsameproblems
Algorithmforcalculatefactorialvalueofanumber:
Page 9 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit1/assets/4.html 2/3
Introduction to programming
8/7/2015 scormcontent
Flowchartforcalculatefactorialvalueofanumber
Page 10 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit1/assets/4.html 3/3
Introduction to programming
8/7/2015 scormcontent
ProgramminglanguageIntroduction
Aprogramminglanguageisasetofsymbols,grammarsandruleswiththehelpofwhichoneis
abletotranslatealgorithmstoprogramsthatwillbeexecutedbythecomputer.
Theprogrammercommunicateswithamachineusingprogramminglanguages.
There are many different classifications of programming languages and these programming
languagesdifferintheirclosenesstothemachineandinthewaytheyarestructured.
Mostoftheprogramshaveahighlystructuredsetofrules.
Theprimaryclassificationsofprogramminglanguagesare:
MachineLanguages.
AssemblyLanguages.
HighlevelLanguages.
MachineLevelLanguage
Machinelanguageisacollectionofbinarydigitsorbitsthatthecomputerreadsandinterprets.
Machinelanguageistheonlylanguageacomputeriscapableofunderstanding.
Machine level language is a language that supports the machine side of the programming or
doesnotprovidehumansideoftheprogramming.
Itconsistsof(binary)zerosandones.
Amachinelevellanguageisthelowestformofcomputerlanguage.
Eachinstructioninaprogramisrepresentedbyanumericcode,andnumericaladdressesare
usedthroughouttheprogramtorefertomemorylocationsinthecomputersmemory.
All book keeping aspects of the program are the sole responsibility of the machinelanguage
programmer.
Finally,alldiagnosticsandprogrammingaidsmustbesuppliedbytheprogrammer.
Also included as machinelevel programs are programs written in microcode (i.e., micro
programs).
Microcodeallowsfortheexpressionofsomeofthemorepowerfulmachinelevelinstructionsin
termsofasetofbasicmachineinstructions.
Eachcomputerhasonlyoneprogramminglanguagewhichdoesnotneedatranslatingprogram
themachinelanguage.
Machinelanguageprograms,thefirstgenerationprograms,arewrittenatthemostbasiclevelof
computeroperation.
Page 11 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit1/assets/5.html 1/5
Introduction to programming
8/7/2015 scormcontent
Because their instruction are directed at this basic level of operation, machine language and
assemblerlanguagearecollectivelycalledlowlevellanguage.
Inmachinelanguage,instructionarecodedasaseriesofonesandzeroes.
Themachinelanguageprogramsarecumbersomeanddifficulttowrite.
Themachinelanguageisnativetothatmachineandunderstooddirectlybythemachine.
Themachinelanguagegenerallyhastwoparts:
Opcode Operand
Theopcodeofmachinelanguagetellswhatfunctiontoperformtothecomputer.
Theoperandgivesthedataonwhichtheoperationhastobeperformedorthelocationwhere
thedatacanbefound.
Advantages
Machinelevelinstructionsaredirectlyexecutable.
Machinelevellanguagemakesmostefficientuseofcomputersystemresourceslikestorage
andregister
Machinelanguageinstructioncanbeusedtomanipulateindividualbits.
Asthemachineinherentlyunderstandsmachineinstruction,machinelanguagesareveryfast.
Disadvantages
Difficulttoprogram:Programminginmachinelanguageisthemostdifficultkindofprogramming.
Instruction should be encoded as a sequence of incomprehensible 0s and 1s which is very
difficult.
Errorprone:Inmachinelanguage,theprogrammerhastolookintoalltheactivitieslikememory
management, instruction cycle, etc., which diverts his attention from the actual logic of the
program.Thisfrequencyleadstoerror.
Machine dependent: Every computer is different from one another in its architecture. Hence,
instructionsofonemachinewillbedifferentfromtheother.
As machine level language are device dependent, the programs are not portable from one
computertoanother.
Programminginmachinelanguageusuallyresultsinpoorprogrammerproductivity.
Programsinmachinelanguagearemoreerrorproneanddifficulttodebug.
Computerstoragelocationmustbeaddressdirectly,notsymbolically.
Machine language requires a high level of programming skill, which increases programmer
Page 12 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit1/assets/5.html 2/5
Introduction to programming
8/7/2015 scormcontent
trainingcosts.
AssemblyLevelLanguage
A set of instructions for an assembly language is essentially onetoone with those of machine
language.
Likemachinelanguage,assemblylanguageareuniquetoacomputer.
The big difference is that instead of a cumbersome series of ones and zeroes, assembly
languagesuseeasilyrecognizablesymbolscalledmnemonics,torepresentinstructions.
As said before, machine language and assembly language are lowlevel languages and are
dependentonparticularmachinearchitecture.
Theyaremoreclosetothemachineratherthantheprogrammer.
The only difference between assembly language and machine language is that assembly
languageisrelativelyeasiertousethanmachinelanguage.
Inapureassemblylanguage,eachstatementproducesexactlyonemachineinstruction(oneto
onecorrespondencebetweenmachineinstructionsandstatementsinassemblylanguage).
Soanonlineassemblylanguagewillproduceannwordmachinelanguageprogram.
Assemblylanguagewhichusesmnemoniccodesiseasierthanmachinelanguageusingbinary
orhexadecimalcodes.
ItiseasiertorememberADD,SUB,MUL,orDIV,thantheircorrespondingnumericalvaluesin
machinelanguage.
Assemblylanguageusessymbolicnamesformemorylocationswhilemachinelanguageneeds
numericalvalues.
Theassemblylanguagecandirectlytestifthereisanoverflowbitwhileahigherlevellanguage
cannot.
An assembly language can only run on one family of machines (each machine has its own
assemblylanguage)whileahigherlevellanguagecanrunonmanymachines.
Advantages
Assemblylanguageiseasiertousethanmachinelanguage.
Anassemblerisusefulfordetectingprogrammingerrors.
Programmersdonothavetheabsoluteaddressofdataitems.
Assemblylanguageencouragemodularprogramming.
Disadvantages
Assemblylanguageprogramsarenotdirectlyexecutable.
Page 13 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit1/assets/5.html 3/5
Introduction to programming
8/7/2015 scormcontent
Assemblylanguagearemachinedependentand,therefore,notportablefromonemachine
toanother.
Programminginassemblylanguagerequiresahigherlevelofprogrammingskill.
HighLevelLanguage
High level language is a language that supports the human and the application sides of the
programming (typical features: ability to logic structuring of the algorithm, crossplatform
independence).
Alanguageisamachineindependentwaytospecifythesequenceofoperationsnecessaryto
accomplishatask.
Alanguagecanbedesignedtobeexpressinaconciseway,acommonsequenceofoperations.
A line in a high level language can execute powerful operations, and correspond to tens, or
hundreds,ofinstructionsatthemachinelevel.
Although many programmers prefer assembly language, because it works more efficiently, the
powerandflexibilityofnewgenerationlanguageshaveputthembeyondlowlevellanguagesin
termsofbothhumanandcomputerefficiency.
Consequentlymoreprogrammingisnowdoneinhighlevellanguages.
ExamplesofhighlevellanguagesareBASIC,FORTRANetc.,
Highlevel languages are more, like English statements, which are easy to understand and to
use.
Highlevellanguagesaremoreclosetotheprogrammerandeasethetaskofprogramming.
Higherlevel languages provide a richer set of instructions and support, making the
programmerslifeeveneasier.
YetbeforeahighlevelprogramcanbeexecutedonagivenCPU,itmustbetranslatedbackto
machinecode.
AprogramminglanguagesuchasC,FORTRAN,orPascalthatenablesaprogrammertowrite
programsthatismoreorlessindependentofaparticulartypeofcomputer.
Such languages are considered highlevel because they are closer to human languages and
furtherfrommachinelanguages.
In contrast, assembly languages are considered lowlevel because they are very close to
machinelanguages.
Featuresofhighlevellanguages
Highlevellanguagesareeasilyunderstandable.
Theprogramsthataredevelopedinhighlevellanguageareportable.
Page 14 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit1/assets/5.html 4/5
Introduction to programming
8/7/2015 scormcontent
In case of high level languages debugging of the code is easy and the program written is not
machinedependent.
Advantagesofhighlevellanguagesinclude
Easiertoprogram.
The programmer can concentrate on the logic of the program rather than on the register,
portsandmemorystorage.
Machineindependent.
Provided some other machine has the same compiler and libraries, the program can be
portedacrossvariousplatforms.
Easymaintenance.
Aprograminahighlevellanguageiseasiertomaintainthanassemblylanguage,becauseit
iseasiertocodeandlocatebugsinhighlevellanguages.
Easytolearn.
Thelearningcurveforhighlevellanguagesisrelativelysmooththanlowlevellanguages.
Otherthanthis,highlevellanguagesaremoreflexibleandcanbeeasilydocumented.
Page 15 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit1/assets/5.html 5/5
Introduction to programming
8/7/2015 scormcontent
Compilation
The compiler program translates the instructions of a highlevel language to a machine level
language.
Aseparatecompilerisrequiredforeveryhighlevellanguage.
High level language is simply a programmers convenience and cannot be executed in their
source.
Theactualhighlevelprogramiscalledasourceprogram.
It is compiled (translated) to machine level language program called object program for that
machinebythecompiler.
Suchcompilersarecalledselfresidentcompilers.
Compilercompilesthefullprogramandreportstheerrorsattheend.
Whatis"compilation?
Thecompileristhetooltoconvertaprogramwritteninahighlevellanguageintothesequence
ofmachineinstructionsrequiredbyaspecificcomputertoaccomplishthetask.
Userstypicallycontroldetailsoftheoperationofcompilersbymeansofoptionssuppliedonthe
commandline,ordirectivesembeddedintheprogramsource,buttheyseldomneedtoexamine
theresultingmachinelanguagecode.
Thisprocessofconvertinghighlevellanguagetomachineleveliscalledcompilation.
Thetranslationofsourcecodeintoobjectcodebyacompiler.
CompilationProcess
ThecompilationandexecutionprocessofCcanbedividedintomultiplesteps:
PreprocessingUsingaPreprocessorprogramtoconvertCsourcecodeinexpandedsource
code. "#include" and "#define" statements will be processed and replaced actually source
codesinthisstep.
CompilationUsingaCompilerprogramtoconvertCexpandedsourcetoassemblysource
code.
AssemblyUsingaAssemblerprogramtoconvertassemblysourcecodetoobjectcode.
LinkingUsingaLinkerprogramtoconvertobjectcodetoexecutablecode.Multipleunitsof
objectcodesarelinkedtotogetherinthisstep.
LoadingUsingaLoaderprogramtoloadtheexecutablecodeintoCPUforexecution.
Page 16 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit1/assets/6.html 1/2
Introduction to programming
8/7/2015 scormcontent
Page 17 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit1/assets/6.html 2/2
Introduction to programming
8/7/2015 scormcontent
LinkingandLoading
Whatis"linking"?
Afterallofthefilesarecompiled,theymustbe"mergedtogether"toproduceasingleexecutable
filethattheuserusetoruntheprogram.
In C, most compiled programs produce results only with the help of some standard programs,
knownaslibraryfilesthatresideinthecomputer.
Thisprocessiscalledlinking.
Theresultobtainedafterlinkingiscalledtheexecutablefile.
Tobuildanexecutablefile,thelinkercollectsandlibraries.
Thelinkersprimaryfunctionistobindsymbolicnamestomemoryaddresses.
Todothis,itfirstscansthefilesandconcatenatestherelatedfilesectionstoformonelargefile.
Then, it makes a second pass on the resulting file to bind symbol names to real memory
addresses.
Linkingistheprocessoftakingsomesmallerexecutableandjoiningthemtogetherasasingle
largerexecutable.
Loadingisloadingtheexecutableintomemorypriortoexecution.
Therearetwotypesoflinking:
Staticlinking.
Dynamiclinking.
Staticlinkingoccursatcompilationtimehenceitoccurspriortoloadingaprogram.
Withstaticlinkingtheexternalsymbolsthatareusedbytheprogram(e.g.functionnames)are
resolvedatcompiletime.
Dynamiclinkingoccursatruntime,soitoccursafteroratthetimeoftheloadingofaprogram.
With dynamic linking the symbols are resolved either at loading time, or at run time when the
symbolisaccessed(lazybinding).
Whatis"loading?
Afterthefilesarecompiledandlinkedtheexecutablefileisloadedinthecomputersmemoryfor
executingbytheloader.
ThisprocessiscalledLoading.
Programloadingisbasicallycopyingaprogramfromsecondarystorageintomainmemorysoit
sreadytorun.
Page 18 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit1/assets/7.html 1/2
Introduction to programming
8/7/2015 scormcontent
In some cases, loading us just not copying the data from disk to memory, but also setting
protectionbits,orarrangingforvirtualmemorymapvirtualaddressestodiskpages.
Page 19 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit1/assets/7.html 2/2
Introduction to programming
8/7/2015 scormcontent
TestingandDebugging
Testinginvolvesfindingproblemsinthecode.WhatdoesoneTestfor?
CompilationErrors.
Syntax errors: The compiler cannot understand users program because it does not follow the
syntax.
Commonsyntaxerrorsare:
Missingormisplacedor}
Missingreturntypeforaprocedure.
Missingorduplicatevariabledeclarations.
Typeerrors
These errors include type mismatch when the user assign a value to a variable and type
mismatchbetweenactualandformalparameters.
RuntimeErrors
Outputerrors:Theseerrorsresultwhentheprogramrunsbutproducesanincorrectresult.
Anoutputerrorindicatesanerrorinthemeaningorlogicoftheprogram.
Exceptions:Theseerrorsoccurwhentheprogramterminatesabnormally.
Examples include division by zero and out of memory. Exceptions indicate an error in the
semanticsorthelogicofaprogram.
Nonterminationerrors
Theseerrorsoccurwhentheprogramdoesnotterminateasexpected,butcontinuesrunning
endlessly.
Debuggingconsistsofisolatingandfixingtheproblems.
Testing and debugging are necessary stages in the development cycle, and they are best
incorporatedearlyinthecycle.
Thoroughly testing and debugging individual components makes testing and debugging
integratedapplicationsmucheasier.
Page 20 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit1/assets/8.html 1/1
Introduction to programming
8/7/2015 scormcontent
WhatisDocumentation?
Documentationofaprogramconsistsofwrittendescriptionofprogramsspecification,itsdesign,
coding,operatingproceduresetc.
Documentationcanbebroadlyclassifiedintotwotypes:
Documentationforusers.
Documentationformaintenanceprograms.
The written text and comments that make a program easier for others to understand use and
modify.
Thecompilerinthecompilationprocessignorescomments.
Itprovidesinformationaboutthestepsandprocedures.
Page 21 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit1/assets/9.html 1/1
UNIT - 2
Algorithms for Problem Solving
Page 22 of 260
8/7/2015 scormcontent
ExchangingValuesofTwoVariables
Problemdefinition:Exchangingvaluesoftwovariables.
Analysis:Twovariablesxandycontainstwodifferentvalues.
Swapthevaluesofxandysuchthatxhasysvalueandyhasxsvalue.
Solving by example: Let us consider two variables x and y,containing values 8 and 20
respectively.
Theoriginalvaluesofxandyare:
Therequirementisoncethealgorithmisperformed,theresultsshouldbe
Ifyouthinkbyjustsaying,
x=yy=x
Thevaluegetsswapped,thenyouaremistaken.
Theseinstructionareatomicinnatureandhencex=ymeansthatthevalueofxislost.
So,wehavetouseatemporaryvariable,temptostorethevalueofx.
Page 23 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/2.html 1/2
8/7/2015 scormcontent
Thevalueofxandyisswapped.
AlgorithmDefinition
ExampleProgram:Toexchangethevaluesoftwovariablesusinga
temporaryvariable
Page 24 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/2.html 2/2
8/7/2015 scormcontent
SummationofaSetofNumbers
ProblemDefinition:Summationofasetofnumbers.
ProblemAnalysis:Givenalistofnnumbers,thealgorithmshouldaddupthennumberstofind
thesumofthesevalues.
SolvingbyExample:Consideralistof5numbers.
Thealgorithmtakesthesenumbersasinputandshouldproducetheoutputas47.
AlgorithmDefinition
ToSummationofasetofnumbers
Page 25 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/3.html 1/2
8/7/2015 scormcontent
Page 26 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/3.html 2/2
8/7/2015 scormcontent
DecimalBasetoBinaryBaseConversion
ProblemDefinition:Decimaltobinarybaseconversion.
ProblemAnalysis:Anumberwithbasenwillcontaindigitsfrom0ton1.
Hencedecimalbasesystemis10.
Weuseinournormalcontainingdigitsfrom09.
Forexample,922 10 isanumberwithbase10.
Abinarynumbersystemhasabase2.
Henceitusesjusttwonumbersi.e.0and1.
Thecomputersystemstoresinformationinthebinarynumbersystem.
Theconversionofdecimalnumbertobinarynumberisdonebydividingthedecimalnumberby
2repeatedlyandbyaccumulatingtheremaindersobtained,tillthequotientbecomeszero.
Thereverseoftheaccumulatedremaindersisthebinary,equivalentthedecimalnumber.
SolvingbyExample:Considerthedecimalnumber(18) 10
Hence(18) 10 equivalentto(10010) 2 .
AlgorithmDefinition
Page 27 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/4.html 1/2
8/7/2015 scormcontent
Toconvertanumberfromdecimalbasetobinary
Page 28 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/4.html 2/2
8/7/2015 scormcontent
ReversingDigitsofanInteger
ProblemDefinition:Reversingthedigitofaninteger.
Problem Analysis: Given a integer number, abcd (say 1234where a=I, b=2andso on), the
algorithmshouldconvertthenumbertodcba.
SolvingbyExample:Consideranintegernumber7823.
The reverse of an integer number is obtained by successively dividing the integer by 10 and
accumulatingtheremainderstillthequotientbecomeslessthan10.
Theremainderofadivisionoperationcanbefoundoutbythemodfunction.
Accumulated Quotient
7823Mod10 3 782
782Mod10 32 78
78Mod10 328 7
7Mod10 3287 0
AlgorithmDefinition
Toreversethedigitsofaninteger
Page 29 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/5.html 1/2
8/7/2015 scormcontent
Page 30 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/5.html 2/2
8/7/2015 scormcontent
GCD(GreatestCommonDivision)ofTwoNumbers
ProblemDefinition:TofindtheGreatestCommonDivisor(GCD)oftwonumbers.
ProblemAnalysis:GCDoftwonumbersisthegreatestcommonfactorofthegiventwonumbers.
GCD of two numbers is obtained using the following method: Divide the larger of the two
numbersbythesmallerone.
Dividethedivisorbytheremainder.
Repeatthisprocesstilltheremainderbecomeszero.
ThelastdivisoristheGCDofthetwo.
SolvingbyExample:Considertwonumbers188and423.
Thesmallernumberis188.Thereforedivide423by188.
Step1
47(Remainder)becomesthedivisorand188(Divisor)becomesthedividend.
Step2
Sincetheremainderhasbecomezero,47istheGCDof188and423.
AlgorithmDefinition
Page 31 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/6.html 1/2
8/7/2015 scormcontent
TocomputeGreatestCommonDivisor(GCD)oftwonumbers
Page 32 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/6.html 2/2
8/7/2015 scormcontent
TestWhetheraNumberisPrime
ProblemDefinition:Toverifywhetheranintegerisprimeornot.
ProblemAnalysis:Primenumberisanintegerwhichisexactlydivisibleby1anditself.
Forexample,17isaprimenumberbecause1and17aretheonlytwofactorsof17.
Generalizingthis,apositiveintegerwithjusttwofactorsisaprimenumber.
Examplesofprimenumbersare2,3,5,7,11,13,......
Toverifywhetheranumber(say)isprimeornot,dividethenumberby2ton1.
If the remainder is zero in any of the cases, then the number is not prime (such numbers are
calledcomposite).
Mathematically,itisalsoenoughtodividethenumberfrom2ton
SolvingbyExample:Letustaketwonumbers37and49.
Consider37first.Thesquarerootof37is6(approximately).
Now,divide37by2,3,4,5and6.
Noneofthedivisionoperationgivesaremainderofzero.
Hence,37isaprimenumber.Now,letusconsider49.
Thesquarerootof49is7.Soletusdivide49by2,3,4,5,6and7.
As49isdivisibleby7,itisnotaprimenumbers.
AlgorithmDefinition
Tocheckifthegivennumberisprime
Page 33 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/7.html 1/2
8/7/2015 scormcontent
Page 34 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/7.html 2/2
8/7/2015 scormcontent
OrganizeNumbersinAscendingOrder
ProblemDefinition:Organizeagivensetofnumbersinascendingorder.
Algoritham
Selectionsortinvolvesidentifyingthesmallestnumberinthearrayofnumbersandplacingitin
thetopofthelist.
Thenthesecondsmallernumberisidentifiedandplacedsecondthelist.
Thisprocesscontinuesfornnumber.
SolvingbyExample:Considerthegivenarray.
Identifythesmallerelementinthearray,theelementatposition3isthesmallest.
Swaptheelementsatposition1andposition3.Thearraybecomes.
Page 35 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/8.html 1/4
8/7/2015 scormcontent
Identifythesecondsmallestnumberatposition5.
Swaptheelementsatposition2andposition5.
Varioussnapshotsofthesortingprocessisgivenbelow:
Page 36 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/8.html 2/4
8/7/2015 scormcontent
Page 37 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/8.html 3/4
8/7/2015 scormcontent
Toorganizenumbersinascendingorder
Page 38 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/8.html 4/4
8/7/2015 scormcontent
FindSquareRootofaNumber
ProblemDefinition:Findthesquarerootofaninteger.
ProblemAnalysis:Squarerootofagivennumbernisthatnaturalnumberwhichwhenmultiple
byitselfproducesaproductn.
Forexample,
2*2=4,so2isthesquarerootof
3*3=9,so3isthesquarerootof
So,ifmisasquarerootofn,thenitcanbederivedthatm*m=nanditissymbolicallydenotedby
n=m,
SolvingbyExample:Therearetwowaysoffindingthesquarerootofanumber.
The first one is the trialanderror method where we can zero upon the square root by
multiplying different numbers to itself and deciding on the number which produces the nearest
result.
Anothermethodisabitcomplicated.Forexample,letusconsideraninteger625.
Now,placeabarovereverypairofdigitsstartingfromtheright.
Thenumbersofbarsindicatethenumberofdigitsinthesquareroot.Wecandivide625as
Now,findthelargestsquarerootofthefirstpairwhichisequaltoorlessthanthefirstpair.
Takethesquarerootofthisnumberasdivisorandderivethequotient.
Subtractthefirstpairofnumbersandbringthenextperioddown.
Now, double the quotient as it appears and leaves a blank digit to the right. This is the next
divisor.
Page 39 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/9.html 1/2
8/7/2015 scormcontent
The blank digit should be selected in such a way that multiplying the digit with the number
formedasthedivisorshouldbelessthanequaltoorthedividend,Forexample,here46*6=
276isgreaterthan225.
Hence, we select 5 as the digit which satisfies our condition (45* 5=225). Put the digit to the
quotient.
Hencethesquarerootsof625.
ToFindsquarerootofanumber
Page 40 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/9.html 2/2
8/7/2015 scormcontent
FactorialComputation
Tocomputefactorialofagivennumber:
Input:GiventheNumbertobecomputed=>N.
Output:FactorialofNisFact.
Step1:InputNumberwhoseFactorialistobecomputed:N.
Step2:InitializeFact=1.
AssignN=M.
Step3:CheckifMisgreaterthan1.
Yes:AssignproductofFactandMtoFact.
DecrementM.RepeatStep3.
No:OutputFactorialofNisFact.
Step4:Stop.
Tocomputefactorialofagivennumber
Page 41 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/10.html 1/1
8/7/2015 scormcontent
FibonacciSequence
Algorithm:FibonacciSeries
ToGenerateFibonacciSeriesforgivenrange
Page 42 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/11.html 1/2
8/7/2015 scormcontent
Page 43 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/11.html 2/2
8/7/2015 scormcontent
EvaluatesinxasSumofaSeries
Input:Numberwhosesinefunctionistobecomputed:X.
Numberofiterationstobecarriedout:N.
Output:SineofthegivenNumber
Step1:Input:Numberwhosesinefunctionistobecomputed:X.
Numberofiterationstobecarriedout:N.
Step2:InitializeSum=0.
Den=1.
Step3:IfNisEqualtoOne(1),
Yes:OutputSin(x)isX.
No:Step4.
Step4:InitializeFlag=1.
Fact=1
AssignX=Y.
Step 5: Add Sum to flag multiplied by X divided by Fact and assign to sum: (Sum = (Flag *
X)/Fact).
AssigntheproductofXandtheSquareofYtoX:(X=X*Y^2).
Negatethesignoftheflag.
Compute the product of Fact, Den and Den+1 and assign to Fact: (Fact = Fact*Den*
(Den+1)).
IncrementDenby2.
DecrementNby1.
RepeatStep5Ntimes.
Step6:OutputtheSum.
ToEvaluatesinxasSumofaSeries
Page 44 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/12.html 1/2
8/7/2015 scormcontent
Page 45 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/12.html 2/2
8/7/2015 scormcontent
ReverseOrderofElementsofanArray
Iterativeway
Initializestartandendindexes
start=0,end=n1
Inaloop,swaparr[start]witharr[end]andchangestartandendasfollows.
start=start+1,end=end1.
Recursionway
Initializestartandendindexes
start=0,end=n1.
Swaparr[start]witharr[end].
Recursivelycallreverseforrestofthearray.
Forexampleifaisanarrayofintegerswiththreeelementssuchthat
a[0]=1
a[1]=2
a[2]=3
Thenonreversingthearraywillbe
a[0]=3
a[1]=2
a[0]=1
ToReverseOrderofElementsofanArray
Page 46 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/13.html 1/2
8/7/2015 scormcontent
Page 47 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/13.html 2/2
8/7/2015 scormcontent
FindLargestNumberinArray
ProblemStatement
DesignanalgorithmtofindmaximumvalueamongasetofNnumbers.
Solution
AlgorithmName:SearchMax(A,N,R).
Input:AisanarraycontainsN(>=0)numberofrealnumbers.
Output:RwillholdtheindexofthefirstmaximumvalueinthethearrayA.
Step1:R=0.
Step2:i=1.
Step3:WHILE(i<N)
IF(A[i]>A[R])Then
R=i
EndIf
i=i+1
EndWhile.
Step4:Return.
ToFindLargestNumberinArray
Page 48 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/14.html 1/1
8/7/2015 scormcontent
PrintElementsofUpperTriangularMatrix
Input:TheSquareMatrixoflengthN.
Output:TheUpperTriangleMatrix.
Step1:InputTheOrderoftheMatrix:mxn.
Step2:InputTheElementsoftheMatrixA[I,J].
Step3:Initializei,j.
Step4:Checkifi<rowsandincrementi(i++).
Step5:Checkifj<columnandincrementj(j++).
Printa[i][j].
Stop.
ToPrintElementsofUpperTriangularMatrix
Page 49 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/15.html 1/1
8/7/2015 scormcontent
MultiplicationofTwoMatrices
GiventwomatricesAandBofordersm*nandp*qrespectively.
ThisalgorithmmultipliesthetwomatricesandstorestheresultinmatrixCoforderm*qI,J,K
denotesarrayindices.
Algorithmofmultiplicationoftwomatrices
Input:Twomatrixes.
Output:OutputmatrixC.
MatrixMultiply(A,B)
ifcolumns[A]rows[B]
thenerror"incompatibledimensions"
else
fori=1torows[A]
forj=1tocolumns[B]
C[i,j]=0
fork=1tocolumns[A]
C[i,j]=C[i,j]+A[i,k]*B[k,j]
returnC.
AlgorithmDescription
Tomultiplytwomatrixessufficientandnecessaryconditionis"numberofcolumnsinmatrixA=
numberofrowsinmatrixB".
LoopforeachrowinmatrixA.
LoopforeachcolumnsinmatrixBandinitializeoutputmatrixCto0.
ThisloopwillrunforeachrowsofmatrixA.
LoopforeachcolumnsinmatrixA.
MultiplyA[i,k]toB[k,j]andaddthisvaluetoC[i,j].
ReturnoutputmatrixC.
Page 50 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/16.html 1/1
8/7/2015 scormcontent
EvaluateaPolynomial
Thepolynomialequationformulais
HereissourcecodeoftheCprogramtoevaluatethegivenpolynomialequation.
Page 51 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/17.html 1/2
8/7/2015 scormcontent
Page 52 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit2/assets/17.html 2/2
UNIT - 3
Introduction to C Language
Page 53 of 260
Introduction to C Language
8/7/2015 scormcontent
HistoryofC
C was invented and first implemented by Dennis Ritchie on DEC PDP11 that used the UNIX
operatingsystem.
CistheresultofadevelopmentprocessthatstartedwithanolderlanguagecalledBCPL.
BCPL was developed by Martin Richards, and it influenced a language called B, which was
inventedbyKenThompson.
BledtodevelopmentofCinthe1970.
To alter this situation, ANSI established a committee in the beginning of 1983 to create a
standardforC,whichwasimplementedin1987.
Page 54 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/2.html 1/1
Introduction to C Language
8/7/2015 scormcontent
ASCIICode
ASCIIisanacronymfortheAmericanStandardCodeforInformationInterchange.
ASCII is a code for representing English characters as numbers, with each letter assigned a
numberfrom0to127.
Forexample,theASCIIcodeforuppercaseMis77.
MostcomputersuseASCIIcodestorepresenttext,whichmakesitpossibletotransferdatafrom
onecomputertoanother.
TextfilesstoredinASCIIformataresometimescalledASCIIfiles.
TexteditorsandwordprocessorsareusuallycapableofstoringdatainASCIIformat,although
ASCIIformatisnotalwaysthedefaultstorageformat.
Mostdatafiles,particularlyiftheycontainnumericdata,arenotstoredinASCIIformat.
ExecutableprogramsareneverstoredinASCIIformat.
ThestandardASCIIcharactersetusesjust7bitsforeachcharacter.
There are several larger character sets that use 8 bits, which gives them 128 additional
characters.
The extra characters are used to represent nonEnglish characters, graphics symbols, and
mathematicalsymbols.
CharacterSet:Whatisacharacterset?
Acharactersetisthemappingofcharacterstobinaryvalues.
In8bitcharactersets,thevaluesrangefrom0255andonecharacterwillbemappedtoeachof
thesevalues.
Thismeansthatiftheusersterminalissettosupportaparticularcharacterseteverytimehe
pressacertainkeyoracombinationofkeysacorrespondingcharacterwillbeinvoked.
ASCIICharacterSet
Page 55 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/3.html 1/2
Introduction to C Language
8/7/2015 scormcontent
CCharacterSet
ThesearethecharactersthatCrecognizes.
Letters(uppercaseandlowercase)
ABCDEandsoon.
abcdeandsoon.
Digits
0123andsoon.
SpecialCharacters(punctuationetc),space(alsoknownasblank)
()*+/:=!&$<>%?,.#@{}[]\|
Page 56 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/3.html 2/2
Introduction to C Language
8/7/2015 scormcontent
VariablesandIdentifiers
Variables
Avariableisanameddatastoragelocationinusercomputersmemory.
Byusingavariablesnameintheprogram,theusersare,ineffect,referringtothedatastored
there.
Forexample:
Age=10impliesthatageholdthevalue10.
Age=20nowimpliesthatageholdthevalue20.
Sofromtheaboveexampleagechangeditsvaluefrom10to20.
Henceagecanbereferredtoasavariable.
Identifier
In C the names that are used to reference variables, functions, labels and various other user
definedobjectsarecalledidentifiers.
ThelengthofanidentifierinCcanvaryfromonetoseveralcharacters.
Inmostcasesthefirstcharactermustbealetteroranunderscore,andsubsequentcharacters
canbealetter,numberoranunderscore.
Identifiersareusedextensivelyinvirtuallyallinformationprocessingsystems.
Naming entities makes it possible to refer to them, which is essential for any kind of symbolic
processing.
VariableNames
TousevariablesintheuserCprogram,hemustknowhowtocreatevariablenames.
InC,variablenamesmustadheretothefollowingrules:
Thenamecancontainletters,digits,andtheunderscorecharacter(_).
The first character of the name must be a letter. The underscore is also a legal first
character,butitsuseisnotrecommended.
Casematters(thatis,upperandlowercaseletters).Thus,thenamescountandCountrefer
totwodifferentvariables.
C keywords cant be used as variable names. A keyword is a word that is part of the C
language.
VariableNameLegality
Page 57 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/4.html 1/2
Introduction to C Language
8/7/2015 scormcontent
ThefollowinglistcontainssomeexamplesoflegalandillegalCvariablenames:
VariableName Legality
Percent Legal
y2x5_fg7h Legal
annual_profit Legal
_1990_tax Legalbutnotadvised.
saving#account Illegal:Containtheillegalcharacter#.
double Illegal:IsaCKeyword.
9winter Illegal:Firstcharacterisadigit.
Usinganunderscoretoseparatewordsinavariablenamemakesiteasytointerpret.
Thesecondstyleiscalledcamelnotation.
Insteadofusingspaces,thefirstletterofeachwordiscapitalized.
Insteadofinterestrate,thevariablewouldbenamedInterestRate.
Camel notation is gaining popularity, because its easier to type a capital letter than an
underscore.
Weusetheunderscorebecauseitseasierformostpeopletoread.
Usershoulddecidewhichstyle,hewantstoadopt.
Page 58 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/4.html 2/2
Introduction to C Language
8/7/2015 scormcontent
BuiltinDataTypes
Datatype
Twotypesofbuiltindatatypes:
Fundamentaldatatypes(int,char,double,float,void,pointer).
Deriveddatatypes(array,string,structure).
Itisawayofrepresentingdatastorageformats.
TherearefivebasicdatatypesinC.
Those are char for character, int for integer, float for floating point, double double precision
floatingpoint,andvoid.
Valuesoftypecharare,intheory,restrictedtothedefinedASCIIcharacters.
Therangeoftypesfloatanddoubleisusuallygivenindigitsofprecision.
Themagnitudeoftypefloatanddoubledependuponthemethodusedtorepresentthefloating
pointnumbers.
Typevoidisusedtoexplicitlydeclareafunctionasreturningnovalue.
FundamentalDataTypes
voidusedtodenotethetypewithnovalues.
voidcannotbeusedtodefineavariable.
void,inC,isatypethathasnosize.
Thus, if one was to declare a variable of type "void", the compiler would not know how much
memorytoallocateforit.
Thereforevoidcannotbeusedtodefineavariable.
intusedtodenoteanintegertype.
charusedtodenoteacharactertype.
float,doubleusedtodenoteafloatingpointtype.
int*,float*,char*usedtodenoteapointertype,whichisamemoryaddresstype.
Deriveddatatypes
Arrayafinitesequence(ortable)ofvariablesofthesamedatatype.
Stringanarrayofcharactervariables.
Page 59 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/5.html 1/2
Introduction to C Language
8/7/2015 scormcontent
Structureacollectionofrelatedvariablesofthesameand/ordifferentdatatypes.
Thestructureiscalledarecordandthevariablesintherecordarecalledmembersorfields.
NumericdataTypes
Cprovidesseveraldifferenttypesofnumericvariables.
The users need different types of variables because different numeric values have varying
memorystoragerequirementsanddifferintheeasewithwhichcertainmathematicaloperations
canbeperformedonthem.
Small integers (for example, 1, 199, and 8) require less memory to store, and the user
computer can perform mathematical operations (addition, multiplication, and so on) with such
numbersveryquickly.
Byusingtheappropriatevariabletypes,theusersensurethattheprogramrunsasefficientlyas
possible.
Listedbelowarethenumericdatatypesinc.
shortint 2 32,767to32,767
unsignedshortint 2 0to65,535
signedshortint 2 32,767to32,767
longint 4 2,147,483,647to2,147,483,647
signedlongint 4 2,147,483,647to2,147,483,647
unsignedlongint 4 0to4,294,967,294
Page 60 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/5.html 2/2
Introduction to C Language
8/7/2015 scormcontent
VariableDefinition
Avariableisawayofreferringtoamemorylocationusedinacomputerprogram.
Thismemorylocationholdsvaluesperhapsnumbersortextormorecomplicatedtypesofdata
likeapayrollrecord.
VariableDeclarations
BeforetheuserscanuseavariableinaCprogram,itmustbedeclared.
Avariabledeclarationtellsthecompilerthenameandtypeofavariableandoptionallyinitializes
thevariabletoaspecificvalue.
Iftheprogramattemptstouseavariablethathasntbeendeclared,thecompilergeneratesan
errormessage.
Avariabledeclarationhasthefollowingform:
typenamevarname
typenamespecifiesthevariabletypeandmustbeoneofthekeywords.
From the declarations, varname is the variable name, which must follow the rules mentioned
earlier.
User can declare multiple variables of the same type on one line by separating the variable
nameswithcommas:
intcount,number,start/*threeintegervariables*/
floatpercent,total/*twofloatvariables*/
charfirstname/*charactertypevariable*/
CharacterVariables
Acharacterisasingleletter,numeral,punctuationmark,orothersuchsymbol.
Astringisanysequenceofcharacters.
Stringsareusedtoholdtextdata,whichiscomprisedofletters,numerals,punctuationmarks,
andothersymbols.
UsingCharacterVariables,likeothervariabletheusersmustdeclarecharsbeforeusingthem,
andhecaninitializethematthetimeofdeclaration.
Herearesomeexamplesofcharactervariables:
chara,b,c/*Declarethreeuninitializedcharvariables*/
charcode=x/*Declarethecharvariablenamedcodeandstorethecharacterxthere*/
Page 61 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/6.html 1/2
Introduction to C Language
8/7/2015 scormcontent
code=!/*Store!inthevariablenamedcode*/
Integer,FloatandDoubledeclarations
Todeclareavariableasinteger,followthebelowsyntax:
intvariable_name
intisthetypeofthevariablenamedvariable_name.
intdenotesintegertype.
Afloatisasingleprecisionfloatingpointvalue.
Todeclareavariableasfloat,followthebelowsyntax:
floatvariable_name
Adoubleisadoubleprecisionfloatingpointvalue.
Todeclareavariableasdouble,followthebelowsyntax:
doublevariable_name
Examples:
inti,j,k
floatf,salary
doubled
Page 62 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/6.html 2/2
Introduction to C Language
8/7/2015 scormcontent
ExpressionandOperators
ThesymbolswhichareusedtoperformlogicalandmathematicaloperationsinaCprogramare
calledCoperators.
TheseCoperatorsjoinindividualconstantsandvariablestoformexpressions.
Operators,functions,constantsandvariablesarecombinedtogethertoformexpressions.
ConsidertheexpressionA+B*5.
Where,+,*areoperators,A,Barevariables,5isconstantandA+B*5isanexpression.
TypesofCoperators
Clanguageoffersmanytypesofoperators.
Theyare,
Arithmeticoperators.
Assignmentoperators.
Relationaloperators.
Logicaloperators.
Bitwiseoperators.
Conditionaloperators(ternaryoperators).
Increment/decrementoperators.
Specialoperators.
ArithmeticOperatorsinC
CArithmeticoperatorsareusedtoperformmathematicalcalculationslikeaddition,subtraction,
multiplication,divisionandmodulusinCprograms.
1 + Addition A+B
2 Subtraction AB
3 * Multiplication A*B
4 / Division A/B
5 % Modulus A%B
Page 63 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/7.html 1/12
Introduction to C Language
8/7/2015 scormcontent
ExampleprogramforCarithmeticoperators
In this example program, two values 40 and 20 are used to perform arithmetic operations
such as addition, subtraction, multiplication, division, modulus and output is displayed for each
operation.
Assignmentoperators
InCprograms,valuesforthevariablesareassignedusingassignmentoperators.
For example, if the value 10 is to be assigned for the variable sum, it can be assigned as
sum=10.
OtherassignmentoperatorsinClanguagearegivenbelow.
+= sum+=10 Thisissameassum=sum+10
Page 64 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/7.html 2/12
Introduction to C Language
8/7/2015 scormcontent
= sum=10 Thisissameassum=sum10
*= sum*=10 Thisissameassum=sum*10
Compoundassignmentoperators
/= sum/=10 Thisissameassum=sum/10
%= sum%=10 Thisissameassum=sum%10
^= sum^=10 Thisissameassum=sum^10
ExampleprogramforCassignmentoperators
Inthisprogram,valuesfrom09aresummedupandtotal45isdisplayedasoutput.
Assignmentoperatorssuchas=and+=areusedinthisprogramtoassignthevaluesandto
sumupthevalues.
Relationaloperators
Relational operators are used to find the relation between two variables. i.e. to compare the
valuesoftwovariablesinaCprogram.
Page 65 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/7.html 3/12
Introduction to C Language
8/7/2015 scormcontent
5 == x==y xisequaltoy
6 != x!=y xisnotequaltoy
ExampleprogramforrelationaloperatorsinC
Inthisprogram,relationaloperator(==)isusedtocompare2valueswhethertheyareequalare
not.
Ifbothvaluesareequal,outputisdisplayedasvaluesareequal.
Else,outputisdisplayedasvaluesarenotequal.
Note:doubleequalsign(==)shouldbeusedtocompare2values.
Weshouldnotsingleequalsign(=).
Logicaloperators
Theseoperatorsareusedtoperformlogicaloperationsonthegivenexpressions.
Thereare3logicaloperatorsinClanguage.
Theyare,logicalAND(&&),logicalOR(||)andlogicalNOT(!).
Page 66 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/7.html 4/12
Introduction to C Language
8/7/2015 scormcontent
Itreversesthestateoftheoperand((x>5)&&(y<5))
logical !((x>5)&&
3 ! If((x>5)&&(y<5))istrue,logicalNOToperator
NOT (y<5))
makesitfalse
ExampleprogramforlogicaloperatorsinC
In this program, operators (&&, || and !) are used to perform logical operations on the given
expressions.
&&operator
ifclausebecomestrueonlywhenbothconditions(m>nandm!=0)istrue.
Else,itbecomesfalse.
||Operator
ifclausebecomestruewhenanyoneofthecondition(o>p||p!=20)istrue.
Itbecomesfalsewhennoneoftheconditionistrue.
!Operator
Itisusedtoreversesthestateoftheoperand.
Iftheconditions(m>n&&m!=0)istrue,true(1)isreturned.
Thisvalueisinvertedby!operator.
So,!(m>nandm!=0)returnsfalse(0).
Page 67 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/7.html 5/12
Introduction to C Language
8/7/2015 scormcontent
Bitwiseoperators
Theseoperatorsareusedtoperformbitoperations.
Decimal values are converted into binary values which are the sequence of bits and bit wise
operatorsworkonthesebits.
BitwiseoperatorsinClanguageare&(bitwiseAND),|(bitwiseOR),~(bitwiseOR),^(XOR),<<
(leftshift)and>>(rightshift).
Truthtableforbitwiseoperation
0 0 0 0 0
0 1 1 0 1
1 0 1 0 1
Page 68 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/7.html 6/12
Introduction to C Language
8/7/2015 scormcontent
1 1 1 1 0
Bitwiseoperators
Operatorsymbol Operatorname
& BitwiseAND
| BitwiseOR
~ BitwiseNOT
^ XOR
<< LeftShift
>> RightShift
Considerx=40andy=80.
Binaryformofthesevaluesaregivenbelow.
x=00101000.
y=01010000.
Allbitwiseoperationsforxandyaregivenbelow.
x&y=00000000(binary)=0(decimal).
x|y=01111000(binary)=120(decimal).
~x=1111111111111111111111111111111111111111111111111111111111010111
=41(decimal).
x^y=01111000(binary)=120(decimal).
x<<1=01010000(binary)=80(decimal).
x>>1=00010100(binary)=20(decimal).
Note:
BitwiseNOT:Valueof40inbinaryis
0000000000000000000000000000000000000000000000000000000000101000.
So,all0sareconvertedinto1sinbitwiseNOToperation.
Bitwiseleftshiftandrightshift:Inleftshiftoperationx<<1,1meansthatthebitswillbe
leftshiftedbyoneplace.
Ifweuseitasx<<2,then,itmeansthatthebitswillbeleftshiftedby2places.
Page 69 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/7.html 7/12
Introduction to C Language
8/7/2015 scormcontent
ExampleprogramforbitwiseoperatorsinC
In this example program, bit wise operations are performed as shown above and output is
displayedindecimalformat.
Conditionalorternaryoperators
Conditionaloperatorsreturnonevalueifconditionistrueandreturnsanothervalueiscondition
isfalse.
Thisoperatorisalsocalledasternaryoperator.
Syntax:(Condition?true_value:false_value)
Example:(A>100?0:1)
Inaboveexample,ifAisgreaterthan100,0isreturnedelse1isreturned.
Thisisequaltoifelseconditionalstatements.
Exampleprogramforconditional/ternaryoperatorsinC
Page 70 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/7.html 8/12
Introduction to C Language
8/7/2015 scormcontent
Increment/decrementOperators
Increment operators are used to increase the value of the variable by one and decrement
operatorsareusedtodecreasethevalueofthevariablebyoneinCprograms.
Syntax:
Incrementoperator:++var_name(or)var_name++
Decrementoperator:var_name(or)var_name
Example:
Incrementoperator:++ii++
Decrementoperator:ii
ExampleprogramforincrementoperatorsinC
Inthisprogram,valueofiisincrementedonebyonefrom1upto9usingi++operatorand
outputisdisplayedas123456789.
Page 71 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/7.html 9/12
Introduction to C Language
8/7/2015 scormcontent
ExampleprogramfordecrementoperatorsinC
Inthisprogram,valueofIisdecrementedonebyonefrom20upto11usingioperatorand
outputisdisplayedas20191817161514131211.
SpecialOperatorsinC
BelowaresomeofspecialoperatorsthatClanguageoffers.
Thisisusedtogettheaddressofthevariable.
1 &
Example:&awillgiveaddressofa.
Thisisusedaspointertoavariable.
2 *
Example:*awhere,*ispointertothevariablea.
Page 72 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/7.html 10/12
Introduction to C Language
8/7/2015 scormcontent
3 Sizeof() Thisgivesthesizeofthevariable.
Example:sizeof(char)willgiveus1.
Exampleprogramfor&and*operatorsinC
Inthisprogram,&symbolisusedtogettheaddressofthevariableand*symbolisusedto
getthevalueofthevariablethatthepointerispointingto.
PleasereferCpointertopictoknowmoreaboutpointers.
Exampleprogramforsizeof()operatorinC
sizeof()operatorisusedtofindthememoryspaceallocatedforeachCdatatypes.
Page 73 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/7.html 11/12
Introduction to C Language
8/7/2015 scormcontent
Page 74 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/7.html 12/12
Introduction to C Language
8/7/2015 scormcontent
ConstantsandLiterals
Likeavariable,aconstantisadatastoragelocationusedbytheusersprogram.
Unlikeavariable,thevaluestoredinaconstantcantbechangedduringprogramexecution.
Chastwotypesofconstants,eachwithitsownspecificuses.
LiteralConstants
20andRaretheexamplesforliteralconstant:
intcount=20
charname=R
SymbolicConstants
Asymbolicconstantisaconstantthatisrepresentedbyaname(symbol)intheprogram.
Likealiteralconstant,asymbolicconstantcantchange.
Whenever the User needs the constants value in the program, he can use its name as would
useavariablename.
Theactualvalueofthesymbolicconstantneedstobeenteredonlyonce,whenitisfirstdefined.
Symbolicconstantshavetwosignificantadvantagesoverliteralconstants.
Supposethattheuserswritingaprogramthatperformsavarietyofgeometricalcalculations.
Theprogramfrequentlyneedsthevalueof(PI)(3.14159)foritscalculations.
Thevalueofisconstant.
Forexample:
Tocalculatethecircumferenceandareaofacirclewithaknownradius,theusercouldwrite
thefollowingcode:
Circumference=3.14159*(2*radius)
Area=3.14159*(radius)*(radius)
Theasterisk(*)isCsmultiplicationoperator.
Thus,thefirstofthesestatementsmeansMultiply2timesthevaluestoredinthevariableradius,
andthenmultiplytheresultby3.14159.
Finally,assigntheresulttothevariablenamedcircumference.
If, however, the user define a symbolic constant with the name PI () and the value 3.14, he
couldwritethefollowingcode:
Page 75 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/8.html 1/4
Introduction to C Language
8/7/2015 scormcontent
Circumference=PI*(2*radius)
Area=PI*(radius)*(radius)
The second advantage of symbolic constants becomes apparent when the users need to
changeaconstant.
Continuing with the preceding example, The user might decide that for greater accuracy the
programneedstouseavalueofPIwithmoredecimalplaces:
3.14159Ratherthan3.14.
IftheuserhadusedliteralconstantsforPI,hewouldhavetogothroughthesourcecodeand
changeeachoccurrenceofthevaluefrom3.14to3.14159.
Withasymbolicconstant,heneedstomakeachangeonlyintheplacewheretheconstantis
defined.
Therestofcodewouldnotneedtobechanged.
Definingsymbolicconstants
Chastwomethodsfordefiningasymbolicconstant:
the#definedirectiveand
theconstkeyword.
Thefirstwaytodefineasymbolicconstantisthe#definedirectiveisusedasfollows:
#defineCONSTNAMEliteral
ThiscreatesaconstantnamedCONSTNAMEwiththevalueofliteral.literalrepresentsaliteral
constant,asdescribedearlier.
CONSTNAMEfollowsthesamerulesdescribedearlierforvariablenames.
Byconvention,thenamesofsymbolicconstantsareuppercase.
Thismakesthemeasytodistinguishfromvariablenames,whichbyconventionarelowercase.
Forthepreviousexample,therequired#definedirectiveforaconstantcalledPIwouldbe
#definePI3.14159.
Notethat#definelinesdontendwithasemicolon().
#definestatementscanbeplacedanywhereinyoursourcecode,butthedefinedconstantisin
effectonlyfortheportionsofthesourcecodethatfollowthe#definedirective.
Mostcommonly,programmersgroupall#definestatementstogether,nearbeginningofthefile
andbeforethestartofthemain()function.
Page 76 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/8.html 2/4
Introduction to C Language
8/7/2015 scormcontent
Howa#defineworks?
Thepreciseactionofthe#definedirectiveistoinstructthecompilerasfollows:
Inthesourcecode,replaceCONSTNAMEwithliteral.
Theeffectisexactlythesameasiftheuserhadusedtheeditortogothroughthesourcecode
andmakethechangesmanually.
Forexample,#definePI3.14159.
/*theusershavedefinedaconstantforPI.*/
#definePIPE100.
DefiningConstantswiththeconstkeyword
Thesecondwaytodefineasymbolicconstantiswiththeconstkeyword.
Constisamodifierthatcanbeappliedtoanyvariabledeclaration.
constinta=10
Herearesomeexamples:
constintcount=100
constlongdebt=12000000,floattax_rate=0.21
Constaffectsallvariablesonthedeclarationline.Inthelastline,debtandtax_ratearesymbolic
constants.
Literals
Theconstantsrefertofixedvaluesthattheprogrammaynotalterduringitsexecution.
Thesefixedvaluesarealsocalledliterals.
Constantscanbeofanyofthebasicdatatypeslikeanintegerconstant,afloatingconstant,a
characterconstant,orastringliteral.
Therearealsoenumerationconstantsaswell.
Integerliterals
Anintegerliteralcanbeadecimal,octal,orhexadecimalconstant.
A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for
decimal.
Page 77 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/8.html 3/4
Introduction to C Language
8/7/2015 scormcontent
AnintegerliteralcanalsohaveasuffixthatisacombinationofUandL,forunsignedandlong,
respectively.
Thesuffixcanbeuppercaseorlowercaseandcanbeinanyorder.
Floatingpointliterals
A floatingpoint literal has an integer part, a decimal point, a fractional part, and an exponent
part.
Theusercanrepresentfloatingpointliteralseitherindecimalformorexponentialform.
Whilerepresentingusingdecimalform,theusermustincludethedecimalpoint,theexponent,or
both and while representing using exponential form he must include the integer part, the
fractionalpart,orboth.
ThesignedexponentisintroducedbyeorE.
Characterliterals
Characterliteralsareenclosedinsinglequotes,e.g.,xandcanbestoredinasimplevariableof
chartype.
A character literal can be a plain character (e.g., x), an escape sequence (e.g., \t), or a
universalcharacter(e.g.,\u02C0).
TherearecertaincharactersinCwhentheyareprecededbyabackslashtheywillhavespecial
meaningandtheyareusedtorepresentlikenewline(\n)ortab(\t).
Here,theuserhavealistofsomeofsuchescapesequencecodes:
Stringliterals
Stringliteralsorconstantsareenclosedindoublequotes"".
A string contains characters that are similar to character literals: plain characters, escape
sequences,anduniversalcharacters.
Theuserscanbreakalonglineintomultiplelinesusingstringliteralsandseparatingthoseusing
whitespaces.
Page 78 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/8.html 4/4
Introduction to C Language
8/7/2015 scormcontent
SimpleAssignmentsStatement
Astatementisacompletedirectioninstructingthecomputertocarryoutsometask.
InC,statementsareusuallywrittenoneperline,althoughsomestatementsspanmultiplelines.
Cstatementsalwaysendwithasemicolon(exceptfor#defineand#include).
StatementsandWhiteSpace:
Thetermwhitespacereferstospaces,tabsandblanklinesintheusersourcecode.
TheCcompilerisntsensitivetowhitespace.
Whenthecompilerreadsastatementintheusersourcecode,itlooksforthecharactersin
thestatementandfortheterminatingsemicolon,butitignoreswhitespace.
Thus,thestatement:
x=2+3isequivalenttox=2+3withwhitespaces.
Itisalsoequivalenttoasfollows:
x=
Thisgivestheuseragreatdealofflexibilityinformattingthesourcecode.
Statements should be entered one per line with a standardized scheme for spacing around
variablesandoperators.
Page 79 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/9.html 1/1
Introduction to C Language
8/7/2015 scormcontent
BasicInputOutputStatements
Thebasicinput/outputfunctionsare
getchar,
putchar,
gets,
puts,
scanfand
printf.
Thefirsttwofunctions,getcharandputchar,areusedtotransfersinglecharacters.
Thenextfunctiongetsandputsareusedtoinputandoutputstrings,andthelasttwofunctions,
scanfandprintf,permitthetransferofsinglecharacters,numericalvaluesandstrings.
getchar()Function
getchar()functionisusedtoreadonecharacteratatimefromthekeyboard.
Syntaxch=getchar()wherechisacharVar.
Ex:
Whenthisfunctionisexecuted,thecomputerwillwaitforakeytobepressedandassignsthe
valuetothevariablewhentheenterkeypressed.
putchar()Function
putchar()functionisusedtodisplayonecharacteratatimeonthemonitor.
Syntax:putchar(ch)
EX:
Page 80 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/10.html 1/4
Introduction to C Language
8/7/2015 scormcontent
charch=M
putchar(ch)
TheComputerdisplaythevaluecharofvariablechi.eMontheScreen.
gets()Function
gets()functionisusedtoreadastringofcharactersincludingwhitespaces.
Notethatwhitespacesinastringcannotbereadusingscanf()with%sformatspecifier.
Syntax:gets(S)whereSisacharstringvariable.
Ex:
charS[20]
gets(S)
Whenthisfunctionisexecutedthecomputerwaitsforthestringtobeentered.
Puts()Function
puts()isafunctionusedtodisplaystringsonscreen.
Forexample,
scanf()
Justasmostprogramsneedtooutputdatatothescreen,theyalsoneedtoinputdatafromthe
keyboard.
The most flexible way the program can read numeric data from the keyboard is by using the
scanf()libraryfunction.
Thescanf()functionreadsdatafromthekeyboardaccordingtoaspecifiedformatandassigns
Page 81 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/10.html 2/4
Introduction to C Language
8/7/2015 scormcontent
theinputdatatooneormoreprogramvariables.
Forexample:
The statement reads a decimal integer from the keyboard and assigns it to the integer
variablexasshownbelow:
scanf("%d",&x)
The%indicatesthattheconversionspecificationfollows:
Thedrepresentsthedatatypeandindicatesthatthenumbershouldbereadasainteger.
The&isCunaryoperatorthatgetsthememoryaddressofthevariablefollowingit.
The user will read more about this operator and its associated operator *, in the section
Pointersinthecourse.
Likewise,thefollowingstatementreadsafloatingpointvaluefromthekeyboardandassigns
ittothevariablerate:
scanf("%f",&rate)
Thefrepresentsthedatatypeandindicatesthatthenumbershouldbereadasafloat.
printf()
The printf() function, part of the standard C library, is perhaps the most versatile way for a
programtodisplaydataonscreen.
Printingatextmessageonscreenissimple.
Calltheprintf()function,passingthedesiredmessageenclosedindoublequotationmarks.
Forexample,todisplayanerrorthathasoccurred!onscreen,theuserwritethefollowing:
printf("Anerrorthathasoccurred!")
In addition to text messages, however, he frequently needs to display the value of program
variables.
Thisisalittlemorecomplicatedthandisplayingonlyamessage.
Itacceptsastringparameter(calledtheformatstring),whichspecifiesamethodforrenderinga
number of other parameters (of which there typically may be arbitrarily many, of a variety of
types)intoastring.
Forexample,supposetheuserswanttodisplaythevalueofthenumericvariablexonscreen,
alongwithsomeidentifyingtext.
Furthermore,hewantstheinformationtostartatthebeginningofanewline.
Theprintf()functionasshownbelow:
Page 82 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/10.html 3/4
Introduction to C Language
8/7/2015 scormcontent
printf("\nThevalueofxis%d",x)
\nrepresentsanewlinecharacter.
Theresultingscreendisplay,assumingthatthevalueofxis12,woulddisplaythefollowing:
Thevalueofxis12.
Inthisexample,twoargumentsarepassedtoprintf().
Thefirstargumentisenclosedindoublequotationmarksandiscalledtheformatstring.
Thesecondargumentisthenameofthevariable(x)containingthevaluetobeprinted.
Page 83 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/10.html 4/4
Introduction to C Language
8/7/2015 scormcontent
SimpleCprograms
TheHelloWorldintroduction
Thebestwaytolearnacomputerlanguageistostartwritingshortprogramsthatworkand
thengraduallyaddcomplexity.
ThetraditionalfirstCprogramprintsout"hello,world"andlookssomethinglikethis:
Useofthegets()Function
ToMultiplyTwoIntegers
FrequentlyusedEscapeSequences
Page 84 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/11.html 1/2
Introduction to C Language
8/7/2015 scormcontent
Page 85 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit3/assets/11.html 2/2
UNIT - 4
Conditional Statements and Loops
Page 86 of 260
Conditional Statements and Loops
8/7/2015 scormcontent
DecisionMakingwithinaProgramWhatisDecisionmaking?
Decisionmakingisthethoughtfulconsiderationandselectionofacourseofactionfromamong
availablealternativesinordertoproduceadesiredresult.
Mostcontrolstatementsinanycomputerlanguage,includingC,relyuponaconditionaltestthat
determinesacourseofaction.
Theconditionaltesteitherevaluatestoatrueorafalse.
"True"isconsideredthesameas"yes,"whichisalsoconsideredthesameas1.
"False"isconsideredthesameas"no,"whichisconsideredthesameas0.
DecisionMakingandConditions
Decision making structures require that the programmer specify one or more conditions to be
evaluatedortestedbytheprogram,alongwithastatementorstatementstobeexecutedifthe
condition is determined to be true, and optionally, other statements to be executed if the
conditionisdeterminedtobefalse.
Following is the general form of a typical decision making structure found in most of the
programminglanguages.
Cprogramminglanguageassumesanynonzeroandnonnullvaluesastrue,andifitiseither
zeroornull,thenitisassumedasfalsevalue.
Cprogramminglanguageprovidesfollowingtypesofdecisionmakingstatements.
Decisionisawordwhichisnormallytakeninamomentwhereoneisinapositiontoselectone
optionfromtheavailableoptionswhichareobviouslymorethanone.
Whilewritingprogramsthisconceptisalwaysgoingtoplayanimportantrole.
Wewillhavetoprovidethecapabilitiestoourprogramsothatitcantakedecisionsonitsown
dependinguponthevariouspossibleinputsfromtheuser.
Whenyouaregoingtowritesomeprogramitwillbealwaysnecessarythatyouwillhavetoput
somecodewhichhastobeexecutedonlywhenaspecificconditionissatisfied.
Theseconditionsareevaluatedbythecomputeritselfwhentheinputisgivenbytheuser.
In C language there are various methods which can be used to select an appropriate set of
statementsdependingupontheusersinput.
Oncountingthem,totallythereareFOURdifferentwaystotakedecisionswhichareasfollows:
ifStatement.
Page 87 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit4/assets/2.html 1/2
Conditional Statements and Loops
8/7/2015 scormcontent
ifelseStatement.
ConditionalOperators.
SwitchStatement.
Page 88 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit4/assets/2.html 2/2
Conditional Statements and Loops
8/7/2015 scormcontent
TheRelationalandLogicalOperator
The relational operators are used to compare expressions, asking questions such as, "Is y
greaterthan100?"or"Iszequalto0?"
Anexpressioncontainingarelationaloperatorevaluatestoeithertrue(1)orfalse(0).
"True"isconsideredthesameas"yes,"whichisalsoconsideredthesameas1.
"False"isconsideredthesameas"no,"whichisconsideredthesameas0.
Anexpressioncreatedusingarelationaloperatorformswhatisknownasarelationalexpression
oracondition.
Csrelationaloperatorsareasfollows.
Operator Meaning
< Lessthan
<= Lessthanorequalto
> Greaterthan
>= Greaterthanorequalto
== Equalto
!= Notequalto
LogicalOperators
Logical operators let the users combine two or more relational expressions into a single
expressionthatevaluatestoeithertrueorfalse.
LogicaloperatorsconsistsofAND,ORandNOTasshowninthetablebelow.
AnexpressioncontainingaLogicaloperatorevaluatestoeithertrue(1)orfalse(0).
"True"isconsideredthesameas"yes,"whichisalsoconsideredthesameas1.
"False"isconsideredthesameas"no,"whichisconsideredthesameas0.
Operator Meaning
&& LogicalAND
|| LogicalOR
! LogicalNOT
Page 89 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit4/assets/3.html 1/1
Conditional Statements and Loops
8/7/2015 scormcontent
ControlStatement
Ifstatement
Aprogramcontrolstatementmodifiestheorderofstatementexecution.
Program control statements can cause other program statements to execute multiple times or
nottoexecuteatall,dependingonthecircumstances.
TheifstatementisoneoftheCsprogramcontrolstatements.
In its basic form, the if statement evaluates an expression and directs program execution
dependingontheresultoftheevaluation.
Ifexpressionevaluatestotrue,statementisexecuted.
Ifstatementevaluatestofalse,statementisnotexecuted.
Ineithercase,executionthenpassestowhatevercodefollowstheifstatement.
Theexecutionofstatementdependsontheresultofexpression.
The line if (expression) and the line statement are considered to comprise the complete if
statementtheyarenotseparatestatements.
Anifstatementcancontroltheexecutionofmultiplestatementsthroughtheuseofacompound
statement,orblock.
Ablockisagroupoftwoormorestatementsenclosedinbraces.
Ablockcanbeusedanywhereasinglestatementcanbeused.
Page 90 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit4/assets/4.html 1/4
Conditional Statements and Loops
8/7/2015 scormcontent
Listedbelowisthesyntaxforifstatement:
Thisistheifstatementinitssimplestform.
Ifexpressionistrue,statement1isexecuted.Ifexpressionisnottrue,statement1isignored.
IfstatementSyntax
Ifstatement:Example
ElseStatement
Anifstatementcanoptionallyincludeanelseclause.
Theelseclauseisincludedasshownbelow:
Ifexpressionevaluatestotrue,statement1isexecuted.
Ifexpressionevaluatestofalse,statement2isexecuted.
Bothstatement1andstatement2canbecompoundstatementsorblocks.
IfelseStatement
Thecombinationoftheifandelseclauseiscalledtheifelsestatement.
Page 91 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit4/assets/4.html 2/4
Conditional Statements and Loops
8/7/2015 scormcontent
Thisisthemostcommonformoftheifstatement.
Ifexpressionistrue,statement1isexecutedotherwise,statement2isexecuted.
Thisisanestedif.
Ifthefirstexpression,expression1,istrue,statement1isexecutedbeforetheprogramcontinues
withthenextstatement.
Ifthefirstexpressionisnottrue,thesecondexpression,expression2,ischecked.
Ifthefirstexpressionisnottrue,andthesecondistrue,statement2isexecuted.
Ifbothexpressionsarefalse,statement3isexecuted.
Onlyoneofthethreestatementsisexecuted.
IfelsestatementSyntax
Ifelsestatement:Example
Page 92 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit4/assets/4.html 3/4
Conditional Statements and Loops
8/7/2015 scormcontent
Page 93 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit4/assets/4.html 4/4
Conditional Statements and Loops
8/7/2015 scormcontent
Loops
Theremaybeasituation,whenyouneedtoexecuteablockofcodeseveralnumbersoftimes.
Ingeneral,statementsareexecutedsequentially.
Thefirststatementinafunctionisexecutedfirst,followedbythesecond,andsoon.
Programming languages provide various control structures that allow for more complicated
executionpaths.
A loop statement allows us to execute a statement or group of statements multiple times and
followingisthegeneralformofaloopstatementinmostoftheprogramminglanguages.
Cprogramminglanguageprovidesthefollowingtypesoflooptohandleloopingrequirements.
whileloop.
forloop.
dowhileloop.
WhileloopWhileStatement
The while statement, also called the while loop, executes a block of statements as long as a
specifiedconditionistrue.
Thewhilestatementhasthefollowingform:
ConditionisanyCexpression,andstatementisasingleorcompoundCstatement.
Whenprogramexecutionreachesawhilestatement,thefollowingeventsoccur:
Page 94 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit4/assets/5.html 1/7
Conditional Statements and Loops
8/7/2015 scormcontent
Theexpressionconditionisevaluated.
If condition evaluates to false (that is, zero), the while statement terminates, and execution
passestothefirststatementfollowingthewhilestatement.
Ifconditionevaluatestotrue(thatis,nonzero),theCstatement(s)instatementareexecuted.
Executionreturnstostep1.
whileloop:Syntax
whileloop:Example
ForloopIntroduction
The for statement is a C programming construct that executes a block of one or more
statementsacertainnumberoftimes.
It is sometimes called the for loop because program execution typically loops through the
statementmorethanonce.
Aforstatementhasthefollowingstructure:
Page 95 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit4/assets/5.html 2/7
Conditional Statements and Loops
8/7/2015 scormcontent
Initial,condition,andincrementareallCexpressions,andstatementisasingleorcompound
Cstatement.
TheforStatement
Whenaforstatementisencounteredduringprogramexecution,thefollowingeventsoccur:
The expression initial is evaluated. Initial is usually an assignment statement that sets a
variabletoaparticularvalue.
Theexpressionconditionisevaluatedconditionistypicallyarelationalexpression.
Ifconditionevaluatestofalse(thatis,aszero),theforstatementterminates,andexecution
passestothefirststatementfollowingtheforstatement.
If condition evaluates to true (that is, as nonzero), the C statement(s) in statement are
executed.
Theexpressionincrementisevaluated,andexecutionreturnstotheexpressioncondition.
forloop:Syntax
forloop:Example
Page 96 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit4/assets/5.html 3/7
Conditional Statements and Loops
8/7/2015 scormcontent
Thedo...whileLoop
Csthirdloopconstructisthedo...whileloop,whichexecutesablockofstatementsaslongasa
specifiedconditionistrue.
Thedo...whileloopteststheconditionattheendoftheloopratherthanatthebeginning,asis
donebytheforloopandthewhileloop.
Thestructureofthedo...whileloopisasfollows:
ConditionisanyCexpression,andstatementisasingleorcompoundCstatement.
Whenprogramexecutionreachesado...whilestatement,thefollowingeventsoccur:
Step1:Thestatementsinstatementareexecuted.
Step2:Conditionisevaluated.
Step3:Ifitstrue,executionreturnstostep1.
Step4:Ifitsfalse,theloopterminates.
Thestatementsassociatedwithado...whilelooparealwaysexecutedatleastonce.
Thisisbecausethetestconditionisevaluatedattheend,insteadofbeginning,oftheloop.
Incontrast,forloopsandwhileloopsevaluatethetestconditionatthestartoftheloop,sothe
Page 97 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit4/assets/5.html 4/7
Conditional Statements and Loops
8/7/2015 scormcontent
associatedstatementsarenotexecutedatallifthetestconditionisinitiallyfalse.
Thedo...whileloopisusedlessfrequentlythanwhileandforloops.
Itismostappropriatewhenthestatement(s)associatedwiththeloopmustbeexecutedatleast
once.
Theusercould,ofcourse,accomplishthesamethingwithawhileloopbymakingsurethatthe
testconditionistruewhenexecutionfirstreachestheloop.
do...whileloop:Syntax
do...whileloop:Example
NestedLoopIntroduction
Anestedloopisaloopwithinaloop,aninnerloopwithinthebodyofanouterone.
Ithasthefollowingstructure:
Page 98 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit4/assets/5.html 5/7
Conditional Statements and Loops
8/7/2015 scormcontent
Whathappensisthatthefirstpassoftheouterlooptriggerstheinnerloop,whichexecutesto
completion.
Thenthesecondpassoftheouterlooptriggerstheinnerloopagain.
Thisrepeatsuntiltheouterloopfinishes.
Ofcourse,abreakwithineithertheinnerorouterloopmayinterruptthisprocess.
When the user "nest" two loops, the outer loop takes control of the number of complete
repetitionsoftheinnerloop.
Whilealltypesofloopsmaybenested,themostcommonlynestedloopsareforloops.
Example
InfiniteLoop
Aninfiniteloopisaloopthatneverterminates.
When the condition that controls the loop execution never becomes false, the loop can never
Page 99 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit4/assets/5.html 6/7
Conditional Statements and Loops
8/7/2015 scormcontent
stopexecuting.
Onesuchexampleisshownbelow:
Onecreatesaninfiniteloop.
Theconditionthatthewhiletestsistheconstant1,whichisalwaystrueandcantbechangedby
theprogram.
Because1canneverbechangedonitsown,theloopneverterminates.
Onecanalsocreateaninfiniteloopwiththeforstatement:
SwitchStatement
Cs most flexible program control statement is the switch statement, which lets the program
executedifferentstatementsbasedonanexpressionthatcanhavemorethantwovalues.
Earliercontrolstatements,suchasif,werelimitedtoevaluatinganexpressionthatcouldhave
onlytwovalues:
Trueorfalse.
Tocontrolprogramflowbasedonmorethantwovalues,theuserhadtousemultiplenestedif
statements.
Its purpose is to allow the value of a variable or expression to control the flow of program
execution.
Aswitchstatementisdefinedacrossmanyindividualstatements.
SwitchCase
Thestructureofswitchcaseisasshownbelow:
Fromthestatement,expressionisanyexpressionthatevaluatestoanintegervalue:typelong,
int,orchar.
The switch statement evaluates expression and compares the value against the templates
followingeachcaselabel,andthenoneofthefollowinghappens:
Ifamatchisfoundbetweenexpressionandoneofthetemplates,executionistransferredtothe
statementthatfollowsthecaselabel.
Ifnomatchisfound,executionistransferredtothestatementfollowingtheoptionaldefaultlabel.
If no match is found and there is no default label, execution passes to the first statement
followingtheswitchstatementsclosingbrace.
switchcase:Example
BreakStatement
The break statement can be placed only in the body of a for loop, while loop, or do...while
loop.
Whenabreakstatementisencountered,executionexitstheloop.
Fromtheexample,lefttoitself,theforloopwouldexecute10times.
Onthesixthiteration,however,countisequalto5,andthebreakstatementexecutes,causing
theforlooptoterminate.
Executionthenpassestothestatementimmediatelyfollowingtheforloopsclosingbrace.
Whenabreakstatementisencounteredinsideanestedloop,itcausestheprogramtoexitthe
innermostlooponly.
Thebreakstatementendstheloopandmovescontroltothenextstatementoutsidetheloop.
Thebreakstatementendsonlythesmallestenclosingdo,for,switch,orwhilestatement.
ThebreakstatementinCprogramminglanguagehasthefollowingtwousages:
Whenthebreakstatementisencounteredinsidealoop,theloopisimmediatelyterminated
andprogramcontrolresumesatthenextstatementfollowingtheloop.
Itcanbeusedtoterminateacaseintheswitchstatement.
ContinueStatement
Likethebreakstatement,thecontinuestatementcanbeplacedonlyinthebodyofaforloop,a
whileloop,orado...whileloop.
When a continue statement executes, the next iteration of the enclosing loop begins
immediately.
Thestatementsbetweenthecontinuestatementandtheendofthelooparentexecuted
Continue
Continueisusedinsidealoop.
Itcausesthecontrolofaprogramtoskiptherestofthecurrentiterationofaloopandstartthe
nextiteration.
Thefollowingisanexampleforthecontinuestatement.
Example:
GotoStatement
ThegotostatementisoneofCsunconditionaljump,orbranchingstatements.
Whenprogramexecutionreachesagotostatement,executionimmediatelyjumps,orbranches,
tothelocationspecifiedbythegotostatement.
This statement is unconditional because execution always branches when a goto statement is
encounteredthebranchdoesntdependonanyprogramconditions.
Agotostatementanditstargetmustbeinthesamefunction,buttheycanbeindifferentblocks.
Often,abreakstatement,acontinuestatement,orafunctioncallcaneliminatetheneedfora
gotostatement.
GotoStatement:Example
StructuredProgramming
Structured approach involves the use of methods such as topdown program design and a
limitednumberofcontrolstructuresinaprogramtocreatetightlystructuredmodulesofprogram
code.
Theeffectoftopdowndesignandstructuredprogramminghasbeenusedtolowertheoverall
costofprogramming.
The structured approach promises to reduce the cost of developing and maintaining computer
programsbystandardizingprogramdevelopmentandstructuresused.
This increases the simplicity and accuracy, and at the same time minimizes programming and
maintenancecost.
A traditional flexible and creative environment provided to the programmer often results in
complexanddifficulttoreadprogramsrequiringmuchtestingbeforetheyareerrorfree.
Thesealsobecomecostlytodevelopandmaintain.
Structured programming, on the other hand, emphasizes group responsibility for program
development.
Italsobringsinastandardizationofprogramdesignconceptsandmethods,whichsignificantly
reducestheprogramcomplexity.
Organizationsusingstructuredprogramminghaveshownthefollowingcharacteristics:
ProgrammingProductivity:Programmerswritemoreprogramstatementsperdaywithfewer
errors.
Program Economy: The cost and time of program development and maintenance are
reduced.
ProgramSimplicity:Programsareeasiertoread,write,correct,andmaintain.
These results highlight the reasons for structured programming to continue to be a popular
programmingmethodology.
ModularDesign
projects.
Using structured programming, the solution to the problem is divided into segments called
modules.
Amoduleisalogicallyseparablepartofaprogram.
Itisaunit,discreteandidentifiablewithrespecttocompilationandloading.
Intermsofcommonprogramminglanguageconstructs,amodulecanbeamacro,afunction,a
procedure(orsubroutine),aprocess,orapackage.
Each module involves processing of data that are logically related. Modules are functional
partsthataidinprocessing.
Ideally, each module works independent of other modules, although this is sometimes
impossible.
Modulesarerankedbyhierarchyandorganizedonthebasisofimportance.
The lower the module on the structure organization plan, more is the detail given to the
programmingstepsinvolved.
Thecontrollingmoduleresidesatthetoplevel.
Itgivestheviewoftheoverallstructurefortheentireprogram.
Thesystemisdesignedtogivemoredetailateachmodulelevel.
Amoduleiscodedandtested,andthentestedwithothertestedmodules.
Thisproceduremakesprogramtestingeasier,sincethereisonlyoneentrypointandoneexit
pointpermodule.
OnemajordrawbackofClanguageisthatsimilarfunctionscannotbegroupedinsideamodule
orclass.
Also functions cannot be associated to a type or structure thus data and functions cannot be
boundtogether.
StructuredProgrammingConstructs
Themostcommontechniquesusedinstructuredprogrammingtosolveallproblemsarecalled
constructs.
Sequence,selection,andrepetition
Theseconstructsarealsocalledcontrolstructures.
Using these three basic control structures, it is possible to write standardized programs, which
areeasytoreadandunderstand.
SequenceStructure
Sequencereferstoaninstructionoraseriesofinstructionsthatperformarequiredcalculation
orallowinputoroutputofdata.
Sincethesestepsareexecutedoneaftertheother,thereisnochangeintheflowlogic.
The picture illustrates that program statements in function A will be executed before those for
functionB.
Inotherwords,wesaythatcontrolflowsfromfunctionAtofunctionB.
SelectionStructure
Selectionreferstotestingforacertainconditionfordata.
Thereareonlytwopossibleanswerstoquestionsregardingdatatrue(yes)orfalse(no).
OneselectiontechniquevariationisknownastheIFTHENELSE.
The instructions that are to be executed when the condition is true follow the IFTHEN
alternative.
The instructions followed by the ELSE alternative represent what is to be executed when the
conditionisfalse.
Iftheconditionistrue,thecontrolwillflowtofunctionBanditsstatementswillbeexecutedifitis
false,functionAisexecuted.
RepetitionStructure
Repetitioninvolvestheuseofaseriesofinstructionsthatarerepeateduntilacertainconditionis
met.
Repetitioninvolvestheuseoftwovariationsthefor,whileandthedowhile.
Thewhileperformsafunctionaslongasaconditionistrue.
Ontheotherhand,dowhileallowsafunctiontobeexecuteduntilthegivenconditionisfalse.
Anothermarkeddifferenceisthatthewhilefirstteststhegivenconditionandthenexecutesthe
function,whereasdowhileprocessesthefunctionbeforecheckingthecondition.
Before writing a program to solve a particular problem, its essential to have a thorough
understandingoftheproblemandacarefullyplannedapproachtosolvingtheproblem.
ControlStructures
Normally,statementsinaprogramareexecutedoneaftertheotherintheorderinwhichtheyre
written.
Thisiscalledsequentialexecution.
VariousCstatementswellsoondiscussenabletheusertospecifythatthenextstatementtobe
executedmaybeotherthanthenextoneinsequence.
Thisiscalledtransferofcontrol.
Array
Anarrayisacollectionofsametypeofelementswhichareshelteredunderacommonname.
Anarraycanbevisualizedasarowinatable,whoseeachsuccessiveblockcanbethoughtof
asmemorybytescontainingoneelement.
Lookatthefigurebelow:
AnArrayoffourelements:
Thenumberof8bitbytesthateachelementoccupiesdependsonthetypeofarray.
Iftypeofarrayischarthenitmeansthearraystorescharacterelements.
Sinceeachcharacteroccupiesonebytesoelementsofacharacterarrayoccupyonebyteeach.
Anarrayisacollectionofdatastoragelocations,eachhavingthesamedatatypeandthesame
name.
Eachstoragelocationinanarrayiscalledanarrayelement.
Arraysareoftwotypes:
SingleorOnedimensionalarrays.
Multidimensionaleg.twodimensionalarrays.
SingleDimensionalArrays
Asingledimensionalarrayhasonlyasinglesubscript.
Asubscriptisanumberinbracketsthatfollowsanarrayname.
Thisnumbercanidentifythenumberofindividualelementsinthearray.
Anexampleshouldmakethisclear.
Forthecompanyexpenditureprogram,theuserscouldusethefollowinglinetodeclareanarray
oftypefloat:
floatexpense[12]
Thearrayisnamedexpense,anditcontains12elements.
Eachofthe12elementsistheexactequivalentofasinglefloatvariable.
AllofCsdatatypescanbeusedforcreatingarrays.
C array elements are always numbered starting at 0, so the 12 elements of expense are
numbered0through11.
In the above example, Januarys expenditure would be stored in expense [0], Februarys in
expense[1],andsoon.
Whenanarrayisdeclared,thecompilersetsasideablockofmemorylargeenoughtoholdthe
entirearray.
Individualarrayelementsarestoredinsequentialmemorylocations.
NamingandDeclaringArrays
Therulesforassigningnamestoarraysarethesameasforvariablenames.
An array name must be unique in that program which means should not be used for another
arrayorforanyotheridentifier(variable,constant).
Thearraydeclarationconsistsofanarraynamefollowedbythenumberofelementsinthearray
mustbeenclosedinsquarebrackets.
Whentheusersdeclareanarray,hecanspecifythenumberofelementswithaliteralconstant
orwithasymbolicconstantcreatedwiththe#definedirective.
Arrayelements
Sizeofarraydefinesthenumberofelementsinanarray.
Eachelementofarraycanbeaccessedandusedbyuseraccordingtotheneedofprogram.
Forexample:
intage[5]
Notethat,thefirstelementisnumbered0andsoon.
Here,thesizeofarrayageis5timesthesizeofintbecausethereare5elements.
Suppose,thestartingarrayaddressofage[0]is2120dandthesizeofintbe4bytes.
Page 115 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit5/assets/2.html 2/4
Arrays
8/7/2015 scormcontent
Then,thenextaddress(addressofa[1])willbe2124d,addressofa[2]willbe2128dandsoon.
Accessingarrayelements
Anelementisaccessedbyindexingthearrayname.
This is done by placing the index of the element within square brackets after the name of the
array.
Forexample:
doublesalary=balance[9]
The above statement will take 10th element from the array and assign the value to salary
variable.
Following is an example which will use three concepts viz. declaration, assignment and
accessingarrays:
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Element[0]=100.
Element[1]=101.
Element[2]=102.
Element[3]=103.
Element[4]=104.
Element[5]=105.
Element[6]=106.
Element[7]=107.
Element[8]=108.
Element[9]=109.
SearchinganArrayIntroduction
Acommonarrayoperationistosearchthevaluesofanarrayforaparticularvalue.
Usersmaybedoingthisinordertofindandchangeavalueortofindandprocessinformationin
acorrespondingelementofapairedorparallelarray.
AlinearSearchofanArray
A linear search starts searching for the value with the first element of the array and continues
throughthearray,oneelementatatimeuntilthewantedvalueisfoundortheuserreachthe
endofthearray.
Linearsearchisalsoknownassequentialsearchthatissuitableforsearchingalistofdatafora
particularvalue.
Listedbelowistheflowforalinearsearchinanarray.
Example:
ABinarySearchofanArray
A binary search requires that the element values in the array be in order, such as ascending
order,fromsmallesttolargest.
A binary search algorithm (or binary chop) is a technique for locating a particular value in a
Page 119 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit5/assets/3.html 2/6
Arrays
8/7/2015 scormcontent
sortedlist.
The method makes progressively better guesses, and closes in on the location of the sought
valuebyselectingthemiddleelementinthespan(which,becausethelistisinsortedorder,is
themedianvalue),comparingitsvaluetothetargetvalue,anddeterminingifitisgreaterthan,
lessthan,orequaltothetargetvalue.
A guessed index whose value turns out to be too high becomes the new upper bound of the
span,andifitsvalueistoolowthatindexbecomesthenewlowerbound.
Now,theusercansearchthearrayby:
Findingthecenterelementvalue.
Ifthisisthewantedvalue,theusersaredone.
Otherwise, if they required value is greater than this value and it lies in the top half of the
arrayiteliminatesthebottomhalfofthearrayanditfindsthenewcenterofwhatisleft.
Otherwise, if they wanted value is less than this value and it lies in the bottom half of the
array,iteliminatesthetopofthearrayandfindsthenewcenterofwhatisleft.
Thisisdoneuntiltheuserfindthevalueorherunoutofarray.
Listedbelowistheflowforabinarysearchinanarray:
Example:BinarySearch
InsertingElementsintoanArray
Givenbelowistheflowforinsertingthevaluesintoanarrayatruntime.
Example:
DeletingElementsfromanArray
Example:
FindtheLargest/SmallestoftheElementsofanArray
Thistime,wearelookingforthelargestvalueinthearray.
Wejustsetlargesttothevalueofthefirstelementofthearray.
Thenwecomparethisvaluetoeachoftheotherelementsinthearray.
Ifoneislarger,wereplacethevalueinlargestwiththevalueandcontinuetochecktherestof
thearray.
Thefollowingtheflowtofindthelargestoftheelementsofanarray.
Example:
FindtheSmallestoftheElementsofanArray
We set smallest to the value of the first element of the array and start comparing it to other
elementsinthearray.
Thefollowingistheflowtofindthesmallestoftheelementsofanarray:
Example:
IntroductiontoMultidimensionalArraysTwoDimensionalArrays
Atwodimensionalarrayhastwosubscripts.
Atwodimensionalarrayhasarowandcolumnstructureasshownbelow:
intmatrix[row][column]
Whererowcanonlybeaninteger.
Andcolumncanonlybeaninteger.
WhatisaTwodimensionalarray?
Indexesin2Darrays
Assumethatthetwodimensionalarraycalledvalisdeclaredandlookslikethefollowing:
Row0 8 16 9 52
Row1 3 15 27 6
Row2 14 25 2 10
Toaccessthecellcontaining6,wereferenceval[1][3],thatis,row1,column3.
DECLARATION
Howtodeclareamultidimensionalarray?
intb[2][3]
Thenameofthearraytobeb.
Thetypeofthearrayelementstobeint.
Thedimensiontobe2(twopairsofbrackets[]).
Thenumberofelementsorsizetobe2*3=6.
INITIALIZATION
HowtoinitializeaTwoDimensionalarray?
Initializeddirectlyinthedeclarationstatement.
Usebracestoseparaterowsin2Darrays.
Implicitlydeclaresthenumberofrowstobe4.
InputofTwoDimensionalArrays
Datamaybeinputintotwodimensionalarraysusingnestedforloopsinteractivelyorwithdata
files.
Anestedforloopisusedtoinputelementsinatwodimensionalarray.
Inthiswaybyincreasingtheindexvalueofthearraytheelementscanbeenteredina2darray.
OutputofTwoDimensionalArrays
Theoutputoftwodimensionalarraysshouldbeintheformofrowsandcolumnsforreadability.
Nestedforloopsareusedtoprinttherowsandcolumnsinrowandcolumnorder.
Byincreasingtheindexvalueofthearraytheelementsstoredatthatindexvalueareprintedon
theoutputscreen.
Example:Aprogramtoinputelementsinatwodimensionalarray
andprintit
PassingArraystoFunctions
Twodimensionalarraysmaybypassedbyarrayname.
Because arrays are stored by rows, in order to accurately locate an element, a function must
knowthelengthofarow:thatisthenumberofcolumns.
Thismustbeincludedinboththefunctionprototypeandtheheaderofthefunctiondefinition.
PassingFixedSizedArrays.
PassingArrayElements.
MultidimensionalArray
Amultidimensionalarrayhasmorethanonesubscript.
Atwodimensionalarrayhastwosubscripts.
Athreedimensionalarrayhasthreesubscripts,andsoon.
ThereisnolimittothenumberofdimensionsaCarraycanhave.
Example
Addition/MultiplicationofTwoMatrices
AdditionofTwoMatrices:ProgramandOutput
MultiplicationofTwoMatrices:ProgramandOutput
TransposeofMatrix
NullTerminatedStringsasanArrayofCharacters
C Standard Library implements a powerful string class, which is very useful to handle and
manipulatestringsofcharacters.
However,becausestringsareinfactsequencesofcharacters,wecanrepresentthemalsoas
plainarraysofcharelements.
Forexample,thefollowingarray:
charjenny[20]
Itsanarraythatcanstoreupto20elementsoftypechar.
StringasanArrayofCharacters
In the array, we can store sequences of characters up to 20 characters long. But we can also
storeshortersequences.
For example, jenny could store at some point in a program either the sequence "Hello" or the
sequence"MerryChristmas",sincebothareshorterthan20characters.
Therefore, since the array of characters can store shorter sequences than its total length, a
specialcharacterisusedtosignaltheendofthevalidsequence:
Thenullcharacter,whoseliteralconstantcanbewrittenas\0(backslash,zero).
Ourarrayof20elementsoftypechar,calledjenny,canberepresentedstoringthecharacters
sequences"Hello"and"MerryChristmas"as:
InitializationofNullterminatedCharacterSequences
Becausearraysofcharactersareordinaryarraystheyfollowalltheirsamerules.
Forexample:
charmyword[]={H,e,l,l,o,\0}
charmyword[]="Hello"
RepresentationSparseMatrices
Amatrixisatwodimensionaldataobjectmadeofmrowsandncolumns,thereforehavingm,n
values.
Whenm=n,wecallitasquarematrix.
The most natural representation is to use twodimensional array A [m][n] and access the
elementofirowandjcolumnasA[i][j].
Ifalargenumberofelementsofthematrixarezeroelements,thenitiscalledasparsematrix.
Therefore,analternativerepresentationmustbeusedforsparsematrices.
Onesuchrepresentationistostoreonlynonzeroelementsalongwiththeirrowpositionsand
columnpositions.
Thatmeansrepresentingeverynonzeroelementbyusingtriples(i,j,value),whereiisarow
positionandjisacolumnposition,andstorethesetriplesinalinearlist.
Itispossibletoarrangethesetriplesintheincreasingorderofrowindices,andforthesamerow
indexintheincreasingorderofcolumnindices.
Each triple (i, j, value) can be represented by using a node having four fields as shown in the
following:
Asparsematrixcanberepresentedusingalistofsuchnodes,onepernonzeroelementofthe
matrix.
Forexample,considerthesparsematrixshowninfigure.
Asparsematrix
Thismatrixcanberepresentedusingthelinkedlistshowninfigure.
Example:Sparsematrix
StandardLibraryStringFunctionsStrings
Cimplementsthestringdatastructureusingarraysoftypechar.
Theusershavealreadyusedthestringextensively.
printf(Thisprogramisterminated!\n)
#defineERR_MessageError!!
Sincestringisanarray,thedeclarationofastringisthesameasdeclaringachararray.
charstring_var[30]
charstring_var[20]=Initialvalue
MemoryStorageforaString
Thestringisalwaysendedwithanullcharacter\0.
Thecharactersafterthenullcharacterareignored.
E.g.,charstr[20]=Initialvalue
ArraysofStrings
Anarrayofstringsisatwodimensionalarrayofcharactersinwhicheachrowisonestring.
charnames[People][Length]
charmonth[5][10]={January,February,March,April,May}
Input/OutputofaString
Theplaceholder%sisusedtorepresentstringargumentsinprintfandscanf.
printf(Topic:%s\n,string_var)
Thestringcanberightjustifiedbyplacingapositivenumberintheplaceholder.
printf(%8s,str)
Thestringcanbeleftjustifiedbyplacinganegativenumberintheplaceholder.
Printf(%8s,str)
AnExampleofManipulatingStringwithscanfandprintf
Executionofscanf("%s",dept)
Wheneverencounteringawhitespace,thescanningstopsandscanfplacesthenullcharacterat
theendofthestring.
E.g.,iftheusertypesMATH1234TR1800,thestringMATHalongwith0isstoredinto
dept.
StringLibraryFunctions
Thestringcannotbecopiedbytheassignmentoperator=.
E.g,str=TestStringisnotvalid.
Cprovidesstringmanipulatingfunctionsinthestring.hlibrary.
Page 141 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit5/assets/10.html 2/6
Arrays
8/7/2015 scormcontent
ThecompletelistofthesefunctionscanbefoundinAppendixBofthetextbook.
SomeStringFunctionsfromString.h
Functionsstrcpyandstrncpy
Functionstrcpycopiesthestringinthesecondargumentintothefirstargument.
E.g.,strcpy(dest,teststring)
Thenullcharacterisappendedattheendautomatically.
Ifsourcestringislongerthanthedestinationstring,theoverflowcharactersmayoccupythe
memoryspaceusedbyothervariables.
Functionstrncpycopiesthestringbyspecifyingthenumberofcharacterstocopy.
Theusershavetoplacethenullcharactermanually.
E.g.,strncpy(dest,teststring,6)dest[6]=\0
If source string is longer than the destination string, the overflow characters are discarded
automatically.
ExtractingSubstringofaString
Wecanusestrncpytoextractsubstringofonestring.
E.g.,strncpy(result,s1,9)
E.g.,strncpy(result,&s1[5],2)
Functionsstrcatandstrlen
Functions strcat and strncat concatenate the fist string argument with the second string
argument.
strcat(dest,more..)
strncat(dest,more..,3)
Functionstrlenisoftenusedtocheckthelengthofastring(i.e.,thenumberofcharactersbefore
thefistnullcharacter).
E.g.,dest[6]=Hello
strncat(dest,more,5strlen(dest))
dest[5]=\0
DistinctionBetweenCharactersandStrings
Therepresentationofachar(e.g.,Q)andastring(e.g.,Q)isessentiallydifferent.
Astringisanarrayofcharactersendedwiththenullcharacter.
StringComparison(1/2)
Supposetherearetwostrings,str1andstr2.
Theconditionstr1<str2comparetheinitialmemoryaddressofstr1andofstr2.
The comparison between two strings is done by comparing each corresponding character in
them.
ThecharactersarecomparedagainsttheASCIItable.
thrill>throwsincei<o
joy<joyous
Thestandardstringcomparisonusesthestrcmpandstrncmpfunctions.
StringComparison(2/2)
str1=str2 0 Hi=Hi
E.g.,wecancheckiftwostringsarethesameby
if(strcmp(str1,str2)!=0)
printf(Thetwostringsaredifferent!)
Page 144 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit5/assets/10.html 5/6
Arrays
8/7/2015 scormcontent
Input/OutputofCharactersandStrings
The stdio library provides getchar function which gets the next character from the standard
input.
ch=getchar()isthesameasscanf(%c,&ch)
Similarfunctionsareputchar,gets,puts.
ForIOfrom/tothefile,thestdiolibraryalsoprovidescorrespondingfunctions.
getc:readsacharacterfromafile.
Similarfunctionsareputc,fgets,fputs.
TopdownApproachofProblemSolving
Therearethreegeneralapproachestowritingaprogram:
TopdownInthetopdownapproachonestartswiththetoplevelroutineandmovedownto
thelowlevelroutine.
Bottom up The bottomup approach works in the opposite direction on begins with the
specificroutines,buildthemintoprogressivelymorecomplexstructures,andendatthetop
levelroutine.
Topdownapproach
Atopdownapproachalsohelpsonetoclarifytheoverallstructureandoperationoftheprogram
beforeonecodethelowlevelfunctions.
Thetopdownmethodstartswithageneraldescriptionandworkstowardsspecifics.
Infactagoodwaytodesignaprogramistodefineexactlywhattheprogramisgoingtodoat
thetoplevel.
Eachentryinthelistshouldcontainonlyonefunctionalunit.
Afunctionalunitcanbethoughtofasablackboxthatperformsasingletask.
ModularProgrammingandFunctions
Modularprogramming
Modularprogrammingisastylethataddsstructureandreadabilitytotheprogramcode.
It may not make much difference on small projects, but as one starts to work on something
biggeritcanmakethecodemucheasiertoreadandmaintain.
Structuring the code is a simple task of splitting the program into manageable chunks so that
eachpartisselfcontained.
Bycreatingtheseselfcontainedmodules,onecanfocusonprogrammingeachpart.
Once one is satisfied that one bit is working, one can then move to the next module with the
confidence,whateveronedoeselsewherewillnothaveanoneffectonothermodulesthatone
hasalreadywritten.
Functions
Whatisafunction?
A function is a named, independent section of C code that performs a specific task and
optionallyreturnsavaluetothecallingprogram.
Afunctionisnamed.Eachfunctionhasauniquename.
Byusingthenameinanotherpartoftheprogram,onecanexecutethestatementscontained
inthefunction.
Thisisknownascallingthefunction.
Afunctioncanbecalledfromwithinanyotherfunction.
Afunctionisindependent.
Afunctioncanperformitstaskwithoutinterferencefromorinterferingwithotherpartsofthe
program.
Generalformofafunction
StandardCLibrary
A collection of reusable functions (code for building data structures, code for performing math
functionsandscientificcalculations,etc.,).
WhichwillsaveCprogrammerstimeespeciallywhenworkingonlargeprogrammingprojects.
TheCLibraryispartoftheANSI(AmericanNationalStandardInstitute)fortheCLanguage.
TheCprogramscancallonalargenumberoffunctionsfromthestandardClibrary.
Thesefunctionsperformessentialservicessuchasinputandoutput.
Theyalsoprovideefficientimplementationsoffrequentlyusedoperations.
Manymacrosandtypedefinitionsaccompanythesefunctionsandhelpthemtomakebetteruse
ofthestandardCfunctions.
StandardLibraryofCfunctions
CStandardlibraryfunctionsorsimplyCLibraryfunctionsareinbuiltfunctionsinCprogramming.
Functionprototypeanddatadefinitionsofthesefunctionsarewrittenintheirrespectiveheader
file.
Forexample:Ifyouwanttouseprintf()function,theheaderfile<stdio.h>shouldbeincluded.
ThereisatleastonefunctioninanyCprogram,i.e.,themain()function(whichisalsoalibrary
function).
Thisprogramiscalledatprogramstarts.
TherearemanylibraryfunctionsavailableinCprogrammingtohelptheprogrammertowritea
goodefficientprogram.
Suppose,youwanttofindthesquarerootofanumber.
Youcanwriteyourownpieceofcodetofindsquarerootbut,thisprocessistimeconsumingand
Page 150 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit6/assets/4.html 1/3
Functions
8/7/2015 scormcontent
thecodeyouhavewrittenmaynotbethemostefficientprocesstofindsquareroot.
But,inCprogrammingyoucanfindthesquarerootbyjustusingsqrt()functionwhichisdefined
underheaderfile"math.h".
UseofLibraryFunction:ToFindSquareroot
ListedbelowarefewofthestandardCLibraries.
Stdio.hSupportsFileInput/OutputOperations.
Stdlib.hSupportsMiscellaneousdeclarations.
Math.hSupportsDefinitionsusedformathematicalcalculations.
String.hSupportsstringfunctions.
Time.hSupportssystemtimefunctions.
Ctype.h Header file "ctype.h" includes numerous standard library functions to handle
characters(especiallytestcharacters).
ExampleProgramsoffrequentlyusedstandardCLibraries
PrototypeofaFunction
FunctionPrototype:return_typefunction_name(argtypename1,...,argtypenamen)
Afunctionprototypeprovidesthecompilerwiththedescriptionofafunctionthatwillbedefined
atalaterpointintheprogram.
Theprototypeincludesareturntypeindicatingthetypeofvariablethatthefunctionwillreturnit
alsoincludesthefunctionname,whichshoulddescribewhatthefunctiondoes.
Theprototypealsocontainsthevariabletypesofthearguments(argtype)thatwillbepassedto
thefunction.
Optionally,itcancontainthenamesofthevariablethatwillbepassed.
Aprototypeshouldalwaysendwithasemicolon.
doublesquared(doublenumber)
voidprint_report(intreport_number)
intget_menu_choice(void)
FunctionDefinition
Afunctiondefinitionistheactualfunction.
Thedefinitioncontainsthecodethatwillbeexecuted.
The first line of a function definition, called the function header, should be identical to the
functionprototype,withtheexceptionofthesemicolon.
Afunctionheadershouldntendwithasemicolon.
In addition, although the argument variable names the optional in the prototype, they must be
includedinthefunctionheader.
Following the header is the function body, containing the statements that the function will
perform.
Thefunctionbodyshouldstartwithanopeningbracketandendwithaclosingbracket.
If the function return type is anything other than void, a return statement should be included,
returningavaluematchingthereturntype.
return_typefunction_name(argtypename1,...,argtypenamen)
/*statements*/
ThefollowingProgramdemonstratesprototypeofafunction
FormalParameterList
Parameter
A parameter is a special kind of variable, used in a subroutine to refer to one of the pieces of
dataprovidedasinputtothesubroutine.
Thesepiecesofdataarecalledarguments.
ParameterMeansValuesSuppliedtoFunctionsothatFunctioncanutilizetheseValues.
ParametersareSimplyVariables.
DifferencebetweenNormalVariableandParameteristhatTheseArgumentsareDefinedatthe
timeofCallingFunction.
FormalParameter
ParameterWritteninFunctionDefinitionisCalledFormalParameter.
Althoughformalparametersarealwaysvariablesactualparametersdonothavetobevariables.
Example
Para1iscalledFormalParameter.
ActualParameter
ParameterWrittenInFunctionCallisCalledActualParameter.
Onecanusenumbers,expressions,orevenfunctioncallsasactualparameters.
Example
num1isActualParameter.
Parameterlist
Afunctionisdeclaredinthefollowingmanner:
returntypefunctionname(parameterlist,...){body...}
Returntypeisthevariabletypethatthefunctionreturns.
Thiscannotbeanarraytypeorafunctiontype.
Ifnotgiven,thenintisassumed.
Functionnameisthenameofthefunction.
TheFunctionReturnType
Thefunctionreturntypespecifiesthedatatypethatthefunctionreturnstothecallingprogram.
ThereturntypecanbeanyofCsdatatypes:char,int,long,float,ordouble.
Onecanalsodefineafunctionthatdoesntreturnavaluebyusingareturntypeofvoid.
Givenbelowarefewexamples:
intfunc1(...)/*Returnsatypeint.*/
floatfunc2(...)/*Returnsatypefloat.*/
voidfunc3(...)
ReturnTypeProgram
CallingFunctions
Therearetwowaystocallafunction.
Anyfunctioncanbecalledbysimplyusingitsnameandargumentlistaloneinastatement,asin
thefollowingexample.
Ifthefunctionhasareturnvalue,itisdiscarded.
wait(12)
Thesecondmethodcanbeusedonlywithfunctionsthathaveareturnvalue.
Because these functions evaluate to a value (that is, their return value), they are valid C
expressionsandcanbeusedanywhereaCexpressioncanbeused.
Anexpressionwithareturnvalueusedastherightsideofanassignmentstatement.
Inthefollowingexample,half_of()isaparameterofafunction:printf("Halfof%dis%d.",x,half
_of(x))
First, the function half _of() is called with the value of x, and then printf() is called using the
valuesxandhalf_of(x).
In this second example, multiple functions are being used in an expression: y = half_of(x) +
half_of(z)
Althoughhalf_of()isusedtwice,thesecondcallcouldhavebeenanyotherfunction.
Thefollowingcodeshowsthesamestatement,butnotallononeline:
a=half_of(x)
b=half_of(z)
y=a+b
ExampleProgram
Blockstructure
Aprogramismadeupofoneormorefunctions,withoneofthesebeingmain().
Functionisaselfcontainedblockofprogramthatperformsaparticulartask.
Thisisthestructureoffunction
ExampleofBlockStructureofprogram:Howtocreateblocksusing{}andtheirsignificance.
PassingArgumentstoaFunction
Topassargumentstoafunction,listtheminparenthesesfollowingfunctionname.
The number of arguments and the type of each argument must match the parameters in the
functionheaderandprototype.
Forexample,ifafunctionisdefinedtotaketwotypeintarguments,onemustpassitexactlytwo
intargumentsnomore,nolessandnoothertype.
Ifonetriestopassafunctionanincorrectnumberand/ortypeargument,thecompilerwilldetect
it,basedontheinformationinthefunctionprototype.
Ifthefunctiontakesmultiplearguments,theargumentslistedinthefunctioncallareassignedto
thefunctionparametersinorder.
Thefirstargumenttothefirstparameter,thesecondargumenttothesecondparameter,andso
on.
Multipleargumentsareassignedtofunctionparametersinorder.
EachargumentcanbeanyvalidCexpression:aconstant,avariable,amathematicalorlogical
expression,orevenanotherfunction(onewithareturnvalue).
Forexample,ifhalf(),square(),andthird()areallfunctionswithreturnvalues,onecouldwriteas
follows:
x=half(third(square(half(y))))
Theprogramfirstcallshalf(),passingityasanargument.
Whenexecutionreturnsfromhalf(),theprogramcallssquare(),passinghalf()sreturnvalueas
anargument.
Next,third()iscalledwithsquare()sreturnvalueastheargument.
Then,half()iscalledagain,thistimewiththird()sreturnvalueasanargument.
Finally,half()sreturnvalueisassignedtothevariablex.
Thefollowingisanequivalentpieceofcode:
a=half(y)
b=square(a)
c=third(b)
x=half(c)
CallbyReference
Inthismethodtheaddressofanargumentiscopiedintotheparameter.
Page 159 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit6/assets/6.html 1/3
Functions
8/7/2015 scormcontent
Insidethesubroutinetheaddressisusedtoaccesstheactualargumentusedinthecall.
This means that the change made to the parameter affect the variable used to call the
subroutine.
Theaddressofxandyarepassedastheparametertothefunctionswap().
ThefollowingProgramdemonstratesacallbyReference.
CallbyValue
Thismethodcopiesvalueoftheargumentintotheformalparameterofthesubroutine.
Therefore changes made to the parameters of the subroutines have no effect on the variable
usedtocallit.
Thevalueoftispassedastheparametertothefunctionsqr().
ThefollowingProgramdemonstratescallbyvalue.
RecursiveFunctions
Thetermrecursionreferstoasituationinwhichafunctioncallsitselfeitherdirectlyorindirectly.
Indirect recursion occurs when one function calls another function that then calls the first
function.
Callowsrecursivefunctions,andtheycanbeusefulinsomesituations.
Forexample,recursioncanbeusedtocalculatethefactorialofanumberasshownbelow.
ThefollowingProgramdemonstratesrecursivefunction.
ArraysasFunctionArguments
Anargumentisavaluethatthecallingprogrampassestoafunction.
Itcanbeanint,afloat,oranyothersimpledatatype,butitmustbeasinglenumericalvalue.
Itcanbeasinglearrayelement,butitcantbeanentirearray.
Onecanhaveapointertoanarray,andthatpointerisasinglenumericvalue(theaddressof
thearraysfirstelement).
If one passes that value to a function, the function knows the address of the array and can
accessthearrayelementsusingpointernotation.
intlargest(intx[],inty)
Thelargest()isafunctionthatreturnsaninttothecallingprogramitssecondargumentisanint
representedbytheparametery.
The only thing new is the first parameter, intx[ ], which indicates that the first argument is a
pointertotypeint,representedbyparameterx.
Writethefunctiondeclarationandheaderasshownbelow:intlargest(int*x,inty)
Thisisequivalenttothefirstformbothintx[]andint*xmean"pointertoint."
Thefirstformmightbepreferable.
Theparameterrepresentsapointertoanarray.
Ofcourse,thepointerdoesntknowthatitpointstoanarray,butthefunctionusesitthatway.
ScopeofaVariable
The scope of a variable determines over what part(s) of the program a variable is actually
availableforuse(active).
Longevity:itreferstotheperiodduringwhichavariablesretainsagivenvalueduringexecution
ofaprogram(alive).
Local(internal)variables:arethosewhicharedeclaredwithinaparticularfunction.
Global(external)variables:arethosewhicharedeclaredoutsideanyfunction.
ScopeofaDeclaration
ScopeofadeclarationistheregionofCprogramtextoverwhichthatdeclarationisactive.
ToplevelidentifiersExtendsfromdeclarationpointtoendoffile.
FormalparametersinfunctionsExtendsfromdeclarationpointtoendoffunctionbody.
Block/function(local)identifiersExtendsfromdeclarationpointtoendofblock/function.
Extent
Theextentofanobjectistheperiodoftimethatitsstorageisallocated.
Anobjectissaidtohavestaticextentwhenitisallocatedstorageatorbeforethebeginningof
programexecutionandthestorageremainsallocateduntilprogramtermination.
All functions have static extent, as do all variables declared in toplevel declarations and
variablesdeclaredwiththestaticqualifier.
Formal parameters and variables declared at the beginning of a block or function have local
extent(dynamic,deallocatedonblock/functionexit).
Externalvariableorfunction
Atoplevelidentifieristreatedjustlikeastaticextentobjectinthefilecontainingitsdefinition,but
isalsoexportedtothelinker,andifthesameidentifierisdeclaredinanotherfile,thelinkerwill
ensurethetwofilesreferencethesameobject(variableorfunction).
Thus,toplevelidentifiersandfunctionsareexternalbydefault.
Theconventionistousetheexternqualifierinallplacesthataresimplydeclaringanidentifier
thatisdefined(allocated)inanotherfile,andtoomitthequalifieratthesinglepointwherethe
variableisactuallydefined(allocatedspace).
Thusexternalisthesameasglobalorpublic.
Astaticvariableorfunction:hasonlyfilescope,isnotexternal.
Thusstaticisthesameasprivate.
Examples
Variables,toplevel:
StorageClasses
Astorageclassdefinesthescope(visibility)andlifetimeofvariablesand/orfunctionswithinaC
Program.
TherearefollowingstorageclasseswhichcanbeusedinaCProgram
Auto,
Extern,
Static,
Register.
Automaticvariables
Aredeclaredinsideafunctioninwhichtheyaretobeutilized.
Aredeclaredusingakeywordauto.eg.autointnumber
Arecreatedwhenthefunctioniscalledanddestroyedautomaticallywhenthefunctionisexited.
Thesevariablesarethereforeprivate(local)tothefunctioninwhichtheyaredeclared.
Variables declared inside a function without storage class specification is, by default, an
automaticvariable.
Autoisthedefaultstorageclassforalllocalvariables.
Theexampleabovedefinestwovariableswiththesamestorageclass.
Autocanonlybeusedwithinfunctions,i.e.localvariables.
Exampleprogram
AboutAutoVariables
Anyvariablelocaltomainwillnormallylivethroughoutthewholeprogram,althoughitisactive
onlyinmain.
Duringrecursion,thenestedvariablesareuniqueautovariables.
Automaticvariablescanalsobedefinedwithinblocks.
Inthatcase,theyaremeaningfulonly,insidetheblockswheretheyaredeclared.
Ifautomaticvariablesarenotinitializedwillcontaingarbage.
Thefeaturesofautomaticvariablesare
Storagememory.
Defaultinitialvalueanunpredictablevalue,whichisoftenagarbagevalue.
Scopelocaltotheblockinwhichthevariableisdefined.
Lifetillthecontrolremainswithintheblockvariableisdefined.
ExternalVariables
Thesevariablesaredeclaredoutsideanyfunction.
Thesevariablesareactiveandalivethroughouttheentireprogram.
Alsoknownasglobalvariablesanddefaultvalueiszero.
Unlikelocalvariablestheycanbeaccessedbyanyfunctionintheprogram.
In case local variable and global variable have the same name, the local variable will have
precedenceovertheglobalone.
Sometimesthekeywordexternisusedtodeclarethesevariables.
Externisusedtogiveareferenceofaglobalvariablethatisvisibletoalltheprogramfiles.
Itisvisibleonlyfromthepointofdeclarationtotheendoftheprogram.
Theexternvariablecannotbeinitialized,asallitdoesis,pointthevariablenameatastorage
locationthathasbeenpreviouslydefined.
Whenaprogrammerhasmultiplefilesandhedefinesaglobalvariableorfunction,whichwillbe
used in other files also, then extern will be used in another file to give reference of defined
variableorfunction.
Externisusedtodeclareaglobalvariableorfunctioninanotherfile.
ExternalDeclaration
Asfarasmainisconcerned,yisnotdefined.
Socompilerwillissueanerrormessage.
Therearetwowayoutatthispoint
Defineybeforemain.
Declareywiththestorageclassexterninmainbeforeusingit.
ExternalDeclaration(Examples)
Notethatexterndeclarationdoesnotallocatestoragespaceforvariables.
ExternalVariable(Examples)
externinta=1,b=2
Externalvariableneverdisappear.
Because exist throughout the execution life of the program, they can be used to transmit
valueacrossfunctions.
Theymaybe,hiddeniftheidentifierisredefined.
Allfunctionshaveexternalstorageclass.
This means that the key word extern can be used in function definitions and in function
prototypes.
Forexample
externdoublesin(double)
Inafunctionprototype,forthesin()functionitsfunctiondefinitionwecanwrite
Anexternwithinafunctionprovidesthetypeofinformationjusttothatonefunction.
Theexterndeclarationdoesnotallocatestoragespaceforvariables.
Thefeaturesofexternalstorageclassvariableareasfollows:
Storagememory.
Defaultinitialvaluezero.
Scopeglobal.
Lifeaslongastheprogramexecutiondoesnotend.
Example
Hereexternkeywordisbeingusedtodeclarecountinanotherfile.
Nowcompilethesetwofiles.
Thisfileproducewriteprogramwhichcanbeexecutedtoproduceresult.
Countinmain.cwillhaveavalueof5.Ifmain.cchangesthevalueofcountwrite.cwillseethe
newvalue.
Whenthefunctionreferencesthevariablecount,itwillbereferencingonlyitslocalvariable,not
theglobalone.
GlobalVariableExample
Onceavariablehasbeendeclaredglobalanyfunctioncanuseitandchangeitsvalue.
Thesubsequentfunctionscanthenreferenceonlythatnewvalue.
StaticVariables
Thevalueofstaticvariablespersistsuntiltheendoftheprogram.
Itisdeclaredusingthekeywordstaticlike
staticintx
staticfloaty
Itmaybeofexternalorinternaltypedependingontheplaceofthedeclaration.
Staticvariablesareinitializedonlyonce,whentheprogramiscompiled.
Staticisthedefaultstorageclassforglobalvariables.
Thetwovariablesbelow(countandroad)bothhaveastaticstorageclass.
Staticvariablescanbeseenwithinallfunctionsinthissourcefile.
At link time, the static variables defined here will not be seen by the object modules that are
broughtin.
Staticcanalsobedefinedwithinafunction.
Ifthisisdone,thevariableisinitializedatruntime,butisnotreinitialized,whenthefunctionis
called.
Insideafunction,staticvariableretainsitsvalueduringvariouscalls.
Example
Thiswillproducefollowingresult
NOTE: Here keyword void means function does not return anything and it does not take any
parameter.
StaticFunction
Staticdeclarationcanalsobeusedtocontrolthescopeofafunction.
If one wants a particular function to be accessible only to the functions in the file in which it is
definedandnottoanyfunctioninotherfiles,declarethefunctiontobestatic.eg.
InternalStaticVariable
Arethosewhicharedeclaredinsideafunction?
Scope of Internal static variables extends up to the end of the program in which they are
defined.
Internalstaticvariablesarealmostsameasautovariableexcepttheyremaininexistence(alive)
throughouttheremainderoftheprogram.
Internalstaticvariablescanbeusedtoretainvaluesbetweenfunctioncalls.
Examples(InternalStatic)
Internalstaticvariablecanbeusedtocountthenumberofcallsmadetofunction.eg.
ExternalStaticVariables
Anexternalstaticvariableisdeclaredoutsideofallfunctionsandisavailabletoallthefunctions
intheprogram.
Anexternalstaticvariableseemssimilarsimpleexternalvariablebuttheirdifferenceisthatstatic
externalvariableisavailableonlywithinthefilewhereitisdefinedwhilesimpleexternalvariable
canbeaccessedbyotherfiles.
RegisterVariable
These variables are stored in one of the machines register instead of RAM and are declared
usingregisterkeyword.
Eg.registerintcount
Thismeansthatthevariablehasamaximumsizeequaltotheregistersize(usuallyoneword)
andcannothavetheunary&operatorappliedtoit(asitdoesnothaveamemorylocation).
Since register access are much faster than a memory access keeping frequently accessed
variablesintheregisterleadtofasterexecutionofprogram.
Registershouldonlybeusedforvariablesthatrequirequickaccesssuchascounters.
Itshouldalsobenotedthatdefiningregisterdoesnotmeanthatthevariablewillbestoredina
register.
restrictions.
Since only few variables can be placed in the register, it is important to carefully select the
variablesforthispurpose.
However,Cwillautomaticallyconvertregistervariablesintononregistervariablesoncethelimit
isreached.
Donttrytodeclareaglobalvariableasregister.Becausetheregisterwillbeoccupiedduringthe
lifetimeoftheprogram.
MultifileProgramsandExternVariables
MultiFilesStaticVariables
Introduction:DataTypes
Cprogramminglanguagewhichhastheabilitytodividethedataintodifferenttypes.
Thetypeofavariabledeterminesthekindofvaluesitmaytakeon.
Thevariousdatatypesare
SimpleDatatype:Integer,Real,Void,Char.
StructuredDatatype:Array,Strings.
UserDefinedDatatype:Enum,Structures,Unions.
StructureDataType
Astructureisauserdefineddatatypethatgroupslogicallyrelateddataitemsofdifferentdata
typesintoasingleunit.
Alltheelementsofastructurearestoredatcontiguousmemorylocations.
Avariableofstructuretypecanstoremultipledataitemsofdifferentdatatypesundertheone
name.
Asthedataofemployeeincompanythatisname,EmployeeID,salary,address,phonenumber
isstoredinstructuredatatypeemployee_detail.
DefiningStructure
Astructurehastodefined,beforeitcanused.
Thesyntaxofdefiningastructureis
ExampleofStructure
ThestructureofEmployeeisdeclaredas
Applicationofstructure
Structure is used in database management to maintain data about books in library, items in
store,employeesinanorganization,financialaccountingtransactionincompany.
StructureisusedinCprogrammingforfollowingpurposes
Clearingscreen.
Adjustingcursorposition.
Drawinganygraphicsshapeonthescreen.
Receivingakeyfromthekeyboard.
Findingoutthelistofequipmentattachedtothecomputer.
Changingthesizeofthecursor.
Formattingafloppy.
Hidingafilefromthedirectory.
Displayingthedirectoryofadisk.
Checkingthememorysize.
Sendingtheoutputtoprinter.
Interactingwiththemouse.
StructureVariables
A structure is a collection of one or more variables grouped under a single name for easy
manipulation.
Thevariablesinastructure,unlikethoseinanarray,canbeofdifferentvariabletypes.
AstructurecancontainanyofCsdatatypes,includingarraysandotherstructures.
Eachvariablewithinastructureiscalledamemberofthestructure.
DeclaringaStructureVariable
Astructurehastodeclared,afterthebodyofstructurehasdefined.
Thesyntaxofdeclaringastructureis
struct<struct_name><variable_name>
Theexampletodeclarethevariablefordefinedstructureemployee.
structemployeee1
Heree1variablecontains6membersthataredefinedinstructure.
StructureVariablesProgram
InitializationInitializingStructureMembers
Themembersofindividualstructurevariableareinitializingonebyoneorinasinglestatement.
Theexampletoinitializeastructurevariableis
AccessingStructureMembers
Thestructurememberscannotbedirectlyaccessedintheexpression.
Theyareaccessedbyusingthenameofstructurevariablefollowedbyadotandthenthename
ofmembervariable.
The method used to access the structure variables are e1.emp_id, e1.name, e1.salary,
e1.address,e1.dept_no,e1.age.
The data within the structure is stored and printed by this method using scanf and printf
statementincprogram.
Astructurenamedcoordthatcontainsboththexandyvaluesofascreenlocationisasfollows:
The struct keyword, which identifies the beginning of a structure definition, must be followed
immediately by the structure name, or tag (which follows the same rules as other C variable
names).
Withinthebracesfollowingthestructurenameisalistofthestructuresmembervariables.
Thevariabletypeandnamemustbeprovidedforeachmember.
Theabovestatementsdefineastructuretypenamedcoordthatcontainstwointegervariables,x
andy.
Theydonot,however,actuallycreateanyinstancesofthestructurecoord.
Inotherwords,theydontdeclare(setasidestoragefor)anystructures.
Therearetwowaystodeclarestructures.
Oneistofollowthestructuredefinitionwithalistofoneormorevariablenames.
Thesestatementsdefinethestructuretypecoordanddeclaretwostructures,firstandsecond,
oftypecoord.
Firstandsecondareeachinstancesoftypecoordfirstcontainstwointegermembersnamedx
andy,andsodoessecond.
Thismethodofdeclaringstructurescombinesthedeclarationwiththedefinition.
The second method is to declare structure variables at a different location in the source code
fromthedefinition.
Thestatementsalsodeclaretwoinstancesoftypecoord:
Thefollowingprogramshowsthestructureforrecordingstudents.
StructureAssignment
The value of one structure variable is assigned to another variable of same type using
assignmentstatement.
If the e1 and e2 are structure variables of type employee then the statement e1 = e2 assign
valueofstructurevariablee2toe1.
Thevalueofeachmemberofe2isassignedtocorrespondingmembersofe1.
Individualstructurememberscanbeusedlikeothervariablesofthesametype.
Structure members are accessed using the structure member operator (.), also called the dot
operator,betweenthestructurenameandthemembername.
Thus, to have the structure named first refer to a screen location that has coordinates x=50,
y=100,thecodeisasfollows:
first.x=50
first.y=100
To display the screen locations stored in the structure second, the code is as follows:
printf("%d,%d",second.x,second.y)
Whatistheadvantageofusingstructuresratherthanindividualvariables.
One major advantage is that a programmer can copy information between structures of the
sametypewithasimpleequationstatement.
Continuingwiththeprecedingexample,thestatement:
first=secondisequivalenttothisstatementasfollows,
first.x=second.x
first.y=second.y.
ProgramtoImplementtheStructure
StructureswithinStructures
Clanguageallowsavariableofstructuretypetobeamemberofsomeotherstructuretype.
Thesyntaxtodefinethestructurewithinstructureis
ExampleofStructurewithinStructure
AccessingStructureswithinStructures
Thedatamemberofstructurewithinstructureisaccessedbyusingtwoperiod(.)symbols.
Thesyntaxtoaccessthestructurewithinstructureis
struct_var.nested_struct_var.struct_member
ForExample:
e1.doj.day
e1.doj.month
e1.doj.year
NestedStructures
In the example a defined structure has been dealt with, that can hold the two coordinates
requiredforasinglepoint.
Oneneedstwosuchstructurestodefinearectangle.
One can define a structure as follows (assuming, of course, that one has already defined the
typecoordstructure):
Thisstatementdefinesastructureoftyperectanglethatcontainstwostructuresoftypecoord.
Thesetwotypecoordstructuresarenamedtopleftandbottomrt.
Theprecedingstatementdefinesonlythetyperectanglestructure.
Todeclareastructure,onemustincludeastatementsuchas:
structrectanglemybox
Onecouldhavecombinedthedefinitionanddeclaration,ashedidbeforeforthetypecoord:
To access the actual data locations (the type int members), one must apply the member
operator(.)twice.
Thus,theexpression:
mybox.topleft.x
Referstothexmemberofthetopleftmemberofthetyperectanglestructurenamedmybox.
Page 190 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit8/assets/7.html 1/2
Structures and Unions
8/7/2015 scormcontent
Todefinearectanglewithcoordinates(0,10),(100,200),onecanwrite.
StructuresandFunctions
InC,structurecanbepassedtofunctionsbytwomethods:
Passingbyvalue(passingactualvalueasargument).
Passingbyreference(passingaddressofanargument).
PassingStructurebyValue
Astructurevariablecanbepassedtothefunctionasanargumentasnormalvariable.
Ifstructureispassedbyvalue,changemadeinstructurevariableinfunctiondefinitiondoesnot
reflectinoriginalstructurevariableincallingfunction.
WriteaCprogramtocreateastructurestudent,containingnameandroll.
Askuserthenameandrollofastudentinmainfunction.Passthisstructuretoafunctionand
displaytheinformationinthatfunction.
PassingStructurebyReference
Theaddresslocationofstructurevariableispassedtofunctionwhilepassingitbyreference.
WriteaCprogramtoaddtwodistances(feetinchsystem)enteredbyuser.
Tosolvethisprogram,makeastructure.Passtwostructurevariable(containingdistanceinfeet
andinch)toaddfunctionbyreferenceanddisplaytheresultinmainfunctionwithoutreturningit.
ArrayofStructure
Clanguageallowscreatinganarrayofvariablesofstructure.
Thearrayofstructureisusedtostorethelargenumberofsimilarrecords.
Forexampletostoretherecordof100employeesthenarrayofstructureisused.
Themethodtodefineandaccessthearrayelementofarrayofstructureissimilartootherarray.
Thesyntaxtodefinethearrayofstructureis
Struct<struct_name><var_name><array_name>[<value>]
ForExample:
Structemployeee1[100]
StructuresContainingArrays
Onecandefineastructurethatcontainsoneormorearraysasmembers.
ThearraycanbeofanyCdatatype(int,char,andsoon).
Forexample,considerthedeclarationbelow.
Theabovestatementsdefineastructureoftypedatathatcontainsafourelementintegerarray
membernamedxanda10elementcharacterarraymembernamedy.
StructuresandArrays
Onecanthendeclareastructurenamedrecordoftypedataasfollows:
structdatarecord
Onecanaccessindividualelementsofarraysthatarestructuremembersusingacombinationof
thememberoperatorandarraysubscripts:
record.x[2]=100
record.y[1]=x
Thecharacterarraysaremostfrequentlyusedtostorestringsandthenameofanarray,without
brackets,isapointertothearray.
Becausethisholdstrueforarraysthatarestructuremembers,theexpression:
record.y
Isapointertothefirstelementofarrayy[]inthestructurerecord.
Therefore,onecouldprintthecontentsofy[]onscreenusingthestatement:
puts(record.y)
ArraysofStructures
Whatoneneedsisanarrayofstructuresoftypeentry.
Afterthestructurehasbeendefined,onecandeclareanarrayasfollows:
structentrylist[1000]
Thisstatementdeclaresanarraynamedlistthatcontains1,000elements.
Eachelementisastructureoftypeentryandisidentifiedbysubscriptlikeotherarrayelement
types.
Eachofthesestructureshasthreeelements,eachofwhichisanarrayoftypechar.
Structure is used to store the information of One particular object but if we need to store such
100objectsthenArrayofStructureisused.
Example
HereBookstructureisusedtoStoretheinformationofoneBook.
IncaseifweneedtostoretheInformationof100booksthenArrayofStructureisused.
b1[0]storestheInformationof1stBook,b1[1]storestheinformationof2ndBookandSoonWe
canstoretheinformationof100books.
ExampleProgram
Unions
Unionsaresimilartostructures.
Aunionisdeclaredandusedinthesamewaysthatastructure.
Thereasonforthisissimpleallthemembersofaunionoccupythesameareaofmemory.
Unionsaredefinedanddeclaredinthesamefashionasstructures.
Inunionsallthememberssharethespacewhichisaccordingtothespacerequirementofthe
largestmember.
Aunioncanbeinitializedonitsdeclaration.
Becauseonlyonemembercanbeusedatatime,onlyonecanbeinitialized.
Toavoidconfusion,onlythefirstmemberoftheunioncanbeinitialized.
The following code shows an instance of the shared union being declared and initialised:union
sharedgeneric_variable={@}
The generic variable union was initialized just as the first member of a structure would be
initialized.
Note:Theunioncanholdonlyonevalueatatime.
DefiningofUnion
Aunionhastodefined,beforeitcanbeused.
Thesyntaxofdefiningastructureis
To define a simple union of a char variable and an integer variable, one would write the
following:
Thisunion,shared,canbeusedtocreateinstancesofaunionthatcanholdeitheracharacter
valuecoranintegervaluei.
ThisisanORcondition.
Unlikeastructurethatwouldholdbothvalues,theunioncanholdonlyonevalueatatime.
UnionDataType
Aunionisauserdefineddatatypelikestructure.
Theuniongroupslogicallyrelatedvariablesintoasingleunit.
Theuniondatatypeallocatesthespaceequaltospaceneededtoholdthelargestdatamember
ofunion.
Theunionallowsdifferenttypesofvariabletosharesamespaceinmemory.
Thereisnootherdifferencebetweenstructureandunionthaninternaldifference.
Themethodtodeclare,useandaccesstheunionissameasstructure.
AccessingUnionMembers
Individualunionmemberscanbeusedinthesamewaythatstructurememberscanbeusedby
usingthememberoperator(.).
However,thereisanimportantdifferenceinaccessingunionmembers.
Onlyoneunionmembershouldbeaccessedatatime.
Because a union stores its members on top of each other, its important to access only one
memberatatime.
Thefollowingisanexampleforthis:
DifferencebetweenStructures&Union
Thememoryoccupiedbystructurevariableisthesumofsizesofallthemembersbutmemory
occupiedbyunionvariableisequaltospaceholdbythelargestdatamemberofaunion.
Inthestructureallthememberscanbeaccessedatanypointoftimebutinuniononlyoneof
unionmembercanbeaccessedatanygiventime.
WhatarePointers?
Apointerisaspecialvariablewhichholdstheaddressofthevariableithaspointedto.
BasicConceptofPointer
ConsideraboveDiagram
iisthenamegivenforParticularmemorylocation.
ConsideritsCorrespondingaddressbe65524andtheValuestoredinvariableiis5
Theaddressofthevariableiisstoredinanotherintegervariablewhosenameisjandwhichis
havingcorrespondingaddress65522
Thus,onecansaythat,j=&ii.e.,j=Addressofi.
Here j is not ordinary variable It is special variable and called pointer variable as it stores the
addressoftheordinaryvariable.
Itcanbesummarizedlike
I 5 65524
J 65524 65522
AddressoperatorinCprogramming
ItisDenotedby&
Whenusedasaprefixtoavariablename&operatorgivestheaddressofthatvariable.
Example:
&nGivesaddressonn.
HowAddressOperatorworks?
VisualUnderstanding
Considerthefollowingprogram
Afterdeclarationmemorymapwillbelikethis:
inti=5
int*ptr
Afterassigningtheaddressofvariabletopointer,i.eaftertheexecutionofthisstatement:ptr=
&i
InvalidUseofAddressOperator
ProgrammercannotuseAddressoperatorforAccessingAddressofLiterals.
OnlyVariableshaveAddressassociatedwiththem.
&75
(a+b)willevaluateadditionofValuespresentinvariables.
Outputof(a+b)isnothingbutLiteral,soonecannotuseAddressoperator.
&(a+b)
AgainaisCharacterLiteral,sohecannotuseAddressoperator.
&(a)
Declaringpointers
Apointerisanumericvariableand,likeallvariables,mustbedeclaredbeforeitcanbeused.
Pointervariablenamesfollowthesamerulesasothervariablesandmustbeunique.
Thischapterusestheconventionthatapointertothevariablenameiscalledp_name.
Thisisntnecessary,howeveronecannamepointerstoanythingwithinCsnamingrules.
Apointerdeclarationtakesthefollowingform:
typename*ptrname
Typename is any of Cs variable types and indicates the type of the variable that the pointer
pointsto.
The asterisk (*) is the indirection operator, and it indicates that ptrname is a pointer to type
typenameandnotavariableoftypetypename.
Pointerscanbedeclaredalongwithnonpointervariables.
char*ch1,*ch2/*ch1andch2botharepointerstotypechar*/
SyntaxforPointerDeclarationinC
data_type*<pointer_name>
Explanation
data_type
Typeofvariablethatthepointerpointsto
ORdatatypewhoseaddressisstoredinpointer_name.
Asterisk(*).
AsteriskiscalledasIndirectionOperator.
ItisalsocalledasValueataddressOperator.
ItIndicatesVariabledeclaredisofPointertype.
pointer_name.
MustbeanyValidCidentifier.
MustfollowallRulesofVariablenamedeclaration.
WaysofDeclaringPointerVariable
*canappearsanywherebetweenPointer_nameandDataType.
PointerAssignments
Toassignanaddresstoapointerwellneedanewoperator,the"addressof"operator.
Onceassigned,thepointerwillcontainthe"addressof"theassignedvariablenotitsvalue.
CodeExample:
int*xp//declaresxpasapointertoaninteger
xp=&x//xpreceivestheaddressofx
Pointervariablescanbe"assigned":
int*p1,*p2
p2=p1
Assignsonepointertoanother.
"Makep2pointtowherep1points".
Donotconfusewith:
*p1=*p2
Assigns"valuepointedto"byp1,to"valuepointedto"byp2.
Exampleprogram:PointerAssignments
Initialization
HowtoInitializePointerinCProgramming?
pointer=&variable
AboveisthesyntaxforinitializingpointervariableinC.
InitializationofPointercanbedoneusingfollowing4Steps
DeclareaPointerVariableandNotedowntheDataType.
DeclareanotherVariablewithSameDataTypeasthatofPointerVariable.
InitializeOrdinaryVariableandassignsomevaluetoit.
Nowinitializepointerbyassigningtheaddressofordinaryvariabletopointervariable.
ThefollowingexamplewillclearlyexplaintheinitializationofPointerVariable.
ExplanationofAboveProgram
Pointershouldnotbeusedbeforeinitialization.
ptrispointervariableusedtostoretheaddressofthevariable.
Storesaddressofthevariablea.
Nowptrwillcontaintheaddressofthevariablea.
Note:Pointersarealwaysinitializedbeforeusingitintheprogram.
Example:InitializingIntegerPointer
Likeregularvariables,uninitializedpointerscanbeused,buttheresultsareunpredictableand
potentiallydisastrous.
Untilapointerholdstheaddressofavariable,itisntuseful.
Theaddressdoesntgetstoredinthepointer.
Theprogrammustputittherebyusingtheaddressofoperator,theampersand(&).
Whenplacedbeforethenameofavariable,theaddressofoperatorreturnstheaddressofthe
variable.
Therefore,onehastoinitializeapointerwithastatementoftheform:pointer=&variable
The program statement to initialize the variable p_rate to point at the variable rate would
be:p_rate=&rate/*assigntheaddressofratetop_rate*/
Beforetheinitialization,p_ratedidntpointtoanythinginparticular.Aftertheinitialization,p_rate
isapointertorate.
PointersandVariableTypes
For the more common PC operating systems, an int takes two bytes a float takes four bytes,
andsoon.
Each individual byte of memory has its own address, so a multibyte variable actually occupies
severaladdresses.
How,then,dopointershandletheaddressesofmultibytevariables?
Hereshowitworks:Theaddressofavariableisactuallytheaddressofthefirst(lowest)byteit
occupies.
Thiscanbeillustratedwithanexamplethatdeclaresandinitializesthreevariables:
Page 210 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit9/assets/6.html 2/3
Pointers
8/7/2015 scormcontent
Thesevariablesarestoredinmemory.
In this, the int variable occupies two bytes, the char variable occupies one byte, and the float
variableoccupiesfourbytes.
Differenttypesofnumericvariablesoccupydifferentamountsofstoragespaceinmemory.
PointerArithmetic
SeetableandobserveHavedeclaredsomeofthevariablesandalsoassumedsomeaddress
fordeclaredvariables.
Onecanseeaddressofavariableafterperformingarithmeticoperations.
Expression Result
Address+Number Address
AddressNumber Address
AddressAddress Number
Address+Address Illegal
Itclearlyshowsthatonecanaddorsubtractaddressandintegernumbertogetvalidaddress.
Aprogrammercanevensubtracttwoaddressesbuthecannotaddtwoaddresses.
ArithmeticPointers(Incrementing)
Whenoneincrementsapointer,heisincreasingitsvalue.
Forexample,whenoneincrementsapointerby1,pointerarithmeticautomaticallyincreasesthe
pointersvaluesothatitpointstothenextarrayelement.
In other words, C knows the data type that the pointer points to (from the pointer declaration)
andincreasestheaddressstoredinthepointerbythesizeofthedatatype.
Supposethatptr_to_intisapointervariabletosomeelementofanintarray.
Ifexecutethestatementptr_to_int++thevalueofptr_to_intisincreasedbythesizeoftypeint
(usually2bytes),andptr_to_intnowpointstothenextarrayelement.
Likewise,ifptr_to_floatpointstoanelementofatypefloatarray,thestatement:ptr_to_float++
Increasesthevalueofptr_to_floatbythesizeoftypefloat(usually4bytes).
Thesameholdstrueforincrementsgreaterthan1.
If the value n is added to a pointer, C increments the pointer by n array elements of the
associateddatatype.
Therefore:ptr_to_int+=4
Increases the value stored in ptr_to_int by 8 (assuming that an integer is 2 bytes), so it points
fourarrayelementsahead.Likewise:ptr_to_float+=10
Increasesthevaluestoredinptr_to_floatby40(assumingthatafloatis4bytes),soitpoints10
arrayelementsahead.
ArithmeticPointers(incrementing)Program
ArithmeticPointers(decrementing)
Thesameconceptsthatapplytoincrementingpointersholdtruefordecrementingpointers.
Decrementingapointerisactuallyaspecialcaseofincrementingbyaddinganegativevalue.
Ifonedecrementsapointerwiththeor=operators,pointerarithmeticautomaticallyadjusts
forthesizeofthearrayelements.
ArithmeticPointers(decrementing)
Supposethatptr_to_intisapointervariabletosomeelementofanintarray.
Ifthisstatementisexecuted:ptr_to_intthevalueofptr_to_intisdecreasedbythesizeoftype
int(usually2bytes),andptr_to_intnowpointstothenextarrayelement.
Likewise,ifptr_to_floatpointstoanelementofatypefloatarray,thestatement:ptr_to_float
decreasethevalueofptr_to_floatbythesizeoftypefloat(usually4bytes).
ArithmeticPointers(decrementing)program
OtherPointerManipulations
Theonlyotherpointerarithmeticoperationiscalleddifferencing,whichreferstosubtractingtwo
pointers.
Ifonehastwopointerstodifferentelementsofthesamearray,onecansubtractthemandfind
outhowfaraparttheyare.
Again,pointerarithmeticautomaticallyscalestheanswersothatitreferstoarrayelements.
Thus,ifptr1andptr2pointtoelementsofanarray(ofanytype),thefollowingexpressiontells
howfaraparttheelementsare:ptr1ptr2.
Pointercomparisonsarevalidonlybetweenpointersthatpointtothesamearray.
Underthesecircumstances,therelationaloperators==,!=,>,<,>=,and<=workproperly.
Lowerarrayelements(thatis,thosehavingalowersubscript)alwayshavealoweraddressthan
higherarrayelements.
Thus,ifptr1andptr2pointtoelementsofthesamearray,thecomparison:ptr1<ptr2.
Istrueifptr1pointstoanearliermemberofthearraythanptr2does.
PointersandFunctions
Whentheprogramisexecuted,thecodeforeachfunctionisloadedintomemorystartingata
specificaddress.
Apointertoafunctionholdsthestartingaddressofafunctionitsentrypoint.
Thecodeforeachfunctionisloadedintomemorystartingataspecificaddress.
Likeotherpointers,onemustdeclareapointertoafunction.
Thegeneralformofthedeclarationisasfollows:
type(*ptr_to_func)(parameter_list)
WhatisfunctionPointer?
Functionpointer:Apointerwhichkeepsaddressofafunctionisknownasfunctionpointer.
ReturnType:None
void*(*ptr)() ptr=&display (*ptr)()
Parameter:None
ReturnType:Integer intresult
int*(*ptr)() ptr=&display
Parameter:None result=(*ptr)()
ReturnType:Float floatresult
float*(*ptr)() ptr=&display
Parameter:None result=(*ptr)()
ReturnType:Char charresult
char*(*ptr)() ptr=&display
Parameter:None result=(*ptr)()
Threestepstousepointertocallfunction:
DeclarePointerwhichiscapableofstoringaddressoffunction.
InitializePointerVariable.
CallfunctionusingPointerVariable.
Step1:DeclaringPointer
void*(*ptr)()
Declareadoublepointer.
Write()symbolafterDoublePointer.
voidrepresentsthat,functionisnotreturninganyvalue.
()representsthat,functionisnottakinganyparameter.
Step2:InitializingPointer
ptr=&display
Thisstatementwillstoreaddressoffunctioninpointervariable.
Step3:Callingafunction
(*ptr)()
using(*ptr)(),onecancallfunctiondisplay()
Example:FunctionhavingtwoPointerParametersandreturntypeasPointer.
Thisstatementdeclaresptr_to_funcasapointertoafunctionthatreturnstypeandpassesthe
parametersinparameterlist.
Herearesomemoreconcreteexamples:
The first line declares func1 as a pointer to a function that takes one type int argument and
returnsatypeint.
Thesecondlinedeclaresfunc2asapointertoafunctionthattakestwotypedoublearguments
andhasavoidreturntype(noreturnvalue).
The third line declares func3 as a pointer to a function that takes an array of pointers to type
charasitsargumentandreturnstotypechar.
Thefinallinedeclaresfunc4asapointertoafunctionthatdoesnttakeanyargumentsandhas
avoidreturntype.
InitializingandUsingaPointertoaFunction
Apointertoafunctionmustnotonlybedeclared,butalsoinitializedtopointersomething.
The"something"is,ofcourse,afunction.
Theresnothingspecialaboutafunctionthatgetspointedto.
The only requirement is that its return type and parameter list match the return type and
parameterlistofthepointerdeclaration.
Forexample,thefollowingcodedeclaresanddefinesafunctionandapointertothatfunction:
Becausethefunctionsquare()andthepointerphavethesameparameterandreturntypes,one
caninitializeptopointtosquareasfollows:p=square
Thenaprogrammercancallthefunctionusingthepointerasfollows:answer=p(x)
TheArraynameasPointers
Anarraynamewithoutbracketsisapointertothearraysfirstelement.
Thus, if a programmer has declared an array data[ ], data is the address of the first array
element.
For example, the following code initializes the pointer variable p_array with the address of the
firstelementofarray[].
p_arrayisapointervariable,itcanbemodifiedtopointelsewhere.
Unlikearray,p_arrayisntlockedintopointingatthefirstelementofarray[].
Example,itcouldbepointedatotherelementsofarray[].
PointerPointingtotheArrayofElements
ArrayandPointerarebackbonesoftheCProgramminglanguage.
Pointerandarray,botharecloselyrelated.
Arraynamewithoutsubscriptpointstofirstelementinanarray.
Example:OneDimensionalArray
inta[10]
Herea,a[0]bothareidentical.
Example:TwoDimensionalArray
inta[10][10]
Herea,a[0][0]bothareidentical.
Letxisanarray,iissubscriptvariable.
ProofoftheaboveFormula
Forfirstelementofarrayi=0
Thefirstelementofarrayisequivalentto*x.
Thus*(x+i)willgivesusvalueofithelement.
ArraysandPointers
Anarraynamewithoutbracketsisapointertothearraysfirstelement.
Therefore,onecanaccessthefirstarrayelementusingtheindirectionoperator.
Ifarray[]isadeclaredarray,theexpression*arrayisthearraysfirstelement,*(array+1)isthe
arrayssecondelement,andsoon.
Thisillustratestheequivalenceofarraysubscriptnotationandarraypointernotation.
Ifonecangeneralizefortheentirearray,thefollowingrelationshipsholdtrue:
ArraySubscriptNotationandPointers
StringsandPointers
Toallocateandinitializeastringistodeclareanarrayoftypecharasfollows:
charmessage[]="Thisisthemessage."
Onecouldaccomplishthesamethingbydeclaringapointertotypechar:
char*message="Thisisthemessage."
StringsandPointersprogram
ArrayofPointerstoTypechar
Thefollowingstatementdeclaresanarrayof10pointerstotypechar:
char*message[10]
Eachelementofthearraymessage[]isanindividualpointertotypechar.
One can combine the declaration with initialisation and allocation of storage space for the
strings:
char*message[10]={"one","two","three"}
Thisdeclarationdoesthefollowing:
Itallocatesspacesomewhereinmemoryandstoresthethreeinitializationstrings,eachwith
aterminatingnullcharacter.
Itinitializesmessage[0]topointtothefirstcharacterofthestring"one",message[1]topoint
tothefirstcharacterofthestring"two",andmessage[2]topointtothefirstcharacterofthe
string"three".
ArrayofPointers
Step1:ArrayofFunction
int(*arr[3])()
Abovestatementtellthatarrisanarrayofsize3.
Arraystoresaddressoffunctions.
Array stores address of function having integer as return type and does not takes any
parameter.
Step2:DeclaringArrayoffunctionPointer
int(*(*ptr)[3])()
Itisarrayoffunctionpointerwhichpointstoarrayoffunction.
Step3:Storefunctionnamesinsidefunctionarray
arr[0]=display
arr[1]=getch
Step4:StoreaddressoffunctionArraytoFunctionPointer
ptr=&arr
Step5:CallingFunction
Followingsyntaxisusedtocalldisplayfunction:(**ptr)()
Thissyntaxisusedtocallgetchfunction:v(*(*ptr+1))()
PointerstoStructures
Astructureisacollectionofvariableswithinonevariable.
Structurescanbetermedasavariablethataggregatesvariablesofdifferentorsimilartypes.
Thecorrelationofstructuresandpointersisverystrong.
Astructureprovidesaveryintuitivewaytomodeluserdefinedentities(records,packetformats,
imageheaders,etc.).
DefiningStructures
ExampleProgram:PointerstoStructures
DynamicMemoryAllocation
Ingeneral,therearetwotypesofstoragesavailableforvariables.
Theyare
(i)Stackand
(ii)Heapmemorystorages.
Thestackmemoryispermanentstorageareawheretheordinaryvariablescanbestored.
Theheapmemoryisthefreememoryareaavailableinthemainmemoryofthecomputerwhich
willbeusedfordynamicmemoryallocation.
InC,thereexistsasetofbuiltinfunctionswhichareusedtoallocatememorydynamicallytothe
deriveddatatypeslikearrays,structuresandunions.
Someoftheimportantfunctionsare:
(i)malloc()
(ii)calloc()and
(iii)free()
malloc()
Thegeneralsyntaxofthemalloc()functionis
pointervariable=(datatype*)malloc(no.ofbytestobeallocated)
Example
int*x,n
x=(int*)malloc(n*sizeof(int))
Here, x is the pointer variable of int data type and n is an int type variable which can hold the
valueofthesizeofthearraytobereadin.
The malloc() function allocates a single contiguous memory of n locations of int type for the
pointervariablex,suchthatxcanbecomelikeanarrayofnintvalues,andthememorylocation
addressofthefirstelementofthearrayisstoredinx.
Thiswillprovidetheunderstandingoftheconnectionbetweenthepointersandarrays.
Themalloc()functiondoesnotinitializetheallocatedmemorybydefault.
So,onehastoperforminitializationseparatelybeforeusingthem.
Fortheaboveexample,itcanbedonesimplyaswedoinitializationforanyarrayandisgiven
below.
for(i=0i<ni++)
x[i]=0
Ingeneral,malloc()functionisusedtoallocatememoryforbasicdatatypeslikeint,char,float,
anddouble.
Inordertoallocatememorydynamicallyforderiveddatatypeslikestructuresandunionscalloc
()functionisused.
calloc()
Thegeneralsyntaxofthecalloc()functionis
pointervariable=(datatype*)calloc(no.ofbytestobeallocated)
Example
int*x,n
x=(int*)calloc(n,sizeof(int))
The above example is similar to the malloc () function, but with the following changes. Here
therearetwoargumentsthatareusedtospecifythenumberofbytestobeallocated.
The calloc function allocates a number of blocks of memory in contiguous form and not as a
singlecontiguousblockofmemoryallocatedbymalloc()function.
Since the calloc () function allocates memory as number of blocks, even in the case of single
contiguousblockofmemoryisnotavailable.
The other important aspect is that the calloc () function initializes the allocated memory, by
default.
So,oneneednotinitializetheallocatedmemoryasinthecaseofmalloc()function.
This calloc () function is used to allocate memory for derived data types like arrays, structures
andunions.
Differencesbetweenmalloc()andcalloc()functions
Themaindifferencesbetweenthetwodynamicmemoryallocationfunctionsmalloc()andcalloc
()availableinCaregiveninTable:
malloc() calloc()
Itallocatessinglecontiguousblockofmemory Itallocatesnumberofblocksofmemoryin
only. contiguousform.
Memoryallocationisnotinitialized,bydefault. Memoryallocationisinitialized,bydefault.
Itisusedtoallocatememoryforbasicdata Itisusedtoallocatememoryforderiveddatatypes
types(likeint,char,floatanddouble). (likearrays,structuresandunions).
Page 227 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit9/assets/11.html 2/4
Pointers
8/7/2015 scormcontent
free()
Dynamicallyallocatedmemorywitheithercalloc()ormalloc()doesnotgetreturnonitsown.
Theprogrammermustusefree()explicitlytoreleasespace.
Syntaxoffree()
free(ptr)
Thisstatementcausesthespaceinmemorypointerbyptrtobedeallocated.
Examplesofcalloc()andmalloc()
WriteaCprogramtofindsumofnelementsenteredbyuser.Toperformthisprogram,allocate
memorydynamicallyusingmalloc()function.
WriteaCprogramtofindsumofnelementsenteredbyuser.Toperformthisprogram,allocate
memorydynamicallyusingcalloc()function.
SelfreferentialStructures
Astructurecanhavememberswhichpointtoastructurevariableofthesametype.
These types of structures are called selfreferential structures and are widely used in dynamic
datastructuresliketrees,linkedlist,etc.
Thefollowingisadefinitionofaselfreferentialstructure.
Here,nextisapointertoastructnodevariable.
Itshouldberememberedthatapointertoastructureissimilartoapointertoanyothervariable.
A selfreferential data structure is essentially a structure definition which includes at least one
memberthatisapointertothestructureofitsownkind.
Achainofsuchstructurescanthusbeexpressedasfollows.
The above illustrated structure prototype describes one node that comprises of two logical
segments.
One of them stores data/information and the other one is a pointer indicating where the next
componentcanbefound.
Severalsuchinterconnectednodescreateachainofstructures.
Thefollowingfiguredepictsthecompositionofsuchanode.
Thefigureisasimplifiedillustrationofnodesthatcollectivelyformachainofstructuresorlinked
list.
Page 231 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit10/assets/2.html 1/2
Self Referential Structures and Linked Lists
8/7/2015 scormcontent
Suchselfreferentialstructuresareveryusefulinapplicationsthatinvolvelinkeddatastructures,
suchaslistsandtrees.
Unlikeastaticdatastructuresuchasarraywherethenumberofelementsthatcanbeinserted
in the array is limited by the size of the array, a selfreferential structure can dynamically be
expandedorcontracted.
Operations like insertion or deletion of nodes in a self referential structure involve simple and
straightforwardalterationofpointers.
LinkedLists
AlinkedlistisausefulmethodofdatastoragethatcaneasilybeimplementedinC.
Thereareseveralkindsoflinkedlists,includingsinglelinkedlists,doublelinkedlists,andbinary
trees.
Eachtypeissuitedforcertaintypesofdatastorage.
Theonethingthattheselistshaveincommonisthatthelinksbetweendataitemsaredefined
byinformationthatiscontainedintheitemsthemselves,intheformofpointers.
This is distinctly different from arrays, in which the links between data items result from the
layoutandstorageofthearray.
CreationofaSinglyConnectedLinkedList
BasicsofLinkedLists
Eachdataiteminalinkedlistiscontainedinastructure.
Thestructurecontainsthedataelementsneededtoholdthedatabeingstoredthesedepend
ontheneedsofthespecificprogram.
Inaddition,thereisonemoredataelementapointer.
Thispointerproducesthelinksinalinkedlist.Heresasimpleexample:
Thiscodedefinesastructurenamedperson.
Forthedata,personcontainsonlya20elementarrayofcharacters.
Onegenerallywouldntusealinkedlistforsuchsimpledata,butthiswillserveasanexample.
Thepersonstructurealsocontainsapointertotypepersoninotherwords,apointertoanother
structureofthesametype.
Thismeansthateachstructureoftypepersoncannotonlycontainachunkofdata,butalsocan
pointtoanotherpersonstructure.
HeadPointer
Thisisidentifiedbyaspecialpointer(notastructure)calledtheheadpointer.
Theheadpointeralwayspointstothefirstelementinthelinkedlist.
The first element contains a pointer to the second element the second element contains a
pointertothethird,andsoonuntiloneencountersanelementwhosepointerisNULL.
Iftheentirelistisempty(containsnolinks),theheadpointerissettoNULL.
NOTE:Theheadpointerisapointertothefirstelementinalinkedlist.
Theheadpointerissometimesreferredtoasthefirstelementpointerortoppointer.
SelfReferentialStructuresandLinkedListsHeadandTail
TraversingLinkedList
A linked list is a data structure that is used to model such a dynamic list of data items, so the
studyofthelinkedlistsasoneofthedatastructuresisimportant.
Linkedlistisessentiallyanorderedlistofsomedatainwhichonecantraverseit(examineit)in
onlyonedirection.
Linkedlistismadeupofnodesthatconsistofdatasectionthatholdstheactualdataandalink
section,whichcontainsinformationaboutthenextnodeinthelist.
Usually, that link section contains a pointer to the next node, or in array implementation of the
list,anindexofthenextnode.
UsuallyLinkedListhasthefollowingfunctions:
Addaddsanelementattheendofthelist.
Add(position)addsanelementatacertainposition.
Remove(position)removesacertainelement.
Traversetraversesthelistandpossiblydisplayitscontentonthescreen.
IsEmptyfunctionthatchecksifthelistisemptyornotandpossiblyotherssuchasgetSize,
etc.
It is important to check the position parameter when Add (position) and Remove (position)
functionsarecalled.
Supposethelisthas5elementsintotal0to4.
ItwouldbelegaltocallAddorRemovewithpositionparameterintherangeof0to4andalsoit
wouldbelegaltocallAddwiththepositionparametervalueof5,whichwouldessentiallyadda
newNodeattheveryendofthelist(afterthe4thelement).
Thusintheabovelinkedlistof4elementsNode0hasapointertoNode1,Node1toNode2,
Node2toNode3.
Alsoneedtokeepapointertothefirstnodeinthelist,FirstNode(whichisNode0intheabove
example)tobeabletoaccessthelistatall.
Clearly,nextisusedtocreatealinktothenextnodeinthelist,hencethenamelinkedlist.
Linkedlistcanberepresentedgraphicallyasfollows:
StepsforTraversingthelinkedlist:
Step1:StartatthebeginningFirstNode.
Step2:Accessnodesdatasection.
Step3:Printoutthedataordoessomeotherworkperapplicationspecification.
Step4: Access the next node by using the link provided in the next section of the current
node.
Repeatstep2.
Dosteps2and3aslongasthelastnodeisnotreached.
Lastnodewillpointtonothinginitsnextsection.
Nothingisrepresentedvariouslydependingontheactualimplementation.
InsertionintoaLinkedList
AddinganElementtotheBeginningofaList
IftheheadpointerisNULL,thelistisempty,andthenewelementwillbeitsonlymember.
IftheheadpointerisnotNULL,thelistalreadycontainsoneormoreelements.
Ineithercase,however,theprocedureforaddinganewelementtothestartofthelististhe
same:
Createaninstanceofthestructure,allocatingmemoryspaceusingmalloc().
Setthenextpointerofthenewelementtothecurrentvalueoftheheadpointer.
ThiswillbeNULLifthelistisempty,ortheaddressofthecurrentfirstelementotherwise.
Maketheheadpointerpointtothenewelement.
Hereisthecodetoperformthistask:
AddinganElementtotheBeginningofaList:Example
AddinganElementtotheBeginningofadoublyLinkedList:Example
WARNING:
Itisimportanttoswitchthepointersinthecorrectorder.
Ifonereassignstheheadpointerfirst,onewilllosethelist.
Themalloc()isusedtoallocatethememoryforthenewelement.
Aseachnewelementisadded,onlythememoryneededforitisallocated.
Thecalloc()functioncouldalsobeused.
Oneshouldbeawareofthedifferencesbetweenthesetwofunctions.
Themaindifferenceisthatcalloc()willinitializethenewelementmalloc()willnot.
AddinganElementtotheEndoftheList
Toaddanelementtotheendofalinkedlist,oneneedstostartattheheadpointerandgo
throughthelistuntilonefindsthelastelement.
Createaninstanceofthestructure,allocatingmemoryspaceusingmalloc().
Set the next pointer in the last element to point to the new element (whose address is
returnedbymalloc()).
SetthenextpointerinthenewelementtoNULLtosignalthatitisthelastiteminthelist.
Hereisthecode:
Example:
AddinganElementtotheEndofthesinglylinkedlist:Example:
AddinganElementtotheEndofadoublyLinkedListExample:
AddinganElementtotheMiddleoftheList
When one is working with a linked list, most of the time one will be adding elements
somewhereinthemiddleofthelist.
Exactlywherethenewelementisplaceddependsonhowonekeepsthelistforexample,if
itissortedononeormoredataelements.
This process, then, requires that one first locates the position in the list where the new
elementwillgo,andthenaddit.
Inthelist,locatetheexistingelementthatthenewelementwillbeplacedafter.Letscallthis
themarkerelement.
Createaninstanceofthestructure,allocatingmemoryspaceusingmalloc().
Setthenextpointerofthenewelementtopointtotheelementthatthemarkerelementused
topointto.
Setthenextpointerofthemarkerelementtopointtothenewelement.(whoseaddressis
returnedbymalloc()).
Hereshowthecodemightlook:
Example:
DeletionfromaLinkedList
Deletinganelementfromalinkedlistisasimplematterofmanipulatingpointers.
Theexactprocessdependsonwhereinthelisttheelementislocated:
Todeletethefirstelement,settheheadpointertopointtothesecondelementinthelist.
Todeletethelastelement,setthenextpointerofthenexttolastelementtoNULL.
Todeleteanyotherelement,setthenextpointeroftheelementbeforetheonebeingdeleted
topointtotheelementaftertheonebeingdeleted.
Heresthecodetodeletethefirstelementinalinkedlist:head=head>next
Example
Deletionofanodefromalinkedlist
Deletinganelementfromthelist
Thefollowingarethecodestodeletethelastelementandtheelementinthemiddleofthelist:
Deletingfromthemiddleofalist
Thefollowingcodedeletesanelementfromwithinthelist:
After any of these procedures, the deleted element still exists in memory, but it is removed
fromthelistbecausethereisnopointerinthelistpointingtoit.
Thisisaccomplishedwiththefree()function.
ConceptofFilesWhatarefiles?
Many realworld problems handle large volume of data and in such situations external storage
deviceslikethefloppydiskandtheharddisksareused.
Dataisstoredinthesedevicesusingtheconceptoffiles.
Afileisacollectionofrelateddatastoredonaparticularareaofthedisk.
Filenames
Everydiskfilehasaname,andonemustusefilenameswhendealingwithdiskfiles.
Filenamesarestoredasstrings,justlikeothertextdata.
The rules as to what is acceptable for filenames and what is not, differ from one operating
systemtoanother.
FileOpeninginVariousModesandClosingofaFile
OpeningaFile
Theprocessofcreatingastreamlinkedtoadiskfileiscalledopeningthefile.
Whenoneopensafile,itbecomesavailableforreading(meaningthatdataisinputfromthefile
totheprogram),writing(meaningthatdatafromtheprogramissavedinthefile),orboth.
Afterworkingwiththefile,closethefile.
Toopenafile,usethefopen()libraryfunction.
Theprototypeoffopen()islocatedinSTDIO.Handitreadsasfollows:
This prototype tells the programmer that fopen() returns a pointer to type FILE, which is a
structuredeclaredinSTDIO.H.
The members of the FILE structure are used by the program in the various file access
operationsthereisnoneedtobeconcernedaboutthem.
However,foreachfilethathastobeopen,onemustdeclareapointertotypeFILE.
Thefopen(),thatfunctioncreatesaninstanceoftheFILEstructureandreturnsapointertothat
structure.
Aprogrammerusesthispointerinallsubsequentoperationsonthefile.
Iffopen()fails,itreturnsNULL.
Theargumentfilenameisthenameofthefiletobeopened.
Asnotedearlier,filenamecanandshouldcontainapathspecification.
Thefilenameargumentcanbealiteralstringenclosedindoublequotationmarksorapointerto
astringvariable.
Theargumentmodespecifiesthemodeinwhichtoopenthefile.
In this context, mode controls whether the file is binary or text and whether it is for reading,
writing,orboth.
Thedefaultfilemodeistext.
Valuesofmodeforthefopen()function.
FILE*ptrfile.
ptrfile=fopen("filename","mode").
Page 246 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit11/assets/3.html 2/4
File Processing
8/7/2015 scormcontent
r Opensthefileforreading.Ifthefiledoesntexist,fopen()returnsNULL
Opensthefileforwriting.Ifafileofthespecifiednamedoesntexist,itiscreated.Ifafileofthe
w
specifiednamedoesexist,itisdeletedwithoutwarning,andanew,emptyfileiscreated.
Opensthefileforappending.Ifafileofthespecifiednamedoesntexist,itiscreated.Ifthefile
a
doesexist,newdataisappendedtotheendofthefile.
Opensthefileforreadingandwriting.Ifafileofthespecifiednamedoesntexist,itiscreated.If
r+
thefiledoesexist,newdataisaddedtothebeginningofthefile,overwritingexistingdata.
Opensthefileforreadingandwriting.Ifafileofthespecifiednamedoesntexist,itiscreated.If
w+
thefiledoesexist,itisoverwritten.
Opensafileforreadingandappending.Ifafileofthespecifiednamedoesntexist,itiscreated.If
a+
thefiledoesexist,newdataisappendedtotheendofthefile.
DifferentStepstoOpenFile
Step1:DeclaringFILEpointer.
Firstlyoneneedspointervariablewhichcanpointtofile.
Thesyntaxfordeclaringthefilepointeris.
FILE*fp
Step2:Openingfilehello.txt
fp=fopen("filename","mode")
ClosingaFile
fclose()functioninFileHandling.
Whenaprogrammeropensafileinreadorwritemodethenheperformsappropriateoperations
onfileandwhenfileisnolongerneededthenheclosesthefile.
FILEclosewillflushoutalltheentriesfrombuffer.
Important
AfterperformingallOperations,FILEisnolongerneeded.
Fileisclosedusingfclose()function.
Allinformationassociatedwithfileisflushedoutofbuffered.
ClosingfilewillpreventmisuseofFILE.
Syntax:fclose()
intfclose(FILE*fp)
SimpleExample
WritingandReadingFileData
Aprogramthatusesadiskfilecanwritedatatoafile,readdatafromafile,oracombinationof
thetwo.
Onecanwritedatatoadiskfileinthreeways:
Firstway:Onecanuseformattedoutputtosaveformatteddatatoafile.
Oneshoulduseformattedoutputonlywithtextmodefiles.
The primary use of formatted output is to create files containing text and numeric data to be
readbyotherprogramssuchasspreadsheetsordatabases.
Secondway:Onecanusecharacteroutputtosavesinglecharactersorlinesofcharacterstoa
file.
Althoughtechnicallyitspossibletousecharacteroutputwithbinarymodefiles,itcanbetricky.
Onecanwritedatatoadiskfileinthreeways:
Oneshouldrestrictcharactermodeoutputtotextfiles.
Themainuseofcharacteroutputistosavetext(butnotnumeric)datainaformthatcanbe
readbyC,aswellasotherprogramssuchaswordprocessors.
Thirdway:Onecanusedirectoutputtosavethecontentsofasectionofmemorydirectlyto
adiskfile.
Thismethodisforbinaryfilesonly.
DirectoutputisthebestwaytosavedataforlaterusebyaCprogram.
When one wants to read data from a file, he has the same three options: formatted input,
characterinput,ordirectinput.
Thetypeofinputonewoulduseinaparticularcasedependsalmostentirelyonthenatureofthe
filebeingread.
Thedatawillbereadinthesamemodethatitwassavedin,butthisisnotarequirement.
FormattedFileInputandOutput
Formattedfileinput/outputdealswithtextandnumericdatathatisformattedinaspecificway.
Itisdirectlyanalogoustoformattedkeyboardinputandscreenoutputdonewiththeprintf()and
scanf()functions.
FormattedFileOutput
Formattedfileoutputisdonewiththelibraryfunctionfprintf().
Theprototypeoffprintf()isintheheaderfileSTDIO.H,anditreadsasfollows:
intfprintf(FILE*fp,char*fmt,...)
ThefirstargumentisapointertotypeFILE.
To write data to a particular disk file, pass the pointer that was returned when the file was
openedwithfopen().
Thesecondargumentistheformatstring.
Theformatstringusedbyfprintf()followsexactlythesamerulesasprintf().
Inotherwords,inadditiontothefilepointerandtheformatstringarguments,fprintf()takeszero,
one,ormoreadditionalarguments.
This is just like printf(). These arguments are the names of the variables to be output to the
specifiedstream.
Remember,fprintf()worksjustlikeprintf(),exceptthatitsendsitsoutputtothestreamspecified
intheargumentlist.
FormattedFileInput
Forformattedfileinput,usethefscanf()libraryfunction,whichisusedlikescanf(),exceptthat
inputcomesfromaspecifiedstreaminsteadoffromstdin.
Theprototypeforfscanf()is:
Intfscanf(FILE*fp,constchar*fmt,...)
The argument fp is the pointer to type FILE returned by fopen(), and fmt is a pointer to the
formatstringthatspecifieshowfscanf()istoreadtheinput.
Thecomponentsoftheformatstringarethesameasforscanf().
Finally, the ellipses (...) indicate one or more additional arguments, the addresses of the
variableswherefscanf()istoassigntheinput.
CharacterInputandOutput
Whenusedwithdiskfiles,thetermcharacterI/Oreferstosinglecharactersaswellaslinesof
characters.
Thelineisasequenceofzeroormorecharactersterminatedbythenewlinecharacter.
UsecharacterI/Owithtextmodefiles.
CharacterInput
Therearethreecharacterinputfunctions:getc()andfgetc()forsinglecharacters,andfgets()for
lines.
Thefunctionsgetc()andfgetc()areidenticalandcanbeusedinterchangeably.
Theyinputasinglecharacterfromthespecifiedstream.
Hereistheprototypeofgetc(),whichisinSTDIO.H:
intgetc(FILE*fp)
Theargumentfpisthepointerreturnedbyfopen()whenthefileisopened.
ThefunctionreturnsthecharacterthatwasinputorEOFonerror.
getc()wasusedinearlierprogramstoinputacharacterfromthekeyboard.
This is another example of the flexibility of Cs streamsthe same function can be used for
keyboardorfileinput.
Thegetc()FunctionProgram
Thefgets()Function
Toreadalineofcharactersfromafile,usethefgets()libraryfunction.
Theprototypeis:char*fgets(char*str,intn,FILE*fp)
The argument str is a pointer to a buffer in which the input is to be stored, n is the maximum
numberofcharacterstobeinput,andfpisthepointertotypeFILEthatwasreturnedbyfopen()
whenthefilewasopened.
Whencalled,fgets()readscharactersfromfpintomemory,startingatthelocationpointedtoby
str.
Characters are read until a newline is encountered or until n1 characters have been read,
whicheveroccursfirst.
By setting n equal to the number of bytes allocated for the buffer str, one prevents input from
overwriting memory beyond allocated space. (The n1 is to allow space for the terminating \0
thatfgets()addstotheendofthestring).
Ifsuccessful,fgets()returnsstr.
Page 252 of 260
file:///D:/NIELIT%20PROJECT/Final%20Product/C%20Review%20updated/unit11/assets/6.html 2/5
File Processing
8/7/2015 scormcontent
Theputc()Function
Thelibraryfunctionputc()writesasinglecharactertoaspecifiedstream.
ItsprototypeinSTDIO.Hisasshownbelow:intputc(intch,FILE*fp)
Theargumentchisthecharactertooutput.
Aswithothercharacterfunctions,itisformallycalledatypeint,butonlythelowerorderbyteis
used.
Theargumentfpisthepointerassociatedwiththefile(thepointerreturnedbyfopen()whenthe
filewasopened).
Thefunctionputc()returnsthecharacterjustwrittenifsuccessfulorEOFifanerroroccurs.
ThesymbolicconstantEOFisdefinedinSTDIO.H,andithasthevalue1.
Becauseno"real"characterhasthatnumericvalue,EOFcanbeusedasanerrorindicator(with
textmodefilesonly).
Thefputs()Function
Towritealineofcharacterstoastream,usethelibraryfunctionfputs().
Thisfunctionworksjustlikeputs().
Theonlydifferenceisthatwithfputs()onecanspecifytheoutputstream.
Also,fputs()doesntaddanewlinetotheendofthestringonemustexplicitlyincludeit.
ItsprototypeinSTDIO.His:
charfputs(char*str,FILE*fp)
Theargumentstrisapointertothenullterminatedstringtobewritten,andfpisthepointerto
typeFILEreturnedbyfopen()whenthefilewasopened.
Thestringpointedtobystriswrittentothefile,minusitsterminating\0.
Thefunctionfputs()returnsanonnegativevalueifsuccessfulorEOFonerror.
DirectFileInputandOutput
The direct file I/O most often when one has to save data to be read later by the same or a
differentCprogram.
DirectI/Oisusedonlywithbinarymodefiles.
Withdirectoutput,blocksofdataarewrittenfrommemorytodisk.
Directinputreversestheprocess:Ablockofdataisreadfromadiskfileintomemory.
Forexample,asingledirectoutputfunctioncallcanwriteanentirearrayoftypedoubletodisk,
andasingledirectinputfunctioncallcanreadtheentirearrayfromdiskbackintomemory.
ThedirectI/Ofunctionsarefread()andfwrite().
Thefwrite()Function
Thefwrite()libraryfunctionwritesablockofdatafrommemorytoabinarymodefile.
ItsprototypeinSTDIO.His:intfwrite(void*buf,intsize,intcount,FILE*fp)
Theargumentbufisapointertotheregionofmemoryholdingthedatatobewrittentothefile.
Thepointertypeisvoiditcanbeapointertoanything.
Theargumentsizespecifiesthesize,inbytes,oftheindividualdataitems,andcountspecifies
thenumberofitemstobewritten.
The argument fp is, of course, the pointer to type FILE, returned by fopen() when the file was
opened.
Thefwrite()functionreturnsthenumberofitemswrittenonsuccessifthevaluereturnedisless
thancount,itmeansthatanerrorhasoccurred.
Thefwrite()FunctionProgram
Thefread()Function
Thefread()libraryfunctionreadsablockofdatafromabinarymodefileintomemory.
ItsprototypeinSTDIO.His:intfread(void*buf,intsize,intcount,FILE*fp)
Theargumentbufisapointertotheregionofmemorythatreceivesthedatareadfromthefile.
Aswithfwrite(),thepointertypeisvoid.
Theargumentsizespecifiesthesize,inbytes,oftheindividualdataitemsbeingread,andcount
specifiesthenumberofitemstoread.
Notehowtheseargumentsparalleltheargumentsusedbyfwrite().
Again,thesizeof()operatoristypicallyusedtoprovidethesizeargument.
The argument fp is the pointer to type FILE that was returned by fopen() when the file was
opened.
Thefread()functionreturnsthenumberofitemsreadthiscanbelessthancountifendoffile
wasreachedoranerroroccurred.
Thefread()FunctionProgram
FileBuffering:ClosingandFlushingFiles
Whenonehasdonewithusingafile,oneshouldcloseitusingthefclose()function.
Thefclose()prototypeisasshownbelow
intfclose(FILE*fp)
TheargumentfpistheFILEpointerassociatedwiththestreamfclose()returns0onsuccessor
1onerror.
Whenoneclosesafile,thefilesbufferisflushed(i.e.writtentothefile).
Onecanalsocloseallopenstreamsexceptthestandardones(stdin,stdout,stdprn,stderr,
andstdaux)byusingthefcloseall()function.
Itsprototypeisasshownbelow:
intfcloseall(void)
Thisfunctionalsoflushesanystreambuffersandreturnsthenumberofstreamsclosed.
When a program terminates (either by reaching the end of main() or by executing the exit()
function),allstreamsareautomaticallyflushedandclosed.
However,itsagoodideatoclosestreamsexplicitlyparticularlythoselinkedtodiskfiles.
Theftell()andrewind()Functions
Tosetthepositionindicatortothebeginningofthefile,usethelibraryfunctionrewind().
Itsprototype,inSTDIO.H,is:
voidrewind(FILE*fp)
TheargumentfpistheFILEpointerassociatedwiththestream.
Afterrewind()iscalled,thefilespositionindicatorissettothebeginningofthefile(byte0).
Therewind()isusedtoreadsomedatafromthebeginningofthefileagainwithoutclosingand
reopeningthefile.
Theftell()andrewind()Functions
Todeterminethevalueofafilespositionindicator,useftell().
Thisfunctionsprototype,islocatedinSTDIO.Handreadsasfollows:
longftell(FILE*fp)
TheargumentfpistheFILEpointerreturnedbyfopen()whenthefilewasopened.
Thefunctionftell()returnsatypelongthatgivesthecurrentfilepositioninbytesfromthestartof
thefile(thefirstbyteisatposition0).
Ifanerroroccurs,ftell()returns1(oftypelong).
fseek()Function
More precise control over a streams position indicator is possible with the fseek() library
function.
Byusingfseek(),onecansetthepositionindicatoranywhereinthefile.
Thefunctionprototype,inSTDIO.H,isasfollows:
intfseek(FILE*fp,longoffset,intorigin)
TheargumentfpistheFILEpointerassociatedwiththefile.
Thedistancethatthepositionindicatoristobemovedisgivenbyitsoffsetinbytes.
Theargumentoriginspecifiesthemovesrelativestartingpoint.
Therecanbethreevaluesfororigin,withsymbolicconstantsdefinedinIO.H
feof()Function
Withabinarymodestream,onecantdetecttheendoffilebylookingfor1,becauseabyteof
datafromabinarystreamcouldhavethatvalue,whichwouldresultinaprematureendofinput.
Insteadthelibrarycanbeused.functionfeof(),whichcanbeusedforbothbinaryandtext
modefilesasshownbelow:
intfeof(FILE*fp)
TheargumentfpistheFILEpointerreturnedbyfopen()whenthefilewasopened.
Thefunctionfeof()returns0iftheendoffilefphasntbeenreached,oranonzerovalueifend
offilehasbeenreached.
Ifacalltofeof()detectsendoffile,nofurtherreadoperationsarepermitteduntilarewind()has
beendone,fseek()iscalled,orthefileisclosedandreopened.