Programming With C Notes

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 115

Programming w ith C-Lab

Prepared by Departments of CS
Pr ogr ammingwithC-Lab

TABLEOFCONTENTS

WEEK CONTENT PAGENO


FundamentalsofComputerHardware,IntroductiontoProgram
1 mingLanguages&Translators,DOS/UNIXCommands 3-23

Algorithms&Flowcharts,IntroductiontoC,History,StepsofLear
2 ningC,C–Tokens,DataTypes- 24-48
FormatSpecifiers,I/OStatements,Structureof
OperatorsinC,theirPrecedenceandAssociativity,ArithmeticEx
3 pressions/Instructions,Typecasting,Math.hfunctions,Sampl 49-64
eCPrograms

ControlStatements(Conditional):IfanditsVariants,Switch(Bre
4 ak),SampleCPrograms
65-81

GotoStatement,ControlStatements(Looping):While,Do..While
5 ,ForLoop,Continue&Break(Unconditional),NestedLoops,Sam 82-100
pleCPrograms

Arrays, One Dimensional Array: Declaration and


6 101-107
Initialization, Accessing Array Elements, Sample C
Programs
Two Dimensional Array: Declaration and
7 108-113
Initialization, AccessingArray
Elements,SampleCPrograms
Strings:Read &Write,“String.h”Predefined
8 Functions,SampleCPrograms
114-127

Pointers:Declarations,Types,PointerstoArrays,PointerstoCha
9 racterStrings,PointerstoPointers,ArrayofPointers
128-141

Structures:Definition,Syntax,NestedStructures,PointerstoStr
10 uctures,Unions:Definition,Syntax
142-151

Functions:Definition,Syntax,Terminology,FunctionDeclarati
11 on,Classification(ArgumentsandReturnType),StorageClasses 152-165
,SampleCPrograms

ParameterPassingTechniques,PassingParametersTypes,Recu
12 166-176
rsion

Files:Definition,Opening,Closingof
13 177-185
Files,ReadingandWritingofFiles,SampleCPrograms

BinaryFiles,RandomAccessingofFiles,Enum,Typedef,Preproc
14 186-199
essorCommands,SampleCPrograms

Pr epar ed by CS Page2
UNIT-1

Pr ogr ammingwithC-Lab

WEEK-1
1 Fundament alsofComputerHar dwar e

2 IntroductiontoPr ogr ammingLanguages&Translators

3 DOS/UNIXCommands
------------------
FundamentalsofComputerHardware

IntroductiontoComputers
Theterm“Computer”isderivedfromtheword‘compute’ ,whichmeanstocalculate.Acomputerisanele
ctronicdataprocessingsystem,whichworksveryfastandcapableofperformingbotharithmeticandlogic
alfunctions.
Computerperformsthefollowing3operationsinasequence:
1. Acceptsinputdata
2. Storesandprocessesthedatainrapidspeeds
3. Outputstherequiredinformationindesiredformat.
Characteristicsofacomputerare:
1. respondstoaspecificset of instructionsinawell-definedmanner.
2. canexecuteaprerecordedlistofinstructions.
Advantagesofcomputers:
1. Highspeed :Computershavetheabilitytoperformroutinetasksatagreaterspeedthanhumanbei
ngs.Theycanperformmillionsofcalculationsinseconds.
2. Accuracy: Computersare usedtoperformtasksinawaythatensuresaccuracy.
3. Storage:Computerscanstorelargeamountofinformation.Anyitemofdataoranyinstructionst
oredinthe memorycanberetrievedbythecomputeratlightningspeeds.
4. Automation :Computers canbeinstructed toperformcomplex tasks
automatically(whichincreasestheproductivity).
5. Diligence:Computerscanperformthesametaskrepeatedly&withthesameaccuracywithoutgett
ingtired.
6. Versatility:Computersareflexibletoperformboth simpleandcomplextasks.
7. Cost
effectiveness:Computersreducetheamountofpaperworkandhumaneffort,therebyreducing
costs.
Limitationsofcomputers:
1. Computersneedclear&completeinstructionstoperformataskaccurately.Iftheinstructionsaren
otclear& complete, thecomputerwill notproducethe requiredresult.
Pr ogr ammingwithC-Lab

2. Computerscannotthink.
3. Computerscannotlearnbyexperience.

HARDWARE
ComputerHardwareisthephysicalpartofacomputerorphysicalcomponentsofthecomputer,includingt
hedigitalcircuitry,asdistinguishedfromthecomputersoftwarethatexecuteswithinthehardware.Itrefer
stotheobjectsthatwecanactuallytouch.
Ex:inputandoutputdevices,processors,circuitsandthecables.

OrganizationofComputer

Thecomputerconsistsoffivefunctionallyindependentmainparts:

1. InputUnit
2. MemoryUnit
3. A.L.Unit
4. OutputUnit
5. ControlUnit

INPUTUNIT:
 Computeracceptscodedinformationthroughinputunitsandreadthedata.Themostwellknowni
nputdeviceiskeyword.
 Wheneverakeyispressedthecorrespondingletterordigitisautomaticallytranslatedintocorresp
ondingbinarycodeandtransmittedoveracabletothememoryortheprocessor.
 Muchothertype ofinputdevicesincludesjoystickandmouse.

MEMORYUNIT:
 Themainfunctionofthememoryistostoreprogramanddata.
 Therearetwoclassesofstoragecalledprimaryandsecondarymemory.
MEMORY

PRIMARY SECONDARY

FLOPPY
RAM ROM HARDDISK CDROM DVD FLASHDRIVE
DRIVE

RAM(RandomAccessMemory):Itisatemporarystorageanddatawillbeerasedwhenthesystemisturne
doff.
ROM(ReadOnlyMemory):Itisapermanentmemoryanddatawillnotbeerasedwhenthesystemisturned
off.

DATASTORAGE
 4bits=1Nibble
 8bits=1byte
 1024bytes=1kor1kb(kilobyte)
 1024KB=1MB(megabyte)
 1024MB=1GB(Gegabyte)
 1024GB=1TBCTerabytes
Althoughprimarystorageisessentialbutittendstobeexpensive.Thusadditional,cheapersecondarystor
ageisused.Largeamountsofdataandprogramsarestoredinsecondarystorage.

A.L.U :
MostcomputeroperationsareexecutedinA.L.U.oftheprocessor.A.L.U.standsforArithmetic&Logical
Unit.Consideratypicalexample:supposetwonumberslocatedinthememoryaretwotobeadded,theyare
broughtintotheprocessorandtheactualadditioniscarriedoutoftheA.L.U.Thesummaybestoredinthem
emoryorretainintheprocessor.

OUTPUTUNIT:The outputunitisthecounterpart
oftheinputunit.Itsfunctionistotheoutsideworld.Themosttypicalexampleof
suchdeviceisprinter,monitorandLCD.

CONTROLUNIT:CUcontrolstheoveralloperationsofthecomputeri.e.it
checksthesequenceofexecutionofinstructions,and,controlsandcoordinatestheoverallfunctioningof
theunitsof
computer.Thememoryunit,arithmetic&logicalunit,inputandoutputunit’sstoreandprocessinformati
onandperforminputandoutputoperations.Controlunitmustcoordinatetheoperationsoftheseunits.
SOFTWARE
SoftwareisaprogramorsetofinstructionsthatcausestheHardwaretofunctioninadesiredway.
Practicalcomputersystemsdividesoftwareintothreemajorclasses:
 Systemsoftwarehelpsrunthecomputerhardwareandcomputersystem.Itincludesoperatings
ystems,devicedrivers,diagnostictools,servers,windowingsystems,utilitiesandmore.
Example:WindowsOS,UnixOS,etc
 Programmingsoftwareusuallyprovidestoolstoassistaprogrammerinwritingcomputerprog
ramsandsoftwareusingdifferentprogramminglanguagesinamoreconvenientway.Thetoolsinc
ludetexteditors,compilers,interpreters,linkers,debuggers,andsoon.
Example:TurboC2,NetBeansIDE,etc
 Applicationsoftwareallowsenduserstoaccomplishoneormorespecific(non-
computerrelated)tasks.Typicalapplicationsincludeindustrialautomation,businesssoftware,e
ducationalsoftware,medicalsoftware,databases,andcomputergames.It
isusedtoautomateallsortsoffunctions.
Example:EzSchool,Wordprocessingtool,Games,etc
OPERATINGSYSTEM
Anoperatingsystemactsasaninterfacebetweenuserandcomputerhardware.Itprovidesauser-
friendlyenvironmentinwhichausermayeasilydevelopandexecuteprogramsinmoreflexiblemanner.
ThegoalsofOperatingSystem:
1. Convenience:OperatingSystemmakesacomputermoreconvenienttouse.
2. Efficiency:OperatingSystemallowsthecomputersystemresourcestobeusedinanefficientman
ner.
Acomputersystemhassomeresourceswhichmaybeutilizedtosolveaproblem.TheyareMemory,Proce
ssor(s),I/O,FileSystem,etc.TheOSmanagestheseresourcesandallocatesthemtospecificprogramsand
users.
ApplicationAreasofcomputers:
Computershaveproliferatedintovariousareasofourlives.Thesearebeingusedinlargenumberofareasto
performavarietyoftasks.Someoftheapplicationareasofthecomputerarelistedbelow:
 Education
 Entertainment
 Sports
 Advertising
 Medicine
 Science&Engineering
 Government
 Home
Computershavealso proliferatedinto areas
likebanks,investments,stocktrading,accounting,ticketreservation,militaryoperations,meteorologica
lpredictions,socialnetworking,businessorganizations,policedepartment,videoconferencing,tele-
presence,bookpublishing,webnewspapers,andinformationsharing.

I ntroductiontoProgramm ingLanguages&Translato rs

 Languageiswayofcommunicationbetweentwopersons.
 ComputerLanguagesarecommunicationbetweencomputerandperson.
 Computerscanunderstandonlymachineinstructions.Instructionsaretobegiveninmachineund
erstandablelanguage.
 Aprogramminglanguageisdefinedbyasetofrules.Itisaformalconstructedlanguage,desi
gnedtocommunicationinstructionstoacomputer.Programminglanguagescanbeusedtocreatep
rogramstocontrolthebehaviorof themachine.
 Aprogramisalistofinstructionsorstatementsfordirectingthecomputertoperformarequireddat
a-processingtask.

TYPES

Computer
Language

Machine Assembly HighLevel


Language Language Language

Machinelanguage:
 Atthelowestlevelcomputerunderstandsonly0and1.
 Programsexpressedintermsofbinarylanguagearecalledmachinelanguageandistheonlyonela
nguagecomputercanunderstand.
 Acomputer’sprogramminglanguageconsistsofstringsofbinarynumbers(0’sand1’s).
 Amachinelanguageprogrammer
o hastoknowthebinarycodeforeach operationtobecarriedout,
o mustalsobefamiliarwiththeinternalorganizationof thecomputer,
o mustalsokeeptrackofalltheaddressesofmainmemorylocationsthatarereferredtointhep
rogram.
 Themachinelanguageformatisslowandtediousasuserscouldnotrememberthesebinaryinstruct
ions.
AssemblylanguageandAssembler:
 Alowlevelfirstgenerationcomputerlanguage,popularduringearly1960s,whichusesabbreviati
onsormnemoniccodes(mnemonic
meansmindfull)foroperationcodesandsymbolicaddresses.Thissymbolicinstructionlanguag
eiscalledAssemblylanguage.
 Oneofthefirststepsinimprovingtheprogrampreparationwastosubstitutemnemonicsforoper
ationcodes.Themnemonicsaredifferentamongmakesandmodelsofcomputer.
 Secondstepwassymbolicaddressingtoexpressanaddressintermsofsymbolsconvenienttoth
eprogrammer.
 Anotherimprovementwastheprogrammerturnedtheworkofassigningandkeepingtrackofins
tructionaddressesovertothecomputer.
 ThemnemonicsareconvertedintobinarieswiththehelpofatranslatorknownasAssembler.

AssemblyLanguage Assembler

MachineLanguage

 TheprogramwrittenusingmnemonicsiscalledSourceProgramorassemblylanguageprogram,t
hebinaryformofthesourceprogramequivalentiscalledObjectProgram.
 Assemblerisusedtoconvertassemblylanguageintothemachinelanguage.
 Assemblylanguageprogramsarecommonlyusedtowriteprogramsforelectroniccontrolsusing
microprocessorse.g.,compilers,operatingsystems,animationincomputergraphicsandsoon.
 Assemblylanguageisrelativelyeasyforthehumanbeingscomparedtomachinelanguage.Progra
mswritingarefastercomparedtomachinelanguage.
 Assemblylanguageprogrammershouldknowdetailsofthearchitectureofthemachine.Assembl
ylanguageprogramsarenotportable.

Higherlevellanguagesandcompiler:
 InstructionswhicharewrittenusingEnglishlanguagewithsymbolsanddigitsarecalledhighleve
llanguagesandisclosertoournaturallanguage.
 ThecommonlyusedhighlevellanguagesareFORTRAN,BASIC,COBOL,PASCAL,PROLO
G,C,C++,JAVAetc.
 Thecompleteinstructionsetwritteninoneoftheselanguagesiscalledahighlevellanguageprogra
morcomputerprogramorsourceprogram.
 Inordertoexecutetheinstructions,thesourceprogramistranslatedintobinaryformbyacompiler
orinterpreter.
 Itisalsonecessarytocreateanexecutableprogramtoexecutetheinstructionsgiveninasourcepro
grambylinkingtheinputandoutputdeviceswithyourprogram.
 Alinker(anotherprogram)isusedtolinklibraryroutingandgenerateanexecutableprogramfrom
anobjectprogram.

Compiler:
Compilerisatranslatorthatconvertstheprograminstructionsfromhumanunderstandableform(hig
hlevellanguage)tomachineunderstandableform(machinelanguage)andthetranslatedprogramins
tructioniscalledobjectcode.Everyprogramminglanguagerequiresitsowncompilertotranslatethe
program.Acompilerisalsousedtotranslatesourceprogramintoanobjectprogram.Compilerconver
ts sourceprograminto objectprogramin termsofstages
calledpasses.Normally,mostofthecompilersusetwopassestoconvertsourceprogramintothemach
inelanguageprogram.

HighlevelLanguage
Compiler

MachineLanguage

Interpreter:
An interpreteris aprogramwhichtakesthe
sourceprogramlinebylineandconvertsintomachinecodebutexecuteeach
linebylineasitisentered.Thetranslationofthesourceprogramtakesplaceforeveryrunandisslowert
hanthecompiledcode.Aninterpretermustaccompanytheobjectcodetorunaprogram.Programmin
glanguagesBASIC,LISP,JAVAuseinterpreters.

HighlevelLanguage
Interpreter

MachineLanguage
DOS/UNI XCommands
DOSCommands
MS-DOS
Itwasdevelopedasearlyas1980byBillGatesattheageof19.DOSisasingleuserandsingletask operating
system.Itisacharacter user
interfaceoperatedwithkeyboardonly.Itisacollectionofprograms&otherfiles.Itisdesignedtoprovidea
methodoforganizingandusingtheinformationstoredondisks,applicationprograms,systemprogramsa
ndthecomputeritself.
FilesandFilenames:Afileisacollectionofrelatedinformation.Thefilesshouldhavesuitablenamesfor
theiridentificationinlateruse.
Rulesfornamingthefiles:<FILENAME>.<EXTENSION>
1. Filenamesshouldbeofonetoeight
charactersinlengthwithanoptionofonetothreecharacterextension
2. Filenamescanincludeanyoneofthefollowingcharacters:AtoZ(orat
o z)0to 9,$,&,#,@.%,(),{}, _
3. Thecharacterswhicharenotallowedare::,;+/\*asthesehavespecialmeaning.
5. (.)isusedtoseparatefirstpartoffilenamefromextension.(letter.txtetc.,)
6. Whenafilenameincludesanextension,itshouldbereferredalongwithitsextensionandnotonlyw
iththefirstpart
D irectories:Itisacollectionoffiles,size,dateandtimeofcreationoffiles.Adirectorymaycontaindirect
oriesalso.ThemaindirectoryofadriveiscalledRootDirectoryintowhichseveraldirectoriesandsub-
directoriescanexist.
Commands
1. Command:VER
Description:ItdisplaystheversionofoperatingsystemSyntax:C:\>
VER
ExampleOutput:MicrosoftWindows[Version5.1.7601]
2. Command:DATE
Description:Itdisplayscurrentdateandasksfornewdatein(mm)-(dd)-(YY)format.Ifnodate
istobechanged,theolddatecanberetainedbypressing enterkey.
Syntax:C:\>DATEExa
mpleOutput:
Thecurrentdateis:10/08/2012Entert
henewdate:(mm-dd-yy)

Pr epar edbyIT &CSE Page10


3. Command:TIME
Description: Itdisplayscurrenttimeandasksfornewtineandifnonewtimeis
tobeentered,pressingenterretainstheoldtime.
Syntax:C:\>TIMEExam
pleOutput:
Thecurrenttimeis:21:38:51.06Enterth
enewtime:
4. Command:TITLE
Description:Setsthewindowtitleforthecommandpromptwindow.Syntax:C:\>TITL
E[string]
where"string"specifiesthetexttoset thetitle.
ExampleOutput:
TITLECPNMLAB
CPNMLAB —  X

C:\>TITLECPNMLAB
COMMANDPROMPTWINDOW

5. Command:CLS
Description:ItclearsthescreenSyn
tax:C:\>CLS
ExampleOutput:ScreengetsclearedanddisplaysC:\>at thetop
6. Command:[DRIVE]:
Description:TochangethedriveletterinMS-DOS,typethedriveletterfollowedbyacolon.
Syntax:C:\>[drive]:Exa
mpleOutput:
C:\>D:{changesthedriveletterfromCtoD}D:\>
7. Command:MD
Description: It is used tomakea new directory(or sub-directory)
whichissubordinatetothecurrent(orroot)directory.
Syntax:C:\>MD<directory_name>Example
Output:C:\>MDIT_24

8. Command:CD
Description:Itisusedtochangefromonedirectorytotheother.Syntax:C:\>CD<dir
ectory_name>
ExampleOutput:
C:\>CDIT_24C:\
IT_24>
9. Command:CD..
Description:Goesbackonedirectory.Syntax:C
:\DIRECTORY_NAME>CD..
ExampleOutput:
C:\IT_24>CD..C
:\>
10. Command:CD\
Description:Goestothehighestlevel,therootofthedrive.Syntax:
C:\DIRECTORY_NAME\SUB_DIRECTORY>CD\
ExampleOutput:
C:\DocumentsandSettings\User>CD\C:\>
11. Command:COPYCON
Description:Itallowsthecreationof
afilethroughcommandprompt.Syntax:COPYCON<FILENAME>.<EXTENSION
>
Typecopyconfollowedbythenameofthefile.Afterthisyou'llbereturnedtoablankline,whic
histhestartofyourfile.EnterthelinesyouwanttoinsertintothefileandwhendonepressCtrl+
Ztocreate thefile.Ifyouwishtocancelthecreation of thefilepressCtrl+C.
ExampleOutput:
D:\IT_24>COPYCONsample.txtNa
me:Santosh
Branch:ITRank:
22000College:A
NITS
^Z[Ctrl+Z]
1file(s)copied.
D:\IT_24>
12. Command:TYPE
Description:Displaysthecontentsof
atextfileorfiles.Syntax:TYPE[drive:\path\filename]
ExampleOutput:
D:\IT_24>TYPEsample.txtNa
me:Santosh
Branch:IT
Rank:22000Coll
ege:ANITSD:\I
T_24>
13. Command:EDIT
Description:Editallowsausertoview,create,ormodifytheircomputerfiles.Syntax:EDIT[driv
e:\path\filename]
ToSavethefilePressAlt
+F,amenuappearsthatcontain"Save"option.ToExitthefilePressAlt+F,amenuappea
rsthatcontain"Exit" option.
14. Command:DIR
Description:displayscontinuouslyalistoffilesandsub-
directoriesinadirectory,displaystotalnumberoffiles,directories,bytesusedandremainingbyte
s(storage).
Syntax:D:\>DIR[drive:]
D:\>DIRF:{displayslist offilesanddirectoriesfromFdrive.}Attributes:
 DIR/p:pausesthelistingwheneverthescreenisfull.Nextscreenloadswhenanykeyispre
ssed.
 DIR/w:displaysfilesofdirectoryin5columnformat.Onlyfilenamesandextensionswill
bedisplayed.
 DIR/d:displaysfilesinwideformatandinsortedorder.
 DIR/ON:DisplaysallthefilesinAtoZorder.
 DIR/O-N:Displaysallfilesinreverse(ZtoA)order.
Wildcards:DIRcanalsobespecifiedwithwildcardcharacters(suchas*)
tolistfilessharingacommonelementinthefilenameorextension.
 D:\>DIR*.txt :listallfileswithextension.txt{textfiles}indriveD.
 D:\>DIRW*.*:listallfilesthatstartwith W&otherextensionsindriveD.
15. Command:DEL
Description:DeletesaspecifiedfileSyntax:DE
L{filename}
ExampleOutput:
D:\IT_24>DELsample.txt:Deletesfilesample.txtfromIT_24directoryD:\IT_24>DE
L*.txt:Deletesallfileswithextension.txt
D:\IT_24>DELW*.*: Deletes all files thatstartwithW &otherextensions.
16. Command:REN
Description:Changesthenameof
oldfilewithnewname.Syntax:RENold_file_namenew_file_name
ExampleOutput:
D:\IT_24>RENsample.txtSantosh24.txt
{Changesthefilesample.txttoSantosh24.txt}
17. Command:COPY
Description:Copyfilesfromoneplacetoanother.
Syntax:COPY[drive:\path]<sourcefile>[drive:\path]<destination>ExampleOutput:
D:\IT_24>COPYSantosh24.txtsantoshit.txt
{CopiesthefileSantosh24.txtwiththenamesantoshit.txtonthesamedirectory}
D:\IT_24>COPYsantoshit.txtC:\
{Copiesthefilesantoshit.txtwiththesamenameintoCdirectory}C:\>COPYD:\
IT_24\*.txtC:\
{Copiesallfileswithextension.txtwiththesamenamesintoCdirectory}C:\>COPYD:\
W*.*C:\
{Copies allfiles thatstartwithW&otherextensionswithsamenamesintoCdirectory}
18. Command:COLOR
Description:Setsthedefaultconsoleforegroundandbackgroundcolors.Syntax:COLO
R[attr]whereattrspecifiescolorattributeofconsoleoutput.
Color attributes arespecifiedby TWOhex digits--thefirstcorresponds
tothebackground;thesecondtheforeground.Eachdigitcanbeanyofthefollowingvalue
s:
0=Black 6=Yellow C=Light Red
1= Blue 7=White D=LightPurpleE=
2=Green 8=Gray LightYellowF=Bri
3=Aqua 9=LightBlueA=L ghtWhite
4=Red ightGreenB=Ligh
5=PurpleEx t Aqua
ampleOutput:
C:\>COLOR1F
{ChangesBackgroundColortoblueandforegroundcolortoBrightWhite}
19. Command:RD
Description:Removesordeletesadirectorywithaconditionthatdirectoryshouldbeempty.The
directorycanberemovedfromrootdirectory/maindirectory.
Syntax:RD[option]
[drive:]pathOptions:
 RD/sdirectory_name:Removesalldirectoriesandfilesinthespecifieddirectoryan
dthedirectoryitself&asksforconfirmation.Usedtodeletethedirectorytree.
 RD/qdirectory_name:Quietmode,donotaskifoktoremoveadirectorytreewith/S
ExampleOutput:
D:\ANITS>RDIT
{removesITdirectoryifitisemptyelsedisplaysDirectoryisnotempty}D:\ANITS>RD/sIT
IT,Areyousure(Y/N)?y
{removesITdirectoryevenwhennotemptyasitremovesalldirectoriesandfiles}D:\>RD/s/qA
NITS
{removesANITSdirectorywithoutconfirmationallthefiles.}
20. Command:COMP
Description:Comparescontentsoftwofiles.Synta
x:COMPfilename1filename2ExampleOutput:
D:\IT_24>COMPSantosh24.txtsantoshit.txtComparing
Santosh24.txtandsantoshit.txt...
FilescompareOK
D:\IT_24>COMPSantosh24.txtaa.txtCompar
ingSantosh24.txtandaa.txt...Filesaredifferent
sizes.
21. Command:FC
Description:Comparestwofilesanddisplaysthedifferencebetweenthem.Syntax:FCfilenam
e1filename2
ExampleOutput:
D:\IT_24>FCSantosh24.txtaa.txtComparingf
ilesSantosh24.txtandaa.txt
*****Santosh24.txtNa
me:SantoshBranch:IT
*****aa.txtS
antoshITRs5
0200
*****
22. Command:MORE
Description:Allowsinformationtobedisplayedonepageatatime.Displaysatextfiletothescree
n.
Syntax:MOREfilename
DIR|MORE
ExampleOutput:
D:\>DIR|MORE
VolumeindriveDisNewVolumeVolumeSeria
lNumberis96B5-3300DirectoryofD:\
11-10-201222:14 <DIR> ANITS
28-03-201222:03 15,543BooksandAuthors.docx
30-09-201216:26 <DIR> cmaterial
07-10-201212:56 186C.txt
--More--
11-10-201222:14 <DIR> ANITS
28-03-201222:03 15,543BooksandAuthors.docx
30-09-201216:26 <DIR> cmaterial
07-10-201212:56 186C.txt
03-02-201222:49

28,497WriteaCprogramtoprintallpermutationsofagivenstring.docx
59File(s) 44,477,964bytes
20Dir(s)64,920,227,840bytesfree
23. Command:START
Description:Startsaseparatewindowtorunaspecifiedprogramorcommand.Syntax:START[t
itle][/dpath]
ExampleOutput:
D:\>START"CPNM"/dC:

CPNMLAB —  X CPNM —  x
D:\>START"CPNM"/dC: C:\>

24. Command:FIND
Description:SearchesforatextStringinafileSyntax:FI
ND[OPTION]"string"file
ExampleOutput:
D:\IT_24>FIND"e"Santosh24.txt
----------SANTOSH24.TXT
Name:SantoshCollege:A
NITS
D:\IT_24>FIND/v"e"Santosh24.txt[Displaylinesnotcontainingstring]
----------SANTOSH24.TXT
Branch:ITRank:
22000
D:\IT_24>FIND/c"e"Santosh24.txt[Displaycountoflinescontainingstring]
----------SANTOSH24.TXT:2
D:\IT_24>FIND/n"e"Santosh24.txt[Displaylineswithnumberscontainingstring]
----------SANTOSH24.TXT
[1]Name:Santosh[4
]College:ANITS
D:\IT_24>FIND/i"E"Santosh24.txt[Ignorecaseofcharacters]
----------SANTOSH24.TXT
Name:SantoshCollege:A
NITS
25. Command:EXIT
Description:QuitstheCMD.EXEprogram(commandinterpreter).Syntax:EXIT
ExampleOutput:
D:\>EXIT{closesthecommandwindow}
26. Command:ATTRIB
Description:Displaysorchangesfileattributes.
Syntax:ATTRIB[+R|-R][+H|-H][drive:][path][filename]
+ Setsanattribute
- Clearsanattribute
H HiddenFileAttribute
R Read-
OnlyFileAttributeExampleOutput:
D:\IT_24>ATTRIB+RSantosh24.txt
{Setsthereadonlyattributetothefileandcannotbemodified}D:\IT_24>ATTRIB-
RSantosh24.txt
{Clearsthereadonlyattributetothefileandcanbemodified}D:\IT_24>ATTRIB+
HSantosh24.txt
{Setsthehiddenattributetothefileandcannotbeviewed}D:\IT_24>A
TTRIB-HSantosh24.txt
{Clearsthehiddenattributetothefileandcanbeviewed}

27. Command:PROMPT
Description:Changesthecmd.execommandprompt.Syntax:PRO
MPT[text]$G
ExampleOutput:
D:\>PROMPTCPNM$GCPNM>
{UsetheDOScommandstoexecute,staysincurrentdirectorywithgivenprompt}
{tocometoactualprompt,type‘prompt’andthenpressenter}

28. Command:PATH
Description:Displaysorsetsasearchpathforexecutablefiles&usedtoprovideaccesstofilesloc
atedonotherdirectories.
Syntax:PATH=“[[drive:]path”;ExampleOut
put:
D:\IT_24>PATH=“C:\WINDOWS\system32”;
{Setsthepathforsystem32directorytoinvokethefilesrequiredbyDOS}

29. Command:SORT
Description:Sortsinputinalphanumericorder.Syntax:SORT
[/r](enter)
[inputtext{enter}]
Ctrl+Z
[outputtext{sortedorder}]Example
Output:
D:\IT_24>SORT D:\IT_24>SORT/r
hatc hatc
atm atm
atba atba
tant tant
^Z[Ctrl+Z]ant ^Z[Ctrl+Z]mat
bat hat
cat cat
hat bat
mat{DisplaysinAToZorder} ant{DisplaysinZToAorder}
30. Command:TREE
Description:Displays thedirectories and subdirectories existing ina driveina
Treediagramwithoutfiles.Onlydirectorieswith<DIR>aredisplayed.
Syntax:TREEExamp
leOutput:
D:\networklab>TREEFolderP
ATHlisting
Volumeserialnumberis2475-
5834D:\NETWORKLAB
├───FTP
├───http
├───newtftp
├───remotehost
└───telnet
└───telnet

UNIXCommands

UNIXisoneofthemostversatileandpopularoperatingsystemsinthemarkettoday.Itwasdesignedanddev
elopedin1969toprovideanenvironmenttocreateprograms.It
becamepopularwithitsusagebeginningtospreadtoeducationalinstitutionsscientific
researchlaboratoriesandindustries.KenThompsonandDennisRitchiecreatedUNIX.
BasicUNIXCommands
man:Themancommanddisplaystheonlinemanualpages.Readsthemanualpageforacommand.
Syntax:mancommand_name

ls:Itisusedtolistallthefilesanddirectories.

ls–l:Itiscalledasthelonglist.Itdisplaysorlistsallthefileswiththeirpreferences.

ls–a:Thiscommandisusedtoviewallthehiddenfiles.

mkdir:Thiscommand is

usedtocreateadirectory.Syntax:mkdirdirname.cd:Thiscommandisusedforchanging

thedirectory

cddirectoryname.Thiscommandmovesto thenameddirectory.

cd.:Changesthehomedirectory.

cd..:Changesthe parentdirectory.
pwd: Thiscommanddisplaysthepathofthecurrentdirectory.

cp:Copiesthecontentsofonefiletoanother.Syntax:cpfile1file2

mv:This commandis usedtomoveor renamethefiles.Syntax: mvfile1file2

rm:Thiscommandis

usedforremovingordeletingadirectory.Syntax:rmfilermdir:Thiscommandisusedforremovin

gordeletingadirectory.
Syntax:rmdirdirectory
cat:Displaysafile.
Syntax:catfilenamecat:
Concatenatefiles.
Syntax:catfile1file2>file3
>:Redirectsstandardoutputtoafile.
Syntax:cat>filename
>>:Appendstandardoutputtoafile.
Syntax:cat>>filename
<:Redirect standardinputfrom afile.
Syntax:command<filename

more:Displaysafileapage atatime.
Syntax:morefilename

head:Displaysthefirstfewlinesof afile.
Syntax:head-n/ +nfilename
-n:nlinesfromthebeginningareprinted.
+n:n-1linesare skippedorstartsfrom nthline.

tail:Displaysthelastfewlines of afile.
Syntax:tail-nfilename
-n:nlinesfromendaredisplayed.

wc: Countnumberlines/words/charactersinfile.
Syntax:wc<option(s)>filename
-w:Todoawordcount.
-l:Tofindouthowmanylinesthefilehas.

grep:Grapregularexpressionsandpatterns.Itisusedtosearchforaparticularwordinafile.
Syntax:grep<option(s)>keywordfilename
-i:Ignoresthecaseoftheword.
-v:Printsthelinesthatdonotmatch.

Pr epar edbyIT &CSE Page20


-c:Printsonlythetotalcountofmatchedlines.

pipe:Itisusedtojointwoormorecommandswhereoutputof command1istheinputofcommand2.
Syntax:command1| command2

sort:Sortsthecontentordata.
Syntax:sort<option(s)>filename
-n:Numericsort.
-r:Reversesort.
-d:Directorysort.
who: Listsuserscurrentlyloggedin.
Syntax:who>filename

?:Matchesonecharacter.
* :Matchesanynumberofrecords.

whatis:Offersbriefdescriptionof acommand.

apropos:Matchescommandwiththespecifiedkeywordintheirmanpages.
Syntax:aproposkeyword.p

s:Listcurrentprocesses.

chmod:Changestheaccessrightsfornamedfile.
Syntax:chmod[options]filename
-u:User
-g:Group
-o:Others
-a:All
-r:Read
-w:Write
-x:Execute
-+:Addpermission
--:Takeawaypermission

df:Reportsthespaceleft onthefilesystem.
Syntax:%df

du:Thenumberofkilobytesusedbyeachsubdirectory.
Syntax:%du

nl:Appendslinenumber.Nonumberforemptyfiles.
egrep:Usefulformultiplepatternsmatchingcanbemadefilebasedby–foption.
Syntax:egrep<options>filename
-c+:Oneormoreoccurrencesofcharacter.
-c?:Zerooroneoccurrencesof character.
-a/b:Eitheraorb.
-(a):Regularexpression.

fgrep:Fastorfixedgrep.Itdoesnot
acceptregularexpression.Inthisonecommandisseparatedfromotherbynewline.
Syntax:fgerp‘abcnew linexyz’

tee:Directstheoutputtothestandardoutputdevice.
Syntax:tee<option>filename
-a:Appendstoafile.

find:Searchesforafile.
Syntax:find<option>filename
-atimen:Trueiffilewasaccessedndaysago
-ctimen:Trueiffilewascreatedndaysago.
-namepattern:Trueiffilenamematchespattern.
-print:Printnamesoffilesfound.

Cmp:Purpose:ComparetwofilesSyntax:c
mpfile1file2[skip1[skip2]]ReturnType:
1-filesareidentical
2- filesaredifferent.
>1-anerroroccurred.
Description:Thecmputilitycomparestwofilesofanytypeandwritestheresultstostandardoutput.Byd
efaultcmpissilentiffilesaresame;
iftheydiffer,thebyteandlinenumberatwhichthefirstdifferenceoccurredisreported.Bytesandlinesaren
umberedbeginningwithone.
Options:
-lprintsthebytenumberanddifferingbytevaluesforeachdifference.
-sprintsnothingfordifferingfiles.Returnexitstatusonly.
Theoptionalargumentsskip1andskip2arethebyteoffsetsfromthebeginningoffile1andfile2,respecti
vely,wherethecomparisonwillbegin.
Dept.ofIT,ANITSPage17
Example:$cmpgroup1group2group1group2differ:cahr47,line3

Diff:Purpose:Finddifferencesbetweentwofiles.
Syntax:diff[options]from-fileto-
file.ReturnType:
-0nodifference
-1somedifferencewerefound
-2trouble.
Description:-diffcomparescontentsofthetwofilesfrom-fileandto-file.
-Afilenameof–standsfortextreadfromstandardinput.
-Asspecialcasediff–comparescopyof standardinputtoitself.
-Iffrom fileisadirectoryandto-fileisnot,diffcomparesthefileinfrom-
Filewhosenameisthatofto-fileandvice-versa.Thenondirectoryfilemustnotbe.
-Ifbothfrom-fileandto-
filearedirectories,diffcomparescorrespondingFilesinbothdirectories,inalphabeticalorder.
Options:agreat allfilesastextandcompare thenline byline,eveniftheydonot
seemtobenext.Ignorechangesinamount ofwhitespace.
WEEK-2
1 Algorithms&Flowcharts

2 IntroductiontoC,History,StepsofLear ningC
3 C–Tokens,DataTypes-FormatSpecifiers,I/OStatements

4 StructureofCPr ogr am,SampleCPr ogr ams


------------------
Algo rithm s&Flowcharts
Algorithms
Algorithmisa method ofrepresenting thestep-by-steplogical procedureforsolvinga
problem.Aprogramwritteninanon-computerlanguageiscalledanalgorithm.Itisastep-by-
stepmethodofperforminganytask.
Theseareone
ofthemostbasictoolsthatareusedtodeveloptheprogramsolvinglogic.Theycanhavestepsthatrepeatorr
equiredecisionsuntilthetaskiscompleted.
PROPERTIES
Analgorithmmustpossessthefollowingproperties:
1) Fitness:Analgorithmmustterminateinafinitenumberof steps.
2) Definite:
Bydefinitewemeanthateachstepofalgorithmmustbepreciselydefinedsuchthatthereisnoambi
guityorcontradiction.
3) Effectiveness:Each stepmustbe effective,easilyconvertedintoprogram
statementandcanbeperformedexactlyinafiniteamountoftime.
4) Generality:Thealgorithmmustbecompletesothatitwillworksuccessfullyinsolvingalltheprob
lemsofparticulartypeforwhichitisdefined.
5) Input/Output:Eachalgorithmmusttakezero,oneormorequantitiesaninputdataandproduceon
eormoreoutputvalues.
Whilewritinganalgorithmwecanconcentrateonlyonthelogicandnotonlanguagesyntaxandoncethealg
orithmiswrittenwecancodethealgorithmincomputerlanguage.
Example1:Writeanalgorithmtofindthesumandaverageoftw onumbers
Step 1. Read the numbers a,
bStep 2. Compute the sum of a&b
Step 3. Store the result in variable
sStep 4. Divide the sum s by 2
Step 5. Store the result in variable
avgStep 6.Print the value of s and
avgStep 7. End of program.
Example2: FindArea, DiameterandCircumferenceofa Circle.
Step 1:Start
Step 2:Initialize PI to 0
Step 3:Read radius of the circle
Step 4:Calculate the product of radius with itself and PI value
Step 5:Store the result in variable areaStep
6:Calculate the product of radius with 2Step
7:Store the result in variable diameter
Step 8:Calculate the product of PI and diameter value
Step 9:Store the result in variable circumference
Step 10:Printthe value of area, diameter and circumference
Step 11:Stop

Example3:FindAreaandCircumferenceofa Rectangle.
Step 1:Start
Step 2:Read the values of length and breadth
Step 3:Calculate the product of length and breadth
Step 4:Store the result invariable area
Step 5:Calculate the sum of length and breadth
Step 6:Store the result in variable temp
Step 7:Calculate the product of 2 and temp
Step 8:Store the result in variable
circumferenceStep 9:Print the value of area and
circumferenceStep10: Stop

Flowcharts
INTRODUCTION
Theflowchartisameanofvisuallypresentingtheflowofdatathroughaninformationprocessingsyste
ms,theoperationsperformedwithinsystemandthesequenceinwhichtheyareperformed.
Aflowchartisapictorialrepresentationofanalgorithminwhichthestepsaredrawn,intheformofdifferen
tshapesofboxesandthelogicalflowindicatedbyinterconnectingarrows.
MeaningofaFlowchart
Aflowchartisadiagrammaticrepresentationthatillustratesthesequenceofoperationstobeperformedt
ogetthesolutionofaproblem.Oncetheflowchartisdrawn,itbecomeseasytowritetheprograminanyhi
ghlevellanguage.Hence,itiscorrecttosaythataflowchartisamustforthebetterdocumentationofacom
plexprogram.
ADVANTAGES:
Reasonsforusingflowchartsasaproblem-solvingtoolare:
 Makeslogicclear
 Communication:flowchartsareagoodwayofcommunicatingthelogicofasystemtoallconcern
ed.
 Using in coding, flowcharts actas a guideduring thesystem’s
analysisandprogramdevelopmentphase.
 Effectiveanalysis:problemcanbeanalyzedinmoreeffectiveway.
 Efficientprogrammaintenance:Themaintenanceofaprogrambecomeseasywiththehelpofflo
wchart.
 Properdocumentation:flowchartsserveasagoodprogramdocumentation.
DISADVANTAGES:
a) Complexlogic:Sometimes,theprogramlogicisquitecomplicated.Inthiscase,flowchartbeco
mescomplexandclumsy.
b) Alterationsandmodifications:Ifalterationsarerequiredtheflowchartmayrequirere-
drawingcompletely.
c) Theessentialsofwhat isdonecaneasilybe lostinthetechnicaldetailsofhowitisdone.
SYMBOLS:
Onflowchartsdifferentgeometricshapesareusedcalledflowchartsymbols.Somestandardsymbolsfor
drawingflowchartsare:

BasicFlowchartShapes
Thebasic5flowchartsymbolsare
1) Terminalblock
2) Input/Output
3) Processblock
4) Decisionblock
5) Flowlines.
GUIDELINES:
Thefollowingaresomeguidelinesinflowcharting:
a) Theflowchartshouldbeclear,neatandeasytofollow.Thereshouldnotbeanyroomforambiguityi
nunderstandingtheflowchart.
b) Theusualdirectionoftheflowofaprocedureorasystemisfromlefttorightortoptobottom.

c) Onlyoneflowlineshouldcomeoutorfromaprocesssymbol.

d) Onlyoneflowlineshouldenteradecisionsymbol,buttwoorthreeflowlines,oneforeachpossiblea
nswer,shouldleavethedecisionsymbol.

Three-waybranchdecision Two-waybranchdecision
e) Onlyoneflowlineisusedinconjunctionwithterminalsymbol.
f) Writewithinstandardsymbolsbriefly.Asnecessary,youcanusetheannotationsymboltodescribe
dataorcomputationalstepsmoreclearly.

g) Iftheflowchartbecomescomplex,itisbettertouseconnectorsymbolstoreducethenumberofflowl
ines.Avoidtheintersectionofflowlinesifyouwanttomakeitmoreeffectiveandbetterwayofcomm
unication.

Connector

h) Ensurethattheflowcharthasalogicalstartandfinish.
i) Itisusefultotestthevalidityoftheflowchartbypassingthroughitwithasimpletestdata.
Example1.Drawaflowcharttofindthesumandaverageoftw onumbers.

Example2.Drawaflowcharttofindthelargestofthreenumbers.
Example3:Drawaflowcharttocomputethefinalpriceofanitemafterfiguringinsalestax.

Example4:Writeapseudocodetocheckwhetherastudentispassedornot.

Differencesbetw eenAlgorithmandFlowchart

Algorithm Flowchart
Stepbystepprocedureforsolvingaprob Pictorialrepresentationofanalgorithm
lem
WritteninEnglish- Stepsofalgorithm are
likelanguagewithwords drawnintheformofshapesofboxesand
logicalflowwitharrows.
Explainshowacertainprocessisfol Maynothavedetailedinstructionsabo
lowedoraproblemsolved uthowthetasksaredone.
I ntroductiontoCLanguage,History,Stepsin Learning
Languageistheexpression ofthoughtinaspecified way.Itisabodyofwords,andset
ofmethodsofcombiningthem(calledgrammar),understoodbyacommunityandusedasaformofcommu
nication.

INTRODUCTION
Cisageneral-
purposeprogramminglanguageinitiallydevelopedbyDennisRitchiebetween1969and1973atBellLab
s.Cisarobustlanguagewhoserichsetofbuilt-
infunctionsandoperatorscanbeusedtowriteanycomplexprogram.Cisoneofthemostwidelyusedprogr
amminglanguagesofalltime.
OriginofC
Yea Language DevelopedBy Remarks
r196 ALGOL60 Internation toogener al,tooabstr act,no
0 alCommitt taspecificlanguage
196 CPL(Combined ee
CambridgeUniver sity toodifficulttolear nand
3 Pr ogr ammingLanguage) hardtoimplement
196 BCPL(BasicCombined MartinRichar d, coulddealonlyspecial
7 Pr ogr ammingLanguag CambridgeUniver sity problem
197 e)
B KenThompson,AT& coulddealonlyspecialpr
0 TBellLaboratories oblem,didnotsupportva
riousdatatypes
197 C DennisRitchie,AT&T programmingefficiency
2 BellLaboratories &relativelygoodmachine
efficiency&supportvarious
data types.

Cwastheoffshootoftheearlierlanguages‘BCPL’and‘B’.Itsupportshighlevelfeatureswithcommandsli
keif,else,gotoetcmakingitconvenienttouse.Italsosupportslow-
levelfeatureslikemanipulationofbitsandaddressingmemorylocationdirectlybyusingpointers.
Cmaybecalledasmiddlelevelprogramminglanguage.

Pr epar edbyIT &CSE Page30


Ccompilercombinesthecapabilitiesofanassemblylanguagewithfeaturesofhigh-
levellanguageandthereforeitiswellsuitedforwritingbothsystemsoftwareandbusinesspackages.

ApplicationAreasofC
 InitiallyCwasusedtodesignthesystemsoftwarelike90%ofUNIXoperatingsystemiswritteni
nClanguage.
 fordesigningapplicationsoftware
 InwritingDeviceDrivers.
 InINTERNETprotocols.
 Indevelopingtranslators.
 Inprintspoolersandotherutilities.

Getting StartedWithC
Communicatingwithacomputerinvolvesspeakingthelanguagethecomputerunderstands,whichimme
diatelyrulesoutEnglishasthelanguageofcommunicationwithcomputer.However,thereiscloseanalog
ybetweenlearningEnglishlanguageandlearningClanguage.
TheclassicalmethodoflearningEnglish
istofirstlearnthealphabetsusedinthelanguage,thenlearntocombinethesealphabetstoformwords,whic
hinturnarecombinedtoformsentencesandsentencesarecombinedtoformparagraphs.
LearningCissimilarandeasier.Insteadofstraight-
awaylearninghowtowriteprograms,wemustfirstknowwhatalphabets,numbersandspecialsymbolsar
eusedinC,thenhowusing
themconstants,variables,keywords,andreservedwordsareconstructed,andfinally how
arethesecombined to forman instruction. A groupofinstructions
wouldbecombinedlaterontoformfunctionsorprogram.

StepsinlearningEnglishLanguage:

Sentences
Vocabulary [grammerrules] Essaysor
Alphabets Paragraphs Books
[Words] Story

StepsinlearningClanguage:
VocabularyKeywords,ReservedWords,Identifiers

CharacterSet

Instructions[syntaxrules]
Functions Programs
CharacterSet
AnysymbolisreferredascharacterinClanguage.Acharacterdenotesanyalphabets(A,B,…Zor a,b,…
z),digits(0,1,2,3,4,5,6,7,8,9) orspecialsymbols(!@#~`%^&*(){}-
=+_{}
[]|\”/’<>:;)usedtorepresentinformation.ThischaractersetisusedtoformvocabularyofC(constants,variable
sandkeywords).
ASCIITable

ASC Symb Description ASC Symb Description ASC Symb Description


II ol II ol II ol
32 Space 64 @ atsymbol 96 ` graveaccent

33 ! exclamation 65 A 97 a

34 " doublequotes 66 B 98 b

35 # numbersign 67 C 99 c

36 $ dollarsign 68 D 100 d

37 % percentsign 69 E 101 e

38 & ampersand 70 F 102 f

39 ' singlequote 71 G 103 g


opening
40 ( 72 H 104 h
parenthe
closingp
41 ) 73 I 105 i
arenthesi
42 * asterisk 74 J 106 j

43 + plussign 75 K 107 k

44 , comma 76 L 108 l
UPPER LOWER
45 - Minus/hyphen 77 M 109 m

46 . period 78 N CASEALPHAB 110 n CASEALPHABE


ETS TS
47 / slash 79 O 111 o

48 0 zero 80 P 112 p

49 1 one 81 Q 113 q

50 2 two 82 R 114 r

51 3 three 83 S 115 s

52 4 four 84 T 116 t

53 5 five 85 U 117 u

54 6 six 86 V 118 v

55 7 seven 87 W 119 w

56 8 eight 88 X 120 x

57 9 nine 89 Y 121 y

58 : colon 90 Z 122 z

59 ; semicolon 91 [ openingbracke 123 { openingbrace


t
60 < lessthansign 92 \ backslash 124 | verticalbar

61 = equalsign 93 ] closingbracket 125 } closingbrace

62 > greaterthan 94 ^ caret 126 ~ equivalency-


tilde
63 ? Questionmark 95 _ underscore
C T OKENS

InaCProgram,thesmallestindividualunitsareknownasC-
Tokens.Programsarewrittenusingthesetokensandsyntaxoflanguage.Therearetotallysixtokens.Theyar
e:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. SpecialSymbols

C-Tokens

Special
Keywords Identifiers Constants Strings Operators
Symbols

Keywords:
Keywordsarethosewords,whosemeaning
isalreadyknowntotheCcompileri.e.theyarepredefinedwords.Thekeywordscannotbeusedasvariablen
ames.Thereareonly32keywordsavailableinC.Akeywordcan’tbeusedasavariablenamebecauseifwed
oso,wearetryingtoassignanewmeaningtothekeyword.
int struct for static
float union switch register
char typedef case extern
double enum default void
signed if break volatile
unsigned else continue sizeof
long while goto const
short do auto return

I dentifiers:
Identifiersrefertothenamesofvariable,functionsandarrays.Theseareuser-
definednamesandconsistofasequenceoflettersanddigits,withaletterasafirstcharacter.Bothuppercase
andlowercaselettersarepermitted,althoughlowercaselettersarecommonlyused.Theunderscorechara
cterisalsopermittedinidentifiers.
Constant s:
Constantsin‘C’refertofixedvaluesthatdonochangeduringtheexecutionofaprogram.Constantisamem
orylocationinwhichavaluecanbestoredandthiscannotbealteredduring theexecution
ofprogram.‘C’supportsseveraltypes ofconstants.Theyareillustratedbelow.

Constants

Numeric Character Logical

Single
Integer Real String
Character

IntegerConstants:
Anintegerconstantreferstoasequenceofdigits.Therearethreetypesofintegers,namelybinary,decimal,
octalandhexadecimal.
BinaryN umbers:ABinaryNumberismadeupofonly0sand1s.
Example:110100
RepresentationofaBinaryNumber
MS BinaryDigit LS
B B
8 7 6 5 4 3 2 1 0
2 2 2 2 2 2 2 2 2
25 12 6 3 1 8 4 2 1
6 8 4 2 6
Decimalintegersconsistofasetofdigits,0through9,precededbyanoptional-
or+sign.Spaces,commasandnon-digitcharactersarenotpermittedbetweendigits.
ValidExamples InvalidExamples1
123 5750
-321 20,000
0 2.5
654321 $1000
+78

ConversionofBinarytoDecimal
1011
Youwouldthisinterpretindecimalas:
Eigh Fou Tw On
ts( rs( os es
8) 3
1x2 plus 4)0x2
2
plus (21x2
1
plus (11x2
0

= 1x8 plus 0x4 plus 1x2 plus 1x1


= 8 plus 0 plus 2 plus 1
Thetotalis:11(indecimal)whichequal 8+0+
2+1Inotherwords,
10112 = 1110

ConversionofDecimaltoBinary

OctalIntegersconstantconsistsofanycombinationofdigitsfrom0through7witha0atthebeginning.Oc
talisfancyforBaseEightmeaningeightsymbolsareusedtorepresentallthequantities.Theyare0,1,2,3,4,
5,6,and7.Someexamplesofoctal
integersare026,0,0347,and0676

Octal 0 1 2 3 4 5 6 7 1 1 12 1 20 30 7 10
0 1 … 7 … … 7 0
Decima 0 1 2 3 4 5 6 7 8 9 10 1 16 24 6 64
l … 5 … … 3
OctaltoDecimalConversion
Justlikehowweusedpowersoftenindecimalandpowersoftwoinbinary,todeterminethevalueofanumbe
rwewillusepowersof8sincethisisBaseEight.Considerthenumber3623inbaseeight.
8 8 8 8
3 2 1 0
3 6 2 3
1536+384+16+3

1939

HexadecimalintegerconstantisprecededbyOXorOx,theymaycontainalphabetsfromAtoForatof.Th
ealphabetsAtoFreferto10to15indecimaldigits.ThehexadecimalsystemisBaseSixteen.
Examplesofvalidhexadecimalintegersare0X2,0x8C,0Xbcd,and0x
Hexadecimal 9 A B C D E F 1 11 1 1 1 1C 9F A0
0 … 9 A B …
Decimal 9 1 1 1 1 1 1 1 17 2 2 2 28 15 16
0 1 2 3 4 5 6 5 6 7 9 0
Digitsareexplainedaspowersof16.Considerthehexadecimalnumber2DB7.
16 16 1 16
2
3 61 0
2 D B 7
8192+3328+176+7

11703

RealConstants:
RealConstantsconsistsofafractionalpartintheirrepresentation.Integerconstantsareinadequatetorepre
sentquantitiesthatvarycontinuously.Thesequantitiesarerepresentedbynumberscontainingfractional
partslike26.082.
Examplesofrealconstantsare0.0026,-0.97,435.29,+487.0

Thesenumbersareshownindecimalnotation,havingawholenumberfollowedbyadecimalpointandthef
ractionalpart.Itispossibletoomitdigitsbeforethedecimal pointordigitsafterthedecimalpoint.That
is,215.;.95;-.71;+.5areallvalidrealnumbers.

Arealnumbermayalsobeexpressedinexponential(orscientific)notation.Forexample,
215.65 maybewrittenas2.1565e2inexponentialnotation,e2meansmultiplyby102.Thegeneralformis
:
mantissaeexponent
Themantissaiseitherarealnumberexpressedindecimalnotationoraninteger.The

exponent isanintegernumberwithanoptionalplusandminussign.Thelettere
separating themantissaand theexponentcanbe written in eitherlowercaseor
uppercase.Theexponentcausesthedecimalpointto"float",thisnotationissaidtorepresentarealnumberi
nfloatingpointform.
Examplesoflegalfloatingpointconstantsare:0.65e4,12e-2,1.5e+5,3.18E3,-1.2E-1
Whitespacesarenotallowed.Exponentialnotationisusefulforrepresentingnumbersthatareeitherveryl
argeorverysmallismagnitude.E.g.7500000000-->7.5e9or75e8.

SingleCharacterConstants
Asingecharacterconstantcontainsasinglecharacterenclosedwithinapairofsinglequotemarks.
Examplesofsinglecharacterconstantsare:'5','x','',';'.Thecharac
terconstant'5'isnotsameasthenumber5.
StringConstants
Astringconstantisasequenceofcharacterenclosedindoublequotes.Thecharactersmaybeletters,numb
ers,specialcharactersandblankspace.
Examplesare"Hello!","1987","WELLDONE","5+3","X"

Logical Constant : Alogicalconstantcantakeeitheratrueorafalseasvalue.InC,


 Zero(0)representsfalsevalue.
 Anynon-zerovaluesuchas1representstruevalue.

BackslashCharacterConstants[EscapeSequences]
Backslashcharacterconstantsarespecialcharactersusedinoutputfunctions.Althoughtheycontaintwoc
haracterstheyrepresentonlyonecharacter.Givenbelowisthetableofescapesequenceandtheirmeanings
.
Constant Meaning
'\a' AudibleAlert(Bell)
'\b' Backspace

'\f' Formfeed

'\n' New Line

'\r' CarriageReturn

'\t' Horizontaltab

Constant Meaning

'\v' VerticalTab

'\'' SingleQuote

'\"' DoubleQuote

'\?' QuestionMark
'\\' BackSlash

'\0' Null

V ariables:
InC,aquantity,whichmayvaryduringtheprogramexecution,iscalledavariable.Variablenamesarethen
amesgiventothememorylocationsofacomputerwherethevariablevalueisstored.
Avariableisanamethatisusedtostoredatavalueandisallowedtovarythevalueduringtheprogramexecuti
on.Avariableisabletoholddifferentvaluesduringexecutionofaprogram,whereasaconstantisrestricted
tojustonevalue.Variablename
canbechosenbytheprogrammerinameaningfulwaysoastoreflectitsnatureintheprogram.

LengthofCvariablenamecanbeupto8charactersandsometranslatorspermitevenahigherlength(32).
Itmaytakedifferentvaluesatdifferenttimesduringprogramexecution.

Variablenamesmayconsistofletters,digits,andunderscoresubjectedtofollowingconditions:
 Theymustbeginwithaletterorunderscore(_),followedbyanynumberofletters,digits,orund
erscores.
 Uppercaseisdifferentfromlowercase,sothenamestotal,Total,andTOTALspecifythreediff
erentvariables.
 Thevariablenameshouldn’tbeakeyword.
 Blankspacesarenotallowed.
 Thelengthshouldbenormally8characters(sinceonlythefirst8characterstreatedassignifican
tbymanycompilers).
 Thevariablenamesarecasesensitive.
 Thevariablesaredefinedatthebeginningoftheblock.
Forexample,intheequation 2x+3y=10;sincexandycanchange,theyarevariables,whereas2,3and
10cannotchange,hencetheyare constants.Thetotalequationisknownasexpression.
Validvariablenames:Alpha,X,fyear_9899,matrix,income

DATATYPES
AClanguageprogrammerhastotellthesystembefore-hand,thetypeofnumbersorcharacters
heisusinginhisprogram.
Thesearedatatypes.TherearemanydatatypesinClanguage.ACprogrammerhastouseappropriatedatat
ypeasperhisrequirement.

Datatypeistheinstructiontothecompilertellingaboutwhattypeofvaluewillbestoredinamemorylocatio
nandalsotospecifytheamountofmemoryrequiredforlocation.

Clanguagedatatypescanbebroadlyclassifiedas
 Primarydatatypes
 Deriveddatatypes
 User-defineddatatypes
PrimaryDataTypes

IntegerType:
Integersarewholenumberswithamachinedependentrangeofvalues.Generally,integers occupy
onewordofstorageandsincewordsizes ofmachines vary (typically,16or32bits),thesize
ofanintegerthat canbestoreddependsonthecomputer.
Chas3classesofintegerstoragenamelysℎortint,intandlongint.Allofthesedata
typeshavesignedandunsignedforms.Signed numbersarepositiveornegativeandone
bitisusedforsignandrestofthebitsforthemagnitudeofthenumber.Unsignednumbersarealwayspositiv
eandconsumeallthebitsforthemagnitudeofthenumber.
A sℎortint
representssmallintegervaluesandrequireshalfthespacethannormalintegervalues.Thelongandunsign
edlongint areusedtodeclarealongerrangeof
values.

Size Siz
Type Range
(inByte e(inB
intorsignedint 2 s) 16its) −32768 to32767
unsignedint 2 16 0to65535
sℎortintorsi
gnedsℎortint 1 8
−128to127
unsignedsℎortint 1 8 0to255
longintors
ignedlongin
t 4 32
−2147483648 to2147483647
unsignedlongint 4 32 0to4294967295
Tofindtherangeofthesesigneddatatypeweusetheformula,−2n-1to+2n-1−1

Tofindtherangeoftheseunsigned datatypewe usetheformula,0to2n−1


CharacterDataType

Asinglecharactercanbedefinedasacharacter(cℎar)typedata.Charactersareusually
storedin8bits(1byte)ofinternalstorage.Thequalifiersignedorunsignedmaybe
explicitlyappliedtochar.Unsignedcharactershavevaluesbetween0to255,Signedcharactershavevalu
esfrom-128to+127.
Size Siz
Type Range
(inByte e(inB
cℎarorsignedcℎar 1 s) 8 its) −128to127
unsignedcℎar 1 8 0to255
FloatingPointTypes
Floatingpointnumbersarestoredin32bits(onall16bitand32bitmachines),with6

digitsofprecision.Floatingpointnumbersare definedinCby thekeywordfloat.


Whentheaccuracyprovidedbyafloatnumberisnotsufficient,thetype
thenumber.Thisisalsocalledlongfloat.Adoubledatatypenumberuses doublecanbeusedtodefine
64 bits givingaprecisionof14 digits. These areknown as doubleprecisionnumbers. The
double representsthesamedatatypethatfloatrepresents,butwithgreater
precision.Toextendtheprecisionfurther,wemayuselongdoublewhichuses80bits.
Size Siz
Type Range
(inByte e(inB
float 4 s) 32 its) 3.4E−38to3.4E+ 38
double 8 64 1.7E−308to1.7E+ 308
long double 10 80 493
3.4E−4932to1.1E+
2
N ote:ThesizeandrangeofDataTypesvaryfromonemachinetoanother.Theabovespecifiedsize
andrangeofDataTypes areona16-bitMachine.
VoidDataType
Calsohasaspecialdatatypecalled ,which indicatesthatanydata typei.e.,nodatatype doesnot
voiddatatypeis0bytes.
describethedataitems.Thesizeofvoid
DerivedDataTypes
Thesearealsocalledsecondarydatatypesthatincludearrays,structures,unions and

pointers.
TypeDeclarationInstruction:
Avariablecanbeusedtostoreavalueofanydatatype.Thisinstructionisusedtodeclarethetypeofvaria
blesbeingusedintheprogram.
Thesyntaxfordeclaringavariableis

data_typevariable1,variable2…variablen;
variable1,variable2,...variablenarethenamesofvariables.Variablesareseparatedby
commas(,).Declarationstatementmustendwithasemicolon(;).E.g.:
intcount;intnum,total;
chargender;d
oubleratio;flo
atrs;

Severalsubtlevariationsofthetype declarationinstructionare
1) Whiledeclaringthetypeofvariable wecanalsoinitializevalue

inti=10,j=35;

Pr epar edbyIT &CSE Page40


floata=1.5,b=1.99+2.4∗1.44;
2) Theorderinwhichwedefinethevariablesissometimesimportantsometimesnot.

int i=10,j=35;issameasintj=35,i=10;
However,floata=1.5,b=a+3.1;isnot sameasfloatb=a+3.1,a=1.5;
(aswe aretryingtouseabeforedefiningit).
3) Thefollowingstatementswouldwork
inta,b,c,d;

a=b= c=10;
&thefollowingstatementswouldnotwork
inta= b= c= d= 10;
aswearetryingtouseb(toassigntoa) before definingit.

Declaringvariableasconstant
Thevalueof certainvariablesmightremainconstantduringtheexecutionof
aprogramwhichcanbeachievedwiththequalifierconstatthetimeofinitialization.
E.g.constintclass_size= 60;
Thekeywordconsttellsthecompilerthatthevalueoftheintvariableclass_sizemustnot
bemodifiedbytheprogram.

Declaringvariableas volatile
Anotherqualifiervolatilecanbeusedtotellexplicitlythecompilerthatavariable'svaluemaybechangedat
anytimebyexternalsources(fromoutsidetheprogram).
E.g. volatileintdate;
Thevalue ofdatemaybealteredbysomeexternalfactors.Whenwe declareavariable
asvolatile,thecompilerwillexaminethevalueofthevariableeachtimewhetheranyexternalalterationhasc
hangedthevalueandcanbemodifiedbyitsownprogram.
Ifthevaluemust notbemodifiedbytheprogram
whileitmaybealteredbysomeotherprocess,thenwemaydeclarethevalueasbothconstandvolatileas

volatileconstintlocation=100;
FormatCodes:
Formatcodesarecodingcharactersusedtorepresentthedatatypes.Theyareneededmustto
printtheoutputinaformattedmanner. Itisalsocalledcontrolstring, orformatspecifiersorformatstrings.
Code Description
%c SingleCharacter
%d DecimalInteger
%i Decimal,Hexadecimalor Octal Integer
%h ShortInteger
%e,%f,%g Floatingpointvalue
%ld Longinteger %lu Unsignedlongint
%o OctalInteger
%s Stringor sequence ofCharacters
%u Unsigned decimalinteger
%x Unsigned Hexadecimalinteger

BasicStructureofCProgram
Thebasicstructureofthe‘C’programconsistsof
DocumentationSectionLi
nkSection
DefinitionSection
GlobalDeclarationSectionma
in()functionsection
{
Declarationpart;E
xecutablepart;
}
SubprogramsectionFu
nction1
Function2
:
Functionn

Documentationsection
Thissectionconsistsofasetofcommentlinesgivingthenameoftheprogrammer,nameoftheprog
ramandotherdetails,whichtheprogrammerwouldliketouselater.It
startswith‘\*’andendswith‘*/’.
Linksection
Thissectionprovidesinstructionstothecompilertolinkfunctionsfromsystemlibrary.Itisas“#in
clude<stdio.h>”.
Definitionsection
Thissectiondefinesallthesymbolicconstants.
GlobalDeclarationSection:
Therearesomevariablesthatareusedinmorethanonefunction,suchvariablesarecalledglobalva
riables&aredeclaredintheglobaldeclarationsection.
main()functionSection:
EveryCprogrammusthaveone‘main’ function
section.Thissectioncontainstwopartsi.e.declarationpartandexecutablepart.Thedeclarationpa
rtdeclaresallthe
variablesusedintheexecutablepart.Thesetwopartsmustappearbetweenopeningandclosingbra
ces{}.
Declaration&ExecutionParts:
Theprogramexecutionbeginsatopeningbraceandendsattheclosingbrace.Allstatementsinthed
eclarationandexecutablepartendswithsemicolon(;).
SubProgramfunctions:
Thesubprogramfunctionscontainalltheuser-definedfunctions
thatarecalledinthemainfunction.
Userdefinedfunctionsaregenerallyplacedimmediatelyafterthemainfunction.
Thefollowingaretherulestow riteCPrograms:
1. AllCstatementsmustendwithsemicolon(;).
2. Ciscase-sensitive,i.e.,upperandlowercasecharacters
aredifferent.Generally,thestatementsaretypedinlowercase.
3. ACstatementcanbewritteninonelineoritcansplitintomultiplelines.
4. EveryCprogramisacollectionofoneormorefunctions.Theremustbeonlyfunctionwiththenamea
smainasprogramexecutionstartsandendswithmain()function.
5. Thefunction'sbodymustbeenclosedwithinbraces.Bracesmustalwaysmatchuponpairsi.e.,every
openingbrace{musthaveamatchingclosingbrace}toavoidconfusionsandeliminateerrors.
6. Tomakeprogramseasilyunderstandable,commentscanbeadded.Commentscannotbenested.Fo
rExample,/*Welcometo‘C’,/*Programming*/*/(thiscannotbeused).Acomment
cansplitintomorethanone line.

ExecutionofCPrograminTurboC:
ThefollowingarethestepstobefollowedinwritingandrunningaCprogram:
a) CreationofSourceProgram:
CreateaCprogramfileinvariousCcompilersthatareavailableunderMS-
DOS,TurboCEditoretc.
b) CompilationoftheProgram:
TurboCcompilerisuserfriendlyandprovidesintegratedprogramdevelopmentenvironment.Th
us,selectingkeycombinationcandocompilation.ThatmeanspressAlt+F9forcompilation.
c) ProgramExecution:
InTurboCenvironment,theRUNoptionwilldothecompilationandexecutionofaprogram.Press
Ctrl+F9forexecution.
d) ResultDisplay:
InTurboCenvironment,theoutputoftheexecutedprogramcanbeviewed.PressAlt+F5to
viewtheoutput.
Differenttypesoffiles inTurboC
 InClanguage,everysourcefileissavedwithanextensionof“.c”.
 Thecompilerautomaticallyconvertsthissourcefileintomachinecodeatcompiletimeandcre
atesanexecutablefile.
 Themachine code issavedwithanextension“.obj”.
 Theexecutablefileissavedwithanextensionof“.exe”.

ExecutionofCprograminUNIX/LINUXsystems
WeuseaneditorintheUNIXsystemtocreateaCsourceprogram.
ThefollowingcommandisusedtocompileCprogram"helloworld.c"
 CompilationCommand:gcchelloworld.c-ohelloworld
Thiscommandcompilesthecprogramandgeneratesanexecutablefile"helloworld"forrunning
theprogram.Inthecommandifwedon'tspecify"-ohelloworld"it
createsanexecutablefile"a.out"
ThefollowingcommandisusedtoexecuteCprogram"helloworld.c"
 ./a.out-toexecutetheprogramifexecutablefilenameisnotspecified.
 ./hellow orld-toexecutethe programifexecutablefile nameisspecified.

I /OFunctions

Allmost alltheprogramminglanguagesaredesignedtoprovideI/O activity.Input


referstotheprocessthroughwhichdataissuppliedtothesystem.Ontheotherhand,outputreferstotheprovi
sionwhichismadeavailablebythecomputertotheuser.

InCtheinput/outputfunctionstakestwoformstheyare:(1)Formatted(2)Unformatted

FormattedI/OFunctions

TheFormattedinput/outputfunctionsarestandardfunctionscapabletoreadandwritealltypesofdatavalue
s.Theyrequireconversionsymboltoidentifythedatatype.Sotheycanbeusedforbothreadingandwritingo
falltypes.Theformattedfunctionsalsoreturnvaluesaftertheexecution.TheformattedI/Ofunctionssuppo
rtedbyCareprintf()andscanf() .

printf()
Thisisanoutputstatement.Tooutputdataontoascreen,weusethestandardoutputlibraryfunction,repres
entedbytheword"printf"followedbytheopenandclosingparentheses().Itisusedtodisplaythevalueofav
ariableoramessageonthescreen.

Syntax:
printf("<message>");
printf("<controlstring>",argumentlistseparatedwithcommas);
Example:
printf("ThisisCstatement");printf("
Thenumberis%d",a);
printf("Thenumber%disequalto
%d",10,10);printf("Thenumber%disnotequalto
%d",x,y);

scanf()
Thisisaninputstatement.Datacanbestoredinthevariablesafteracceptingthevaluesfromtheuserthroug
hthekeyword,byusingastandardlibraryfunctionforinputoperation.Thisallowsaprogramtogetuserinp
utfromthekeyboard.Thismeansthattheprogramgetsinputvaluesforvariablesfromusers.
Syntax:
scanf("<formatcode>",listofaddressofvariablesseparatedbycommas);

Example:
scanf("%d",&a);
scanf("%d%c%f",&a,&b,&c);

1. Toprinta message"HelloWorld"onthescreen
/*Program to print a message "Hello World" */
#include<stdio.h>
#include<conio.h>main(
)
{
clrscr();printf("Hello
World");
}
Output:Hell
o World

2. ToDisplayMultipleStatements
/*Program to print Name and Address*/
#include<stdio.h>
#include<conio.h>main(
)
{
clrscr();
printf("Name:Sachin
Tendulkar");printf("\nQualification:
Degree");printf("\nAddress:
Mumbai")printf("\nWork: Cricket Player");
}
Output:
Name: Sachin
TendulkarQualification:
DegreeAddress: Mumbai
Work: Cricket Player

3. ToInitializeint,char,floatdatatypes
/*Program to initialize int, char, floatdata types*/
#include<stdio.h>
#include<conio.h>mai
n()
{
int
n=78;floatj=
3.0;char
x='y';clrscr
();
printf("Integer=%d\tFloat Value=%f\tCharacter=%c",n,j,x);
}
Output:
Integer=78 Float Value=3.0 Character=y

4. Toacceptthevaluesofint,float,chardatatypesanddisplaythem.
/*Program to accept valuesofint,char, float data
typesDisplay themin the order of reading*/
#include<stdio.h>
#include<conio.h>mai
n()
{
char
x;intnum;
floatj;cl
rscr();
/*Accept the values for data types from
user*/printf("Enter Character: ");
scanf("%c",&x);
printf("EnterInteger Value:
");scanf("%d",&num);
printf("Enter Float Value:
");scanf("%f",&j);
/*Display the accepted values*/
printf("Integer=%d\tFloat Value=%f\tCharacter=%c",num,j,x);
}
Output:
EnterCharacter:a (Enter)Enter
IntegerValue:20 (Enter)
Enter FloatValue: 100 (Enter)
Integer=20 Float Value=100.0 Character=a

UnformattedI/OFunctions

AsimplereadingofdatafromkeyboardandwritingtoI/Odevice,withoutanyformatiscalledunformattedI
/Ofunctions.Theunformattedinput/outputfunctionsonlyworkwiththecharacterdatatype.Theydonotre
quireconversionsymbolforidentificationofdatatypes.Thereisnoneedtoconvertthedata.Theunformatte
dfunctionsalsoreturnvalues,andreturnvalueisalwaysthesame.
TheunformattedI/Ofunctionsareclassifiedinto(1)CharacterI/Oand(2)StringI/O
CharacterI/O
Thesereadandprintsinglecharacter.
(1) getchar()
Itreturnsasinglecharacteracceptedthroughthekeyboard,aftertheconfirmationkeyispressedandca
nbeassignedto
thevariable.Thefunctiondoesnotrequireanyparameterthoughapairofemptyparenthesesmustfollo
wthewordgetchar.
Syntax:character_variable = getchar();

Example:
charc;c=getchar();/*readsasinglecharacter*/
(2) getch()&getche()
Thesefunctionsreadanyalphanumericcharactersfromthestandardinputdevice.getch()isastandardl
ibraryfunctionusedforsinglecharacterinput,butitdoesnotwaitforenterkeyandneitherdoesit
displaythecharacteronthescreen.
Syntax:character_variable = getch();

getche()isastandardlibraryfunctionsusedforsinglecharacterinputsameasgetch()function.Ital
sodoesnotwaitforenterkeybutechoesonthescreen.Itcanbeusedforgettingtheresultdirectlyont
hescreen.
Syntax:character_variable = getche();

Example:
charc;c=getche();/*Displaysthecharacterenteredonscreen*/c=getch();/*
doesnotdisplaythecharacter*/
(3) putchar(
)
Ittransmitsasinglecharactertoastandardoutputdevice.Thecharacterbeingtransmittedwillnormall
yberepresentedasacharactertypevariable.Itmustbeexpressedasaparametertothefunction,enclose
dinparentheses,followedbythewordputchar.
Syntax:putchar(character_variable/expr);

Example:
charc;c=getchar();putchar(c);/*printstheacceptedcharacter*/
(4) putch()
Thisfunctionprintsanyalphanumericcharactertakenbythestandardinputdevice.
Syntax:putch(character_variable/expr);

Example:Programtoacceptcharactersanddisplaythem.
/*Program to accept characters and display*/
#include<stdio.h>
#include<conio.h>mai
n()
{
char
x,y,z;clrscr();
printf("Enter 1st character:
");x=getchar();
printf("Enter 2nd character:
");y= getche();
printf("\nEnter 3rd character:
");z=getch();
printf("\nFirst character is
");putchar(x);
printf("\nSecond character is
");putch(y);
printf("\nThird character is
");putchar(z);
}
Output:
Enter 1st
character:kEnter 2nd
character:lEnter 3rd
character:First
character iskSecond
character islThird
character is;

StringI/O
Inordertoreadandwritestringofcharactersthefunctionsgets()andputs()areused.gets()functionreads
thestringandputs()functiontakesthestringasargumentandwritesonthescreen.
UNIT- 2

WEEK–3
1 OperatorsinC,theirPrecedenceandAssociativity,

2 Ar ithmeticExpressions/Instr uctions
3 Typecasting,Math.hfunctions

4 SampleCPr ogr ams


------------------
OperatorsinC
Anoperatorisasymbolthattellsthecomputertoperformcertainmathematicalorlogicalmanipulations(c
alculations).Cisextremelyrichinbuilt-
inoperators.Operatorsareusedinprogramtomanipulatedataandvariables.Someoperatorsrequiretwoo
perands,whileothersactupononlyoneoperand.Coperatorsareclassifiedasfollows:
1) ArithmeticOperators
2) RelationalOperators
3) LogicalOperators
4) AssignmentOperator
5) Increment&DecrementOperator
6) ConditionalOperator
7) BitwiseOperators
8) SpecialOperators

ArithmeticO perators:Cprovidesallbasicarithmeticoperatorsaslistedbelow:
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% ModuloDivision(remainderafterdivision)

Integerdivisiontruncatesanyfractionalpart.Modulodivisionproducestheremainderofintegerdivision
.
E.g.sum=a+b;product=a*b;difference=a-b;quotient=a/b;remainder=a
%b;Intheexample,a&barevariablesadare knownasoperands.

Note:Themodulodivisionoperator(%)can'tbeusedonfloatanddoubledatatypes.
Pr ogr ammingwithC-Lab

RelationalO perators:RelationalOperatorsaresymbolsthatareusedtotesttherelationshipbetween2
variablesor between
variableandaconstant.Weoftencomparetwoquantities&dependinguponthisrelationtakecertaindecisi
ons.
Operator Meaning
> Greaterthan
>= Greaterthanorequalto
< Lessthan
<= Lessthanorequalto
== Equalto
!= Notequalto
Asimplerelationalexpressioncontainsonlyonerelationaloperatorandtakesthefollowingform:
ae1relationaloperatorae2
Hereae1 andae2 arearithmetic expressions,whichmaybesimpleconstants,variables or
combinationofthem.Thevalueofarelationalexpressioniseitheroneorzero.Itisoneifthespecifiedrelat
ionistrueandzeroif therelationisfalse.
E.g.10< 20istrue,20<10isfalse.
Theseexpressionsareusedindecisionstatementssuchasifandwhiletodecidethecourseofactionofarun
ningprogram.

LogicalO perators:Chasthefollowingthreelogicaloperators:
Operator Meaning
&& LogicalAND
|| LogicalOR
! LogicalNOT
Thelogicaloperator&&and||areusedwhenwewanttotestmorethanonecondition
&makedecisions.
E.g. a>b&&x==10
Anexpressionofthiskindwillcombinetwoormorerelationalexpressionsistermedaslogicalexp
ressionorcompoundrelationalexpression.Thelogicalexpressiongivenbelowistrue if
a>bistrueandx==10istrue.Ifeitherorbothof themarefalse,theexpressionisfalse.
TRUTHTABLE
op-1 op-2 op-1 &&op-2 op-1 || op-2
1 1 1 1
1 0 0 1
0 1 0 1
0 0 0 0

Pr epar edbyIT &CSE Page50


LogicalNOTisusedtoreversethetruth valueof itsoperand.(i.e.NOTF-> T)
Anexpressioncontainingalogicaloperatoristermedasalogicalexpression.Alogicalexpressionalsoyie
ldsavalue ofoneorzero.

AssignmentO perator:(=)
Theseare usedtoassigntheresultofanexpressiontoavariable.Chasasetof
shorthandassignmentoperatorsoftheform:
vop=exp;
wherevisavariable,expisanexpressionandopisaCarithmeticoperator.The
operatorop=isknownasshorthandassignmentoperator.

Theaboveexpression canbe equivalenttov=vop(exp);


E.g.x+=y+1;->x= x+ (y+1);
Statementwithsimpl Statementwithshorthandoperator
eassignmentoperat
aor = a+1 a + 1
a = a-1 a =
- 1
a = a*(n+1) a =
* (n+1)
a = a/(n+1) a =
/ (n+1)
a = a%b a = b
%
=
Theuseofshorthandassignmentoperatorshas3advantages:
1. What appears on theleft-hand sideneednot be repeatedand therefore
itbecomeseasiertowrite.
2. Thestatementismoreconciseandeasiertoread.
3. Thestatementismoreefficient.

Increment&DecrementO perators:
Chastwoveryusefuloperatorsnotgenerallyfoundinotherlanguages.Theseareincrementanddecreme
ntoperators:++and--.
Theoperator++adds1totheoperand,while--subtracts1.
Pre/PostIncrement/DecrementOperators
PREmeansdotheoperationfirstfollowedbyanyassignmentoperation.POSTmeansdotheoperationaft
eranyassignmentoperation.
++m;orm++;|--m;orm--;
++m;isequivalenttom=m+1;(orm+=1;)/--m;isequivalenttom=m-1;(orm-=1;)
Whilem++and+
+mmeanthesamewhentheyformstatementsindependently,theybehavedifferentlywhentheyareusedi
nexpressionsontheright-handsideofanassignmentstatement.
E.g.(i)m= 5;
y=++m;Thisstatement resultsyandm=6
Sincetheprefix operatorfirstadds 1to theoperandandthentheresultis
assignedtothevariableonleft.
(ii) m= 5;
y=m++;Thisstatementresultsy=5andm =6
Sincethepostfixoperatorfirstassignsthevaluetothevariableonleftthenincrementstheoperand.
Weuseincrementanddecrementstatementsinforandwhileloopsextensively.
ConditionalO perator:
Aternaryoperatorpair"?:"isavailableinCtoconstructconditionalexpressionsoftheform:
exp1?exp2∶exp3;
whereexp1,exp2andexp3areexpressions.
Thereoperator?:worksasfollows:exp1isevaluatedfirst.Ifitistrue,thenexp2isevaluatedandbecomesth
evalueoftheexpression.Ifexp1isfalse,exp3isevaluatedanditsvaluebecomesthevalueoftheexpression.
E.g. a=10;
b=15;
x=(a>b)?a:b;Inthis,the xwillbeassignedwiththe valueofb.

BitwiseO perators:
InC,operationsonbitsatindividuallevelscanbecarriedoutusingBitwiseoperators.Theseareusedforma
nipulationofdataatbitlevel.
Theseoperatorsareusedfortestingthebits,orshiftingthemrightorleft.Thesemaynotbeappliedtofloator
double.
Operator Meaning
& bitwiseAND
| bitwiseOR
^ bitwiseexclusiveOR
<< shiftleft
>> shiftright
~ One'scomplement

Thebitw iseAND doesthelogicalANDofthebitsineachpositionofanumberinitsbinaryform.


001 1 1100&
00001 1 01
----------------------------
000011 00:Result
Thebitw iseORdoesthelogicalORofthebitsineachpositionofanumberinitsbinaryform.
001 1 1 100|
00001 1 01
----------------------------
001 1 1101 :Result

ThebitwiseexclusiveORperformsalogicalEX-
ORfunctionorinsimpletermaddsthetwobitsdiscardingthecarry.Thusresultiszeroonlywhenwehave2
zeroesor2onestoperformon.
001 1 1 100^
00001 1 01
----------------------------
0011 0001 :Result
Theone'scomplement(~)orthebitwisecomplementgetsusthecomplementofagivennumber.Thuswege
tthebitsinverted,foreverybit1theresultisbit0andconverselyforeverybit 0wehave abit1.
Bit One'sComplement
0 1
1 0
~001 11 1 00-->11 00001 1
Twoshiftoperatorsshiftthebitsinanintegervariablebyaspecifiednumberofpositions.The<<operator
shiftsbitstotheleft,andthe>>operatorshiftsbitstotheright.
The syntaxforthese binaryoperatorsisx<<nandx>>n.
Eachoperatorshiftsthebitsinxbynpositionsinthespecifieddirection.
 Forarightshift,zerosareplacedinthe nhigh-orderbitsofthevariable;
 Foraleftshift ,zerosareplacedin thenlow-

orderbitsofthevariable.Hereareafewexamples:
Binary00001100(decimal12)right-shifted by2evaluatesto binary00000011(decimal3).
Binary00001100(decimal12)left-shifted by3evaluatestobinary01100000(decimal96).
Binary00001100(decimal12)right-shifted by3evaluatesto binary00000001(decimal1).
Binary00110000(decimal48)left-shifted by3evaluatestobinary10000000(decimal128).

SpecialO perators:
Csupportssomeoperatorsofinterestsuchascommaoperator,sizeofoperator,pointeroperators(&and*)an
dmemberselectionoperators(.and->).
Thecommaoperatorcanbeusedtolinktherelatedexpressionstogether.Acomma-
linked:listofexpressionsareevaluatedleft torightandthevalueofright-
mostexpisthevalueofcombinedexpression.
E.g.value=(x=10,y=5,x+y);
First10isassignedtoxthen5isassignedtoy&finallyx+yi.e.which15isassignedtovalue.
Sincecommaoperatorhaslowestprecedenceofalloperators,theparenthesesarenecessary.
Inforloops:for(n=1,m=10;n<=m;n++,m+
+)Inwhileloops:while(c=getchar(),c!
='10')Exchangingvalues:t=x,x=y,y=t;
Thesizeofisacompiletimeoperatorandwhenusedwithanoperand,itreturnsthenumberofbytestheoper
andoccupies.Theoperandmaybeavariable,aconstantoradatatypequalifier.
E.g. m=sizeof(sum);
n=sizeof(longint);k=si
zeof(235L);
Thisoperatorisnormallyusedtodeterminethelengthsofarraysandstructureswhentheirsizesarenotkno
wntotheprogrammer.Itisalsousedtoallocatememoryspacedynamicallytovariablesduringexecutiono
faprogram.

PrecedenceofArithmeticoperators
Anarithmeticexpressionwithoutparentheseswillbeevaluatedfromlefttorightusingtherulesof
precedenceof operators.Therearetwodistinctprioritylevelsof arithmeticoperatorsinC:
HighPriority *,/,%
LowPriority +,-
Thebasicevaluationprocedureincludestwoleft-to-
rightpassesthroughtheexpression.Duringthefirstpass,thehighpriorityoperators(ifany)areappliedast
heyareencountered.Duringthesecondpass,thelowpriorityoperators(ifany)areappliedastheyareenco
untered.
E.g.Considera=9,b=12andc=3x=a-
b/3+c*2-1;
1>x=9-12/3+ 3*2-1
2>x=9-4+3*2-1
3>x= 9-4+ 6-1
4>x= 5+ 6-1
5>x= 11 -1 6>x= 10
y=a-b/(3+c)*(2-1);
1>y= 9-12/6*(2-1)
2>y= 9-12/6*1
3>y= 9-2*1
4>y= 9-2 5>y= 7
z=a-(b/(3+c)*2)-1;
1>z= 9-(12/(3+3) *2) -1
2>z= 9-(12/6*2)-1
3>z= 9-(2* 2)-1
4>z=9-4-1
5>z= 5-1 6> z= 4

OperatorPrecedenceandAssociativity
EachoperatorinChasaprecedenceassociatedwithit.Thisprecedenceisusedtodeterminehowanexpre
ssioninvolvingmorethanoneoperatorisevaluated.Therearedistinctlevelsofprecedenceandanoperat
ormaybelongtooneofthelevels.Theoperatorsat thehighestlevelof
precedenceareevaluatedfirst.Theoperatorsofthesameprecedenceareevaluatedeitherfromlefttorigh
torfromrighttoleft,dependingonthelevel.Thisisknownasassociativitypropertyofanoperator.

a++ a-- left toright

!a~a (type)a ++a --a righttoleft!

a*b a/b a%b left toright

a+b a-b left toright

a>>b a<<b left toright

a>ba>=b a<b a<=b left toright

a==b a!=b left toright

a&b left toright

a^b left toright

a|b left toright

&& left toright


|| left toright

a?b:c righttoleft
=, +=, -=, *=, /=
righttoleft
%=,<<=,>>=, &=
|=,^=

, left toright
ARITHMETICEXPRESSIONS
Anarithmeticexpressionisacombinationofvariables,constantsandoperatorsarrangedasperthesyntax
ofthelanguage.Ccanhandleanycomplexmathematicalexpressions.
ArithmeticInstruction
ACarithmeticinstructionconsistsofavariablenameonthe lefthandside
of=andvariablenamesandconstantsontheright handside
of=.Thevariablesandconstantsappearingontherighthandside
of=areconnectedbyarithmeticoperatorslike+,-,*,
/,and%.

E.g. inta;a=32
variable−name=expression[or]value;
00;
floatkot,deta,alpha=9.2,beta=3.1256,gamma=100.0;kot=0.0056;
deta=alpha*beta/gamma+3.2*2/5;
Here2,5and3200areintegerconstantsand3.2and0.0056arerealconstantskot,deta,alpha,betaa
ndgammaarerealvariables.
Thevariablesandconstantstogetherarecalledoperandsthatareoperateduponbythearithmeticoperator
sandtheresultisassignedusingtheassignmentoperator,tothevariableontheleft-handside.
Carithmeticinstructionsareof3types:
(1) Integermode:Thisisanarithmeticinstructioninwhichalloperandsareeitherintegervariablesori
ntegerconstants.
E.g.inti,king,issac,noteit;i=
i+1;
king=issac*234+noteit-7689;
(2) Realmode:Thisisanarithmeticinstructioninwhichalloperandsareeitherrealconstantsorrealvar
iables.
E.g.float
q,a,si,princ,anoy,roi;q=a+23.12
3/4.5*0.344;
si=princ*anoy*roi/100.0;
(3) Mixedmode:Thisisanarithmeticinstructioninwhichsomeoftheoperandsareintegersandsome
of theoperandsarereal.
E.g.float
si,princ,anoy,roi,avg;inta,b,c,num
;
q=a+23.123/4.5*0.344;
si=princ*anoy*roi/100.0;avg=(a
+b+c+num)/4;
Theexecutionof
anarithmeticinstruction:Firstly,therighthandsideisevaluatedusingconstantsandthenumericalvalues
storedinthevariablenames.Thisvalueisthenassignedtothevariableontheleft-handside.
GuidelinesforArithmetic Instructions
a) Callowsonlyonevariableonlefthandsideof=.i.e.,x=k+
l;islegal whereask+l=x;isillegal.
b) Anarithmeticinstructionisoftenusedforstoringcharacterconstantsincharactervariables.
E.g. chara,b,d;
a= 'F';
b= 'G';
d= '+';
WhenwedothistheASCIIvaluesofthecharactersarestoredinthevariables.ASCIIvaluesareuse
dtorepresentanycharacterinmemory.
c) Arithmeticoperationscanbeperformedonints,floatsandchars.charx,y;
intz;x='a';
y='b';z=x+y;
d) Nooperatorisassumedtobepresent.Itmustbewrittenexplicitly.
E.g a=c.d.b(xy) usualarithmeticstatement
. b=c*d*b*(x*y); cstatement
e) Unlike other high level languages, there is no operator for
performingexponentiationoperation.
E.g. a=3**2;
b=3^2;statementsarevalid.

EvaluationofExpressions
Expressionsareevaluatedusinganassignmentstatementoftheform

AlgebraicExpression
variable= expression; Cexpression
a xb-c a *b-c
(m+n)(x+y) (m+n)*(x+y)
ab
c a*b/c

3x2+ 2x+ 1 3*x*x+ 2*x+1


x
x/y+c
+c
y
VariableisanyvalidCvariablename.Whenthestatementisencountered,theexpressionisevaluatedfirst
andtheresultthenreplacesthepreviousvalue ofthevariableontheleft-
handside.Allvariablesusedintheexpressionmustbeassignedvaluesbeforeevaluationisattempted.
E.g. x=a*b-c;
y=b/c*a;
z=a-b/c+d;
Theblankspacearoundanoperatorisoptionalandaddsonlytoimprovereadability.Whenthesestatement
sare usedinaprogram,thevariablesa,b,canddmust be definedbeforetheyareusedintheexpressions.
Rules forevaluationofexpression
1. Parenthesizedsubexpressionfromlefttorightisevaluated.
2. Ifparenthesesarenested,theevaluationbeginswiththeinnermostsub-expression.
3. The precedenceruleis applied in determiningtheorderof
applicationofoperatorsinevaluatingsub-expressions.
4. Theassociativityruleisappliedwhen2ormoreoperatorsof
thesameprecedencelevelappearinasub-expression.
5. Arithmetic expressions areevaluated from lefttorightusingtherules ofprecedence.
6. Whenparenthesesareused,theexpressionswithinparenthesesassumehighestpriority.

T ypeCasting
TypecastingconceptinClanguageisusedtomodifyavariablefromonedatetypetoanotherdatatype.New
datatypeshouldbementionedbeforethevariablenameorvalueinbracketswhichtobetypecast.
Ctypecastingexampleprogram:
 InthebelowCprogram,7/5alonewillproduceintegervalueas1.
 So,typecastisdonebeforedivisiontoretainfloatvalue(1.4).
#include
<stdio.h>intmain()
{
float x;
x= (float)
7/5;printf("%f",x)
;
}
Output: 1.400000

Note:
 Itisbestpracticetoconvertlowerdatatypetohigherdatatypetoavoiddataloss.
 Data willbetruncatedwhenhigher datatypeis
convertedtolower.Forexample,iffloatisconvertedtoint,datawhichispresent
afterdecimalpointwillbelost.

UsualArithmeticConversion
Theusualarithmeticconversionsareimplicitlyperformedtocasttheirvaluesinacommontype,Cusesther
ulethat,inallexpressionsexceptassignments,anyimplicittypeconversionsmadefromalowersizetypetoa
highersizetypeasshownbelow:

“m ath.h”functio ns
Mathematics is relatively straightforward library to use again. You must
#include<math.h>andmustremembertolinkinthemathlibraryatcompilation:
ccmathprog.c-omathprog-lm
MathFunctions

S. Functio Description Example


no n floorof5.100000is5.000000
Thisfunctionreturnsthenearest
floorof5.900000is5.000000
1 floor() integerwhichislessthan
floorof-5.400000is-6.000000
orequaltotheargumentpassedtothisfunc
floorof-6.900000is-7.000000
tion.
Thisfunctionreturnsthenearest
integervalueofthefloat/double/long
doubleargument
passedtothisfunction.If decimal roundof5.400000is5.000000
2 round(
valueisfrom“.1 to roundof5.600000is6.000000
)
.5″,itreturnsintegervaluelessthan the
argument. Ifdecimal valueisfrom“.6to
.
9″,itreturnstheintegervaluegreatertha
Thisfunctionreturnsnearest ceilof5.400000is6.000000
3 ceil() integervaluewhichisgreaterthan ceilof5.600000is6.000000
orequal Ceilof8.33=9
to theargument passedtothisfunction.
Thisfunction
4 sin() Thevalueofsin(0.314000):
isusedtocalculatesinevalue.
5 cos() Thisfunction isusedtocalculatecosine. 0.308866
Thevalueofcos(0.314000):
Thisfunction 0.951106
6 cosh()
isusedtocalculatehyperboliccosi Thevalueoftan(0.314000):
ne.
Thisfunction 0.324744
7 exp() Thevalueofsinh(0.250000):
isusedtocalculatetheexponential“e”
tothex
th
power. 0.252612
Thisfunction Thevalueofcosh(0.250000):
8 tan()
isusedtocalculatetangent. 1.031413
Thisfunction Thevalueoftanh(0.250000):
9 tanh()
isusedtocalculatehyperbolictan 0.244919
gent.
Thisfunction Thevalueoflog(6.250000):
10 sinh() 1.832582
isusedtocalculatehyperbolicsin
e. Thevalueoflog10(6.250000):
Thisfunction 0.795880
11 log()
isusedtocalculatesnaturallogarit Thevalueofexp(6.250000):
hm.
Thisfunction 518.012817
12 log10(
isusedtocalculatesbase10logarithm.
)
Thisfunction sqrtof16=4.000000
13 sqrt()
isusedtofindsquarerootoftheargumentp sqrtof2=1.414214
assedtothisfunction.
Thisisusedtofindthepowerofthegive 2power4=16.000000
14 pow()
nnumber. 5power3=125.000000
truncatedvalueof16.99=1
Thisfunction
6.000000
15 trunc() truncatesthedecimalvaluefromfloatingp
truncatedvalueof20.1=2
oint valueandreturnsintegervalue.
0.000000

MathConstants
Themath.hlibrarydefinesmany(oftenneglected)constants.Itisalwaysadvisabletousethesedefinitions
:
 HUGE-Themaximumvalue ofasingle-precisionfloating-pointnumber.
 M_E-Thebaseofnaturallogarithms (e).
 M_LOG2E-Thebase-2logarithmofe.
 M_LOG10E-Thebase-10logarithmofe.
 M_LN2-Thenaturallogarithmof2.
 M_LN10-Thenaturallogarithmof10.
 M_PI- π.
 M_PI_2- π/2.
 M_PI_4- π/4.
 M_1_PI- 1/π.
 M_2_PI- 2/π.

 M_2_SQRTPI-2/√rr.
 M_SQRT2-Thepositive squarerootof2.
 M_SQRT1_2-Thepositivesquarerootof1/2.
 MAXFLOAT-Themaximumvalueofanon-infinitesingle-precision
floatingpointnumber.
 HUGE_VAL- positiveinfinity.

Pr epar edbyIT &CSE Page60


SampleCPrograms
Inputtwonumbersandcomputeallarithmeticoperations
/*Program to accept 2 numbers and compute all arithmetic operations*/
#include<stdio.h>
#include<conio.h>main
()
{
intnum1,num2;clr
scr();
/*Accept two numbers from
user*/printf("Enter first
number:
");scanf("%d",&num1);printf("Ent
er second number:
");scanf("%d",&num2);
/*Displayvalues for arithmetic operators*/printf("Sum
of2 numbers: %d",num1+num2);printf("\nDifference
of2numbers: %d", num1-num2);printf("\nProduct of2
numbers: %d", num1*num2);
printf("\nQuotient for %d/%d: %d",
num1,num2,num1/num2);printf("\nRemainder for %d/%d: %d",
num1,num2,num1%num2);
}
Output:
Enter first number: 52
(Enter)Entersecond number: 12
(Enter)Sumof2 numbers: 64
Difference of2numbers:40
Product of2 numbers:
624Quotient for 52/12:
4Remainder for 52/12:4

Inputradius,computearea,diameter,&circumference ofthecircleanddisplaythem.
/*Program to accept radius& calculatearea, diameter
andcircumference of circle*/
#include<stdio.h>
#include<conio.h>main
()
{
/*Declare the
variables*/intradius,diam
eter;float
area,circumference;
const float PI= 3.14; /*set variable PIto
constant*/clrscr();
/*Accept the value
ofradius*/printf("Enter circle
radius: ");
scanf("%d",&radius);
/*Compute the area, diameter and
circumference*/diameter = 2*radius;
area =
PI*radius*radius;circumference
=2*PI*radius;
/*Display the results*/
printf("Area ofcircle=
%.2f",area);printf("\nDiameter ofcircle=
%d",diameter);
printf("\nCircumference of circle =
%.2f",circumference);getch();
}
Output:
Entercircle radius: 5
(Enter)Area ofcircle=
78.50Diameter
ofcircle=10Circumference of
circle = 31.40

Swappingthevaluesoftw ovariablesusingthirdvariable
/*Program to accept two numbers &swapthe values*/
#include<stdio.h>
#include<conio.h>mai
n()
{
/*Declare the
variables*/int
num1,num2,temp;clrscr();
printf("Enter first number:
");scanf("%d",&num1);printf("Ent
er second number: ");
scanf("%d",&num2);
printf("Numbers before swapping: %d %d",num1,num2);
/*swapping the values of
variables*/temp = num1;
num1 =
num2;num2 =
temp;
printf("Numbers after swapping: %d
%d",num1,num2);getch();
}
Output:
Enter first number:
6Entersecond number: 5
Numbers before swapping: 65
Numbers after swapping: 56
Programforswapping thevaluesoftwovariableswithoutusingthirdvariable
/*Program to accept two numbers &swapthe values*/
#include<stdio.h>
#include<conio.h>mai
n()
{
/*Declare the
variables*/intnum1,num2;
clrscr();
printf("Enter first number:
");scanf("%d",&num1);printf("Ent
er second number:
");scanf("%d",&num2);
printf("Numbers before swapping: %d %d",num1,num2);
/*swapping the values of
variables*/num1 = num1 + num2;
num2 = num1 –
num2;num1 = num1 –
num2;
printf("Numbers after swapping: %d
%d",num1,num2);getch();
}
Output:
Enter first number:
6Entersecond number: 5
Numbers before swapping: 65
Numbers after swapping: 56

Programtocalculatetotalmarksandpercentageofastudentfor5subjectswheremarksofeach
subjectshouldbegreaterthanminimumpassmarks(Ex:35).
/*Program to accept marks and obtaintotal and percentageof marks*/
#include<stdio.h>
#include<conio.h>mai
n()
{
int
sub1,sub2,sub3,sub4,sub5,sum;long
int studno;
float
total=500,percentage;clrscr();
printf("Enter Student Number:
");scanf("%ld",&studno);printf("E
nter SUBJECT1 marks:
");scanf("%d",&sub1);
printf("Enter SUBJECT2 marks:
");scanf("%d",&sub2);
printf("Enter SUBJECT3 marks:
");scanf("%d",&sub3);
printf("Enter SUBJECT4 marks:
");scanf("%d",&sub4);
printf("Enter SUBJECT5 marks:
");scanf("%d",&sub5);sum=sub1+sub2+sub3+sub4+s
ub5;percentage=(sum/total)*100;printf("=======
======RESULT=============\n");
printf("STUDENT NUMBER:
%ld",studno);printf("\nTOTAL MARKS OBTAINED FOR
500: %d",sum);
printf("\nPERCENTAGE:
%.2f",percentage);getch();
}
Output:
Enter Student Number:
1220610113EnterSUBJECT1 marks: 90
EnterSUBJECT2 marks:
91EnterSUBJECT3 marks:
95EnterSUBJECT4 marks:
93EnterSUBJECT5 marks:
89
=============RESULT=============STUDEN
T NUMBER: 1220610113
TOTAL MARKS OBTAINED FOR 500: 458
PERCENTAGE: 91.60

Toimplementtheconceptofevaluating theexpressions
/*Program to evaluate the expressions*/
#include<stdio.h>mai
n()
{
int
a=9,b=13,c=3;floa
tx,y,z;
x= a-b/3.0+c*2-1;
y= a-(float)b/(3+c)*(2-1);
z= a-((float)b/(3+c)*2)-1;
printf("x = %f\t\ty = %f\t\tz =
%f",x,y,z);getch();
}
Output:
x= 9.666667 y= 6.833333 z= 3.666667
WEEK–4
1 ControlStatements(Conditional):IfanditsVar iants

2 Switch(Br eak)
3 SampleCPr ogr ams
------------------
ControlStatements(Conditional–DecisionMaking)

Wehaveanumberofsituationswherewemayhavetochangetheorderofexecutionofstatementsbasedonce
rtainconditions,orrepeatagroupofstatementsuntilcertainspecifiedconditionsaremet.Thisinvolvesakin
dofdecisionmakingtoseewhetheraparticularconditionhasoccurredornotandthendirect
thecomputertoexecutecertainstatementsaccordingly.
Clanguagepossessessuchdecisionmakingcapabilitiesandsupportsthefollowingstatementsknownasc
ontrolordecisionmakingstatements.
1. ifstatement
2. switchstatement
3. conditionaloperatorstatement
4. gotostatement

Decisionmakingwith‘if’statement
Theifstatementisapowerfuldecisionmakingstatementandisused
tocontroltheflowofexecutionofstatements.Itisbasicallyatwo-
waydecisionstatementandisusedinconjunctionwithanexpression.Ittakesthefollowingform:
if(testexpression)
Itallowsthecomputertoevaluatetheexpressionfirstandthendependingonwhether
thevalueofexpression(orcondition)istrue(1)orfalse(0),ittransfersthecontroltoaparticularstatement.T
hispointofprogramhastwopathstofollow,oneforthetrueconditionandtheotherforthefalsecondition.

Entry

test
expression? False

TrueTwo-wayBranching
Examplesofdecisionmaking,usingifstatementare
1. if(bankbalanceiszero)borrowmoney
2. if(ageismorethan60) personretires

Theifstatementmaybeimplementedindifferentformsdependingonthecomplexityofconditionstobete
sted.
1. Simpleifstatement
2. if…elsestatement
3. Nestedif…elsestatement
4. elseifladder
Simple‘if’statement
Thegeneralformofa‘simpleif’statementis
Syntax:
if(test_expression)
{
statement_block;
}
statement_x;

‘statement_block’maybe asinglestatementoragroupof statements.


Ifthetestexpressionistruethe‘statement_block’willbeexecuted,otherwisethe‘statement_block’willb
eskippedandtheexecutionwilljumpto‘statement_x’.

Flow chartforSimpleIf

Example:Tocheckw hetherstudentispassedorfailed.
/*Programtocheckwhetherstudentispassed or failed*/
#include<stdio.h>
#include<conio.h>mai
n()
{
intmarks;clrscr();
printf("Enter
studentmarks:");scanf("%d",&mar
ks);if(marks>50)
printf("StudentPassed");if(
marks<50)
printf("StudentFailed");get
ch();
}

Output:
(1)Enterstudentmarks:55Stud
entPassed
(2)Enter
studentmarks:40StudentFa
iled

If-ElseStatement
Theif-elsestatementisanextensionof the‘simpleif’statement.Thegeneralformis
Syntax:
if(test_expression)
{
true-block-statements;
}
else
{
false-block-statements;
}
statement_x;

Ifthetest_expressionistrue,then thetrue-block-
statement(s),immediatelyfollowingtheifstatementareexecuted;otherwisethefalse-block-
statement(s)areexecuted.Ineithercase,eithertrue-block-statementsorfalse-block-
statementswillbeexecuted,notboth.

Flow chartforIfElse
Example:Programtocheckwhethergivennumberisevenorodd
/*Programtocheckwhethergivennumber is evenor odd*/
#include<stdio.h>
#include<conio.h>mai
n()
{
intnum;clrscr
();
printf("Enter
number:");scanf("%d",&nu
m);if(num%2==0)
printf("%d isevennumber",num);
else
printf("%d isodd number",num);
getch();
}

Output:
(1)Enternumber:5353i
sodd number
(2)Enter
studentmarks:4242isevenn
umber

NestedIf…ElseStatement
Whenaseriesofdecisionsareinvolved,wemayhavetousemorethanoneif…
elsestatementinnestedformasfollows:
Syntax:
if(test_condition1)
{
if(test_condition2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
Ifthetest_condition1isfalse,thestatement-
3willbeexecuted;otherwiseitcontinuestoperformthesecondtest.Ifthetest_condition2istrue,thestate
ment-1willbeexecutedotherwisestatement-
2willbeevaluatedandthenthecontrolistransferredtothestatement-x;
Flow chartforNestedIf…Else

Example:Programtofindthelargestofthreenumbers
/*Programtofind thelargestof threenumbers*/
#include<stdio.h>
#include<conio.h>mai
n()
{
inta,b,c;
clrscr();
printf("Enter the
threevalues:");scanf("%d %d
%d",&a,&b,&c);if(a>b&&a>c)
printf("%d islargest",a);
else
if(b>a&&b>c)printf("%d
islargest",b);
else
printf("%d islargest",c);
getch();
}

Output:
Enternumber:567
7 islargest

ElseIfLadder
Thereisanotherwayofputtingif’stogetherwhenmultipathdecisionsareinvolved.Amultipathdecisioni
sachainofif’sinwhichthestatementassociatedwitheachelseisanif.Ittakesthefollowinggeneralform:

Syntax:
if(condition1)
statement-
1;else if(condition-
2)
statement-
2;else if(condition-
3)
statement-3;
...
...
...
else if(condition-
n)statement-n;
else
default-

Thisconstructisknownaselseifladder.The
conditions are
evaluatedfromthetopdownwards.Assoon
asatrueconditionisfound,thestatementass
ociatedwithitisexecutedandthecontrolist
ransferredtostatement-
x.Whenallthenconditionsbecomefalse,th
enthefinalelsecontainingthedefault-
statementwillbeexecuted.

The
logicofexecutionfor‘elseifladderstateme
nts’isshownintheflowchartbelow.

Pr epar edbyIT &CSE Page70


Example:Programtoillustrateconceptofelse-ifladdertoselectcolor
/*Programtoselectcolor*/
#include<stdio.h>
#include<conio.h>mai
n()
{
intn;clrscr()
;
printf("Enter anynumberbetween 1 &4to
selectcolor:\n");scanf("%d",&n);
if(n==1)
{
printf("Youselected Redcolor");
}
else if(n==2)
{
printf("Youselected Greencolor");
}
else if(n==3)
{
printf("Youselected yellowcolor");
}
else if(n==4)
{
printf("Youselected Bluecolor");
}
else
{
printf("Nocolor selected");
}
getch();
}
Output:
(1) Enteranyvalue between 1
&4toselectcolor:4Youselected Blue Color
(2) Enteranyvalue between1
&4toselectcolor:1Youselected Red Color
(3) Enteranyvalue between1 &4toselectcolor:5Nocolor
selected
SWI T CH-CASEST AT EM ENT
Whenoneofmanyalternativesistobeselectedwecandesignaprogramusing'if'statement,tocontrolthese
lection.However,thecomplexityofsuchprogramsinCnumberofalternativesincreases.Theprogrambe
comesdifficulttoreadandfollow.

The
switchtestorchecksthevaluesofgivenvariable(orexpression)againstalistofcasevaluesandwhenamat
chisfoundablockofstatementsassociatedwiththatcaseisexecuted.
Theswitchmakesoneselectionwhenthereareseveralchoicestobemade.

Thegeneralformofswitchstatementis
Syntax:
switch(expression)
{
case value-1: block-1;
break;ca
se value-2: block-2;
break;
:
:
default: default-
block;break;
}
statement-x;

Theexpressionisanintegerexpressionorcharacters.Value-1,value-2,
...areconstantsorconstantexpressions andareknown as caselabels. Eachofthesevalues
shouldbeuniquewithinaswitchstatement.

Block-1,block-
2,...arestatementslistsandmaycontain0ormorestatements.Thereisnoneedtoputbraces({})aroundthes
eblocks.Caselabelsendwithacolon(:).

Whenaswitchisexecutedthevalueoftheexpressioniscomparedagainstthevalue(value-1,value-2,...).If
acase isfoundwhosevalueof expressionthenblockofstatementsthatfollowsthecaseareexecuted.

Thebreakstatementattheendofeachblocksignalstheendofaparticularcaseandcausesanexitfromthesw
itchstatement,transferringthecontroltothestatement-xfollowingtheswitchstatement.

Thedefaultisanoptionalcase,whenpresent,itwillbeexecutedifthevalueoftheexpressiondoesnotmatc
hwithanyofthecasevalues.
Ifnotpresent,noactiontakesplaceandifallmatchesfail;thecontrolgoestothestatement-x.

Theselectionprocessofswitchstatementisillustratedinflowchart:

Example1:Programtoprintwordscorrespondingnumbersbelow9
/*Print wordscorresponding numbers below 9*/
#include<stdio.h>
#include<conio.h>mai
n()
{
intn;clrsc
r();
printf("Enter a number(0-9):
");scanf("%d",&n);
switch(n)
{
case 0: printf("Zero");
break;
case 1: printf("One");
break;
case 2: printf("Two");
break;
case 3:

printf("Three");break;
case 4: printf("Four");
break;
case 5: printf("Five");
break;
case 6: printf("Six");
break;
case 7:

printf("Seven");
break;
case 8:

printf("Eight");
break;
case 9: printf("Nine");
break;
default: printf("More than 9");
}
getch();
}
Output:
Enteranumber (0-9): 3Three
Enteranumber (0-9): 10
More than 9

Algorithmsfor Conditional andCaseControl

Example:Writeanalgorithmtofindthelargestofthreenumbers.
Step1.Readthenumbersa,b,cStep2.If
a>bANDa>cthen
Step3.Print''aisthelargestnumber"Step4.
ElseIf
b>aANDb>cthenStep5.Print''bisthelarge
stnumber"
Step6.ElsePrint ''cisthelargest
number"Step7.Endofprogram.

Example:Writeanalgorithmtocalculatepaysalarywithovertime.
[Salarydependsonthepayrateandthenumberofhoursworkedperweek.However,ifyouworkmorethan40hours,you get
paidtime-and-a-halfforallhoursworkedover40.]
Step1.Readhoursandrate
Step2.Ifhours≤ 40then
Step3.Setsalaryashours*rateStep4.El
se
Step5.Setsalaryas[40*rate +(hours–40)*rate*1.5]
[salary=payratetimes40plus1.5timespayratetimes(hoursworked -40)]Step6.Printsalary
Step7.Endofprogram.
Pseudocode
isanartificialandinformallanguagethathelpsprogrammersdevelopalgorithms.Pseudocodeis
a"text-based"detail(algorithmic)designtool.ItisanalgorithmwritteninEnglishlikelanguage.
Pseudo-codeLanguageConstructions:
Computation/Assignment
setthevalueof"variable"to:"arithmeticexpression"or"variable"equal
s"expression"
Input/Output
get/read"variable","variable",...disp
lay"variable","variable",...
Conditional(dotnotationusedfornumberingsubordinatestatements)
6. if"condition"
6.1 (subordinate)statement1
6.2 etc...
7. else
7.1 (subordinate)statement2
7.2 etc...
Example:Writeapseudo-codetocompute thefinalpriceofanitemafterfiguring
insalestax.
Step1.Begin
Step2.getprice_of_itemStep
3.getsales_tax_rate
Step4.Setsales_taxtoprice_of_itemtimessales_tax_rateStep5.
Setfinal_pricetoprice_of_itemplussales_taxStep6.displayfinal
_price
Step7.End.

Example:Writeapseudocodetocheckw hetherastudentispassed ornot.


Step1.Begin
Step2.Readmarks
Step3.Ifmarksisgreaterthanorequalto60thenStep3.1.Pri
nt"StudentPassed"
Step4.Else
Step4.1.Print"StudentFailed"Step
5.EndIf;
Step6.End.
AlgorithmtoFindVolumeofSphere,ConeandCylinder(usingswitch...case..default)
step1:Start
step2:Definepi<-
3.14step3:Intilize1<-1
step4:checkwhetheri=1thengotostep5elsegotostep24step5:Readx
step6:checkwhetherx=1,thengotostep7elsegotostep10step7:Readr
step8:print4/3*pi*r*r*rstep9
:break
step10:checkwhetherx=2,thengotostep11elsegotostep14step11:readra
ndh
step12:print1/3*pi*r*r*hstep
13:break
step14:checkwhetherx=3,thengotostep15elsegotostep18step15:readra
ndh
step16:print4/3*pi*r*r*rstep
17:break
step18:checkwhetherx=4,thengotostep19elsegotostep21step19:i=0
step20:break
step21:printinvalidstep22
:break
step23:gotostep4
step24:Stop

SampleCPrograms
1. Tocheckw hethernumberis+ve,-veorzero
/*Program to check number is positive,negativeorzero*/
#include<stdio.h>
#include<conio.h>main
()
{
intn;clrscr();
printf("Enter a number:
");scanf("%d",&n);if(
n>0)
printf("Number is
Positive");if(n<0)
printf("Number is
Negative");if(n==0)
printf("Number is Zero");
}
Output:
Entera number:-2Number
isNegative
Entera number:
0Number isZero
Entera number:
6Number isPositive

2. Tochecktwonumbersareequal
/*Program to check whether the given numbers are equal*/
#include<stdio.h>
#include<conio.h>mai
n()
{
intnum1,num2;clrsc
r();
printf("Enter 2numbers:
");scanf("%d
%d",&num1,&num2);if(num1==num2)
printf("Both the numbers are
equal");getch();
}
Output:
Enter2numbers:66
Both the numbers are
equalEnter2numbers:32

3. Checkwhethergivencharacterisvowelorconsonant.
/*Program to check whether the givencharacter is vowel or consonant*/
#include<stdio.h>
#include<conio.h>m
ain()
{
char
x;clrscr();
printf("Enter letter:
");x=getchar();
if(x=='a'||x=='A'||x=='e'||x=='E'||x=='i'||x=='I'||x=='o'||x=='O'
||x=='u'||x=='U')
printf("The character %cisa vowel",x);
else
printf("The character %cisa consonant",x);
getch();
}
Output:
Enter letter: p
The character pisa consonant

Enter letter: a
The character aisa vowel
4. Programtocalculatesquareofnumberswhoseleastsignificantdigitis5.
/*Program to calculate square of numbers whose LSD is5*/
#include<stdio.h>
#include<conio.h>mai
n()
{
ints,d;clrscr()
;
printf("Enter a Number:
");scanf("%d",&s);
d=s%10;
if(d==5)
{
s=s/10;
printf("Square =%d %d",s*s++,d*d);
}
else
printf("\nInvalid Number");
}
Output:
Entera Number: 25Square
= 625
Entera Number:
32Invalid Number

5. Toobtaintheelectricbillasperthechargesbelow
NoofUnitsConsumed Rates(InRs.)
500 andabove 5.50
200-500 3.50
100-200 2.50
Lessthan100 1.50
/*Program to obtain electric bill asper meter reading*/
#include<stdio.h>
#include<conio.h>mai
n()
{
int
initial,final,consumed;floa
ttotal;
clrscr();
printf("Initial & Final Readings:
");scanf("%d
%d",&initial,&final);consumed = final-
initial;if(consumed>500)
total=consumed*5.50;
elseif(consumed>=200
&&consumed<=500)total=consumed*3.50;
else if(consumed>=100 &&
consumed<=199)total=consumed*2.50;
else
if(consumed<100)total=consu
med*1.50;
printf("Total bill for %d units is
%f",consumed,total);getch();
}
Output:
Initial & Final Readings: 1200
1500Totalbill for 300 units is
1050.000000

Initial & Final Readings: 800


900Totalbill for 100 units
is250.000000

6. Tocheckw hetherletterissmall,capital,digitorspecialsymbol.
/*Program to check small,capital,digitor special*/
#include<stdio.h>
#include<conio.h>mai
n()
{
char
x;clrscr();
printf("Enter character:
");scanf("%c",&x);
if(x>='a' &&
x<='z')printf("Small
letter");
else if(x>='A' &&
x<='Z')printf("Capital
letter");
else if(x>='0' &&
x<='9')printf("Digit");
else
printf("Special Symbol");
getch();
}
Output:
Entercharacter:*Special
Symbol
Entercharacter:TCapital
letter

Entercharacter:aSmal
lletter
Entercharacter:6Digi
t

7:Programtocheckwhetheraletterisvow elorconsonant
/*Program to check whether given letter is vowel or consonant*/
#include<stdio.h>
#include<conio.h>mai
n()
{
char
ch;clrscr();
printf("Enter Character:
");ch= getch();
switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U': printf("Character %cis
Vowel",ch);break;
default: printf("Character %cis Consonant",ch);
}
getch();
}

Output:
EnterCharacter:aCharact
er ais Vowel

Pr epar edbyIT &CSE Page80


EnterCharacter:BCharacter
Bis Consonant
8:ProgramtocalculateArithmeticOperations dependingonoperator.
/*Print words corresponding numbers below 9*/
#include<stdio.h>
#include<conio.h>mai
n()
{
inta,b;cha
r
ch;clrscr(
);
printf("Enter any arithmetic
operator:");scanf("%c",&ch);
printf("Enter two numbers:
");scanf("%d
%d",&a,&b);switch(ch)
{
case '+': printf("\nThe sum is
%d",a+b);break;
case '-': printf("\nThe differenceis %d",a-
b);break;
case '*': printf("\nThe product is
%d",a*b);break;
case '/': printf("\nThe quotientis
%d",a/b);break;
case '%': printf("\nThe remainder is %d",a
%b);break;
default: printf("Not Valid Operator");
}
getch();
}
Output:
Enter any arithmetic operator:
*Enter two numbers:84
Theproduct is32
UNIT-2

WEEK-5
1 GotoStatement, Contr ol Statements(Looping):While,

2 Do..While,ForLoop, Continue&Break(Unconditional)
3 NestedLoops,

4 SampleCPr ogr ams


------------------
GOTOStatement

Csupportsthegotostatementtobranchunconditionallyfromonepointtoanotherintheprogram.Althoug
hitmaynotbeessentialtousethegotostatementinahighlystructuredlanguagelikeC,theremaybeoccasio
nswhentheuseofgotomightbedesirable.
Thegotorequiresalabelinordertoidentifythe place
wherethebranchistobemade.Alabelisanyvalidvariablename,andmustbefollowedbycolon.Thelabelis
placedimmediatelybeforethestatementwherethecontrolistobetransferred.
Thegeneralformsofgotoandlabelstatementsareshownbelow:
gotolabel; label;
…. statement;
…. ….
…. ….
label; ….
statement; gotolabel;
ForwardJump BackwardJump

Thelabelcanbe anywhere intheprogram eitherbefore orafterthe


gotolabel;statement.Duringrunningofaprogramwhenastatementlikegotobegin;ismet,theflowofcon
trolwilljumptothestatementimmediatelyfollowingthelabelbegin.Thishappensunconditionally.
Example:ToprintMultiplicationTable
/*Program to print Multiplication Table*/
#include<stdio.h>
#include<conio.h>main(
)
{
inta,i=1;clrscr()
;
printf("Enter the value ofa: ");
Pr ogr ammingwithC-Lab

scanf("%d",&a);
printf("\nMultiplication Table for
%d\n",a);printf("---------------------------
----\n");
start:
printf("%d x%d=
%d\n",a,i,a*i);i=i+1;
if(i<=10)
goto start;
getch();
}
Output:
Enter the value ofa:5

Multiplication Table for 5


-------------------------------
5x1=5
5x2=10
5x3 =15
5x4=20
5x5=25
5x6=30
5x7=35
5x8=40
5x9=45
5x10=50

Advantage:
Usinggotostatementyoucanalterthenormalsequenceoftheprogramexecutionsoitgivesthepowertoju
mptoanypart ofprogram.

Disadvantages:
Itisalwaysrecommendednotto usegotostatementasthis
reducesthereadabilityoftheprogram.Itbecomesdifficulttotracethecontrolflowofaprogram,makingth
eprogramlogiccomplextounderstand.Usinggotostatementisconsideredaspoorprogrammingpractice.
AnyprogramwritteninClanguagecanbewrittenwithouttheuseofgotostatement.Sotrytoavoidgotostat
ementaspossibleasyoucan.

Loo ping
Loopisamechanismthroughwhichyourepeatedlyexecuteasetofstatements.Inlooping,asequenceofst
atementsisexecuteduntilsomeconditionforterminationoftheloopissatisfied.
Aprogramloop thereforeconsistsoftwosegments,onethebodyoftheloop&otherthecontrolstatement.
Thecontrolstatementtestscertainconditionsandthendirects
therepeatedexecutionofstatementscontainedinbodyoftheloop.
Dependingonthepositionofthecontrolstatementintheloop,acontrolstructuremaybeclassifiedeitheras
entry-controlledlooporexit-controlledloop.
□ Inentry-controlledloop ,thecontrolconditionsaretestedbeforestartoftheexecution.Ifconditionsare
notsatisfied,thenbodyofthe loopwillnotbeexecuted.
□ Inexit-controlledloop ,thetestisperformedattheendofthebodyoftheloopandtherefore the bodyis
executedunconditionallyforthefirsttime.

LoopControlStructures

Thetestconditionsshouldbecarefullystatedinordertoperformthedesirednumberofloopexecutions.Itis
assumedthatthetestconditionwilleventuallytransferthecontroloutoftheloop.Incase,duetosomereaso
nitdoesnotdoso,thecontrolsetsupaninfiniteloopandthebodyisexecutedoverandoveragain.
Aloopingprocess,ingeneral,would includethefollowingfoursteps:
1. Setting&Initializationofa counter
2. Executionofthe statements intheloop
3. Testforaspecifiedconditionfor execution of theloop
4. Updatingthecounter
Thetestmaybeeithertodeterminewhethertheloophasbeenrepeatedthespecifiednumberoftimesortode
terminewhetheraparticularconditionhasbeenmet.
TheClanguageprovidesthefollowingloopconstructs:
(a) whilestatement
(b) do..whilestatement
(c) forstatement
TheWHILEStatement
□ Thesimplestof allloopingstructuresisthewhile(anentry-controlledloop) statement.
□ Thebasicformatofwhilestatementis
Syntax:
while(test_condition)
{
statement;
}
test_condition IsanyvalidCcondition.Statementis repeatedlyexecuted
aslongascondition istrue.Once thecondition isfalse,loopisterminated
andcontrol istransferredto thestatementthatisimmediatelyafterthe
loop.
statement (Bodyof the loop)Maybe either asingle
statementoracompoundstatement.
□ Onexit,theprogramcontinueswiththestatementimmediatelyafterthebodyoftheloop.
Example1:Toprintthemessage5times
/*Print message 10times*/
#include<stdio.h>
#include<conio.h>mai
n()
{
inti=1;clrscr();
while(i<=5)
{ Output:
printf("\nCPNM"); CPNMCPN
i++; MCPNMCP
} NMCPNM
getch();
}

Example2:Toprint1to10numbers.
/*Print 1to10 numbers*/ Output:
#include<stdio.h> 1
#include<conio.h>main( 2
) 3
{ 4
inti=1;clrscr(); 5
while(i<=10) 6
{ 7
8
printf("\n%d",i); 9
i++; 10
}
getch();
}

Example3:Toprint1to10oddnumbers.
/*Print 1to10 numbers*/
#include<stdio.h>
#include<conio.h>main(
)
{
inti=1;clrscr();
while(i<=10) {
printf("\n Output:
%d",i);i+=2; 1
} 3
getch(); 5
} 7
9
Example4:Toprintlargestofthegivennumbers.
/*Program to display the largest of given numbers*/
#include<stdio.h>mai
n()
{
intnum;
int
largenum=0;clrscr
();
printf("Enter anumber(0to stop): ");scanf("%d",&num);
while(num!=0)
{
if(num>largenum)
largenum = num;
printf("Enter anumber(0tostop):
");scanf("%d",&num);
}
printf("Largest numberis
%d",largenum);getch();
}
Output:
Enteranumber(0to stop):
6Enteranumber(0to stop):
9Enteranumber(0to stop): 16
Enteranumber(0to stop):
98Enteranumber(0to stop):
0Largest numberis98
TheDO…WHILEStatement
□ Whenyouneedtoexecutestatementsatleastforonceirrespectiveoftheresultoftheconditiontheny
ouhavetousedo...whileloop.
□ Unlike while loop,inwhichconditionischeckedatthe
topoftheloop;indo...while,conditionischeckedatthebottom.
□ Do…
whileexecutesstatementsfirstandthencheckscondition.Astheresultstatementsareexecutedatlea
stonceasconditionisnotatallcheckedbeforethefirstiteration.
□ Thebasicformof do…whileis
Syntax:
do
{
statements;
}
while(test_condition);

Braces{}aremustfordo…
while.Andwecanhaveanynumberofstatementsbetweenbraces(bodyoftheloop).
□ Sincethetest_conditionisevaluatedatbottomoftheloop,thedo…whileconstructprovidesan exit-
controlled loop and thereforethebodyofloopis always executedatleastonce.
Example1:Tocalculatesumof10naturalnumbers.
/*Calculate sum of10 natural numbers*/
#include<stdio.h>
#include<conio.h>main
()
{
inti=1,sum=0;cl
rscr();
do
{
sum+=i;i+
+;
}
while(i<=10);
printf("\nThe sum of10 natural numbers is:
%d",sum);getch();
}
Output:
The sum of10 natural numbers is: 55

Example2:ToprintMultiplicationtable.
/*Program to print Multiplication Table*/
#include<stdio.h>
#define COLMAX10
#define
ROWMAX10main()
{
int
row,column,y;clrs
cr();
row=1;
printf(" MULTIPLICATION TABLE\n");
printf(" -----------------------------------------\n");
do
{
column=1;
do
{
y=row*column;printf("
%4d",y);column =
column+1;
}
while(column<=COLMAX);print
f("\n");
row=row+1;
}
while(row<=ROWMAX);
printf(" -----------------------------------------\n");
getch();
}
Output:MULTIPLICATION
TABLE
-----------------------------------------
1 2 3 4 5 6 7 8 9 1
2 4 6 8 1 1 1 1 1 0
2
3 6 9 1 0
1 2
1 4
2 6
2 8
2 0
3
4 8 1 2
1 5
2 8
2 1
2 4
3 7
3 0
4
5 1 2
1 6
2 0
2 4
3 8
3 2
4 6
4 0
5
6 10 5
1 0
2 5
3 0
3 5
4 0
4 5 0
6
7 12 8
2 4
2 0
3 6
4 2
4 8
5 4
6 0
7
8 14 1
2 8
3 5
4 2
4 9
5 6 3
7 0
8
9 16 4
2 2
3 0
4 8
5 6 4
7 2
8 0
9
8 7 6 5 4 3 2 1 0
1 2 3 4 5 6 7 8 9 1
0 0 0 0 0 0 0 0 0 0
-----------------------------------------
Example3:ToprintFibonacciSeries.
/*Program to print Fibonacci Series 0,1,1,2,3,5,8,13,...*/
#include<stdio.h>main
()
{
int
n,n1=0,n2=1,n3,i=3;clrscr
();
printf("Enter number for series:
");scanf("%d",&n);
printf("\nFibonacci Series:
");printf("\n%3d%3d",n1,n2);
do
{
n3=
n1+n2;printf("%3d"
,n3);n1= n2;
n2= n3;i+
+;
}while(i<=n);
getch();
}
Output:
Enternumber for series: 10

Fibonacci Series:
0 1 1 2 3 5 8132134

FORLoop:
□ Thisisanotherentrycontrolloop.
□ This integrates3 basic ingredients of a loop (initialization,condition andincrementing).
□ Forloopistypicallyusedtorepeatstatementsforafixednumberoftimes.
□ Thebasicformof forstatement:
Syntax:
for(initialization;condition;updation)
{
statement;
}

initialization Executed onlyfor oncejustbefore loop starts.Normallycounter(variable


used in loop)is initializedhere.
condition IsanyvalidCcondition.Aslongasthis istrue
statementisrepeatedlyexecuted.
updation Executed after the
statementisexecuted.Typicallycontainsincrementingcounteror
decrementingcounterasthecase maybe.
statement (Bodyof the loop)Thisisrepeatedlyexecuted aslongascondition
istrue.Itmaybeacompound statementalso.

Note:Alltheabovear eoptional.Soanyportionoftheloopcanbeomitted.Thoughaportionisomitted
,semicolon(;)afterthatmustbegiven.

Thefollowingisanexampletodisplaynumbersfrom1to10usingforloop.
for(n=1;n<=10;n++)
printf("%d\n",n);
Thisisineffectsameaswhileloopusedpreviously.But,asitcombinesinitialization,conditionandupdatio
n,itismoreeasiercomparedwithwhileloop.

Thefollowingisanotherexampleforforloopwhereinitializationandupdationpartsareomitted.
/*this istobeterminated when 0or negative number is
given*/for(;n>0;)
scanf("%d",&n);

Note:InC language,forloopcanbeusedin placeof whileloopandvice-


ver sa.Bothofthemexecutestatementsaslongastheconditionistrueandterminatethelooponceco
nditionisfalse.

Theforstatement
for(;;)
{
statement;
}
isaninfiniteloop.Thiscanbeterminatedusingabreakstatementoranexit()function.

CommaOperator
Itispossibletohavemorethanoneexpressionininitializationandupdationportionsusing(comma)opera
tor.Commaoperatorisusedtoseparateexpressions.
Thefollowingisanexampleofforloopusingcommaoperator:
printf("\nn\tj");fo
r(n=0,j=10;n<j;n++,j--)
printf("\n%d\t
%d",n,j);Theoutputof the above
example isn j
0 10
1 9

Pr epar edbyIT &CSE Page90


2 8
3 7

Pr epar edbyIT &CSE Page91


4 6

Example1:Tocalculatefactorialofanynumber
/*Program to calculate factorial of given number*/
#include<stdio.h>mai
n()
{
inti,n;
long int
fact=1;clrscr();
printf("Enter nvalue:
");scanf("%d",&n);for(i=1;i
<=n;i++)
fact=fact*i;
printf("Factorial of%dis
%ld",n,fact);getch();
}
Output:
Enternvalue:8Factorial
of8is 40320

Example2:Programtofindnumberofevenandoddnumbersinthelist
/*Program to find numberofeven and odd numbers in the list*/
#include<stdio.h>
#include<conio.h>mai
n()
{
int
i,n,num,ecount=0,ocount=0;clrscr(
);
printf("Enter numberof values:
");scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter avalue:
");scanf("%d",&num);if(num
%2==0) ecount++;else
ocount++;
}
printf("Even count in the listof%d numbers is
%d\n",n,ecount);printf("Odd count in the list of%d numbers is
%d\n",n,ocount);getch();
}
Output:
Enternumberof values: 10
Enteravalue:8Enterav
alue:6Enteravalue:4E
nteravalue:12Enterav
alue:9Enteravalue:2E
nteravalue:3Enter
avalue:1Enteravalue:
15Enteravalue:98
Even count in the listof10 numbers is6Odd
count in the list of10 numbers is4

Example 3:Findoutthesumofseries12 +2 2 +….+n2


/*Program to find the sum of series 12+22+…+ n2*/
#include<stdio.h>
#include<math.h>main
()
{
intn, sum=0,
i;clrscr();
printf("Enter nvalue:
");scanf("%d",&n);for(i=1;i
<=n;i++)
{
sum= sum + pow(i,2);
}
for(i=1;i<=n;i++) {
if(i!=n) printf("%d^2 +
",i);else printf("%d^2 =
%d",i,sum);
}
getch();
}
Output:
Enternvalue:10
1^2+ 2^2 + 3^2 + 4^2 + 5^2 + 6^2 + 7^2 + 8^2 + 9^2 + 10^2 = 385

Example4:Findoutthesumofseries1+x2/2!-x3/3!+....
/*Program to print sum ofseries1+x2/2! -x3/3!+....*/
#include<math.h>main
()
{
int
n,i,k,j,x,sign=1;intf;
char ch;
floatsum=1;clrs
cr();
printf("Enter numberofterms:
");scanf("%d",&n);
printf("Enter xvalue:
");scanf("%d",&x);
k=1;
for(i=1;i<n;i++)
{
j=k;f=1
;
while(j>0) {
f=f*j;j-
-;
}
sum=sum+sign*((float)
(pow(x,i))/f);k++;
sign=sign*(-1);
}
printf("\n1");for(i=1;i<n
;i++) {
if(i%2==0) ch='-';
else ch='+';
printf(" %c %d^%d/%d!",ch,x,i,i);
}
printf(" =
%f",sum);getch();
}
Output:
Enternumberofterms:5Enterxv
alue:2

1+ 2^1/1!- 2^2/2! +2^3/3!- 2^4/4! = 1.666667

breakstatement

Thisisused toterminatealoop.A loopcanbe terminatedeither whenconditionis


falseorwhenyouexecutebreakstatement.Whenyouhavetoterminateloopbasedonsomeothercondition
otherthanconditionoftheloopthenyoucanusebreakstatement.
Example1:Programtoimplementbreakstatement
/*Program to Implement break Statement*/
#include<stdio.h>main
()
{
inti;
clrscr();
for(i=1; i<=10; i++)
{
printf("\n%d",
i);if(i ==7)
break;
}
getch();
}
Output:
1
2
3
4
5
6
7

Example2:Programtodisplaysumof10numbersortill0isgivenwhichcomesfirst.
/*Program to display sum of given numbers*/
#include<stdio.h>mai
n()
{
intsum=0,n,c;clrscr();
for(c=1;c<=10;c++)
{
printf("Enter anumber(0to stop):
");scanf("%d",&n);
if(n==0)
break;
sum+=n;
}
printf("Sum =
%d",sum);getch();
}
Output:
Enteranumber(0to stop):
5Enteranumber(0to stop):
6Enteranumber(0to stop):
4Enteranumber(0 to stop):
2Enteranumber(0to stop):
8Enteranumber(0to stop):
0Sum=25
continuestatement

Thisisusedtotransfercontroltothebeginningoftheloopfromwithintheloop.Itisusedtoskipthestatements
aftercontinuestatementandenterintonextiterationoftheloop.
Example:ProgramtoImplementcontinueStatement
/*Program finds squareofpositive numbers only*/
#include
<stdio.h>main()
{
inti,n,a, sq;
clrscr();
printf("\nHow many numbers you want toenter:
");scanf("%d", &n);
for(i=1;i<=n; i++)
{
printf("\nEnter number:
");scanf("%d", &a);
if(a<0)
continue;s
q=a*a;
printf("\nSquare = %d\n", sq);
}
getch();
}
Output:
Howmany numbers you want to enter:

3Enter number: 2

Square =4

Enter number:-1

Enter number: 6

Square =36

NestedLoops

Whenaloopisplacedinsideanotherloop,itiscalledasnestedloop.Callowsnestedloops.Theinnerlooporn
estedloopisexecutedforeachrepetitionoftheouterloop.
Example1:Displaynumbersinthefollowingformat.
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
#include<stdio.h>mai
n()
{
inti,j;clrscr();
for(i=1;i<=5;i++)
{
printf("\n");
for(j=1;j<=5;j ++)printf("%5d", j);
}
getch();
}
Example2:Displaynumbersinthefollow ingformat.
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
#include<stdio.h>mai
n()
{
inti,j;clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j ++) {printf("%5d", j);
}
printf("\n");
}
getch();
}
Example3:Displaynumbersinthefollow ingformat.
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
#include<stdio.h>mai
n()
{
inti,j;clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j ++) {printf("%5d", i);
}
printf("\n");
}
getch();
}
Example4:Displaynumbersinthefollow ingformat.
1 1 1 1 1
2 2 2 2
3 3 3
4 4
5
#include<stdio.h>mai
n()
{
inti,j;clrscr()
;
for(i=1;i<=5;i++)
{
for(j=5;j>=i;j--){
printf("%5d", i);
}
printf("\n");
}
getch();
}

Example5:Displaynumbersinthefollow ingformat.
5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
#include<stdio.h>mai
n()
{
inti,j;clrscr()
;
for(i=1;i<=5;i++)
{
for(j=5;j>=i;j--){
printf("%5d",j);
}
printf("\n");
}
getch();
}
Example6:Displaynumbersinthefollow ingformat.
5
4 4
3 3 3
2 2 2 2
1 1 1 1 1
#include<stdio.h>mai
n()
{
inti,j;clrscr()
;
for(i=5;i>=1;i--)
{
for(j=5;j>=i;j--){
printf("%5d", i);
}
printf("\n");
}
getch();
}
Example7:Displaynumbersinthefollow ingformat.
*
**
***
****
*****
#include<stdio.h>mai
n()
{
inti,j,n;
clrscr();n=
5;
for(i=0;i<n;i++)
{
for(j=0;j<=i;j++)
printf("*");
printf("\n");
}
getch();
}

Example8:DisplayPascal’sTriangle.
Enterthenumberofrows:6
1
1 1
1 2 1
1 3 3 1
1 4 6 4
1 5 10 5 1
#include<stdio.h>main
()
{
inti,j,k,r,x;cl
rscr();
printf("Enter the numberof rows:
");scanf("%d",&r);
i=1;
for(k=0;k<r;k++)
{
for(j=30-3*k;j>0;j--)
printf("
");for(x=0;x<=k;x+
+)
{
if(x==0||
k==0)i=i
;
else
i=(i*(k-x+1)/x);
printf("%6d",i);
}
printf("\n");
}
getch();
}

AlgorithmsforLoopingStatements
Algorithmtofindreverseof agiven numberusingWhile Loop.
Step1:Begin
Step2:Display"Enteranumber:
"Step3:Readn
Step4:Initializerev to0
Step5:While"n!
=0",doStep5.1:rem=n%10
Step5.2:rev=
(rev*10)+remStep5.3:n=n/10
Step6:EndWhile;
Step7:Print"ReverseNumber:",revStep8:
End

Algorithmtoprintthe FibonacciSeries usingDo..WhileLoop.


Step1:Begin
Step2:Display"Enteranumber:
"Step3:Readn
Step4:Initializen1to0andn2to1Step5:Pri
nt n1,n2
Step6:Do
Step6.1:n3=
n1+n2Step6.2:Print
n3Step6.3:Set n2
ton1Step6.4:Set n3
ton2Step6.5:Increme
nt i
Step7:While"i<=n"gotoStep
6Step8:EndDo;
Step9:End

Algorithmtocheckwhether given number isprime number ornot.


Step1:Begin
Step2:Display"Enteranumber:
"Step3:Readn
Step4:Initializecto0Step5:
Fori=1ton,do
Step5.1:If"n%i==0"
Step5.1.1:Incrementcby1
Step5.2:EndIf;
Step5.3:Increment iby1
Step6:EndFor;Step
7:If"c<=2"
Step7.1:Displayn"isprimenumber"Step8:El
se
Step8.1:Displayn"isnot
primenumber"Step9:EndIf;
Step10:End.

Pr epar edbyIT &CSE Page100

You might also like