Docsity

Programming In C Language (Unit-1), Study notes of C programming

Toggle sidebar
bg1
MODULE1

LECTURENOTE-1




ABEGINNER’SGUIDE

INTRODUCTIONTOCOMPUTERS


Any programming language is implemented on a computer. Right form its inception, to the
presentday, all computer system (irrespective of their shape& size) perform the following 5
basicoperations.Itconvertstherawinputdataintoinformation,whichisusefultotheusers.

ØInputting:Itistheprocessofenteringdata&instructionstothecomputersystem.
ØStoring:Thedata&instructionsarestoredforeitherinitialoradditionalprocessing,
as&whenrequired.
ØProcessing:Itrequires performingarithmeticorlogicaloperationon thesaveddata
toconvertitintousefulinformation.
ØOutputting:Itistheprocessofproducingtheoutputdatatotheenduser.
ØControlling:Theaboveoperationshavetobedirectedinaparticularsequencetobe
completed.

Basedonthese5operations,wecansketchtheblockdiagramofacomputer.

Fig1:BlockDiagramofaComputer





pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22

Partial preview of the text

Download Programming In C Language (Unit-1) and more Study notes C programming in PDF only on Docsity!

MODULE1

LECTURENOTE-1

ABEGINNER’SGUIDE

INTRODUCTIONTOCOMPUTERS

Any programming language is implemented on a computer. Right form its inception, to the present day, all computer system (irrespective of their shape & size) perform thefollowing 5 basicoperations.Itconvertstherawinputdataintoinformation,whichisusefultotheusers. Ø Inputting:Itistheprocessofenteringdata&instructionstothecomputersystem. Ø Storing:Thedata&instructionsarestoredforeitherinitialoradditionalprocessing, as&whenrequired. Ø Processing:Itrequiresperformingarithmeticorlogicaloperationonthesaveddata toconvertitintousefulinformation. Ø Outputting:Itistheprocessofproducingtheoutputdatatotheenduser. Ø Controlling:Theaboveoperationshavetobedirectedinaparticularsequencetobe completed. Basedonthese5operations,wecansketchtheblockdiagramofacomputer.

Fig1:BlockDiagramofaComputer

Ø Input Unit: We need to first enter the data & instruction in the computer system, beforeanycomputationbegins.Thistaskisaccomplishedbytheinputdevices.(Eg: keyboard,mouse,scanner,digitalcameraetc).Thisdeviceisresponsibleforlinking thesystemwiththeexternalenvironment.Thedataacceptedisinahumanreadable form.Theinputdeviceconvertsitintoacomputerreadableform. Ø Storage Unit: The data & instruction that are entered have to be stored in the computer.Similarly,theendresults&theintermediateresultsalsohavetobestored somewherebeforebeingpassedtotheoutputunit.Thestorageunitprovidessolution to all these issues. This storage unit is designed to save the initial data, the intermediateresult&thefinalresult.Thisstorageunithas2units:Primarystorage &Secondarystorage.

Primary Storage: The primary storage, also called as the main memory, holds the data when thecomputer is currently on. As soon as the system is switched off or restarted, the information held in primary storage disappears (i.e. it is volatile in nature). Moreover, the primary storage normally has a limited storage capacity, becauseitisveryexpensiveasitismadeupofsemiconductordevices. Secondary Storage: The secondary storage, also called as the auxiliary storage, handles the storage limitation& the volatile natureofthe primary memory. It can retaininformationevenwhenthe system isoff.Itis basicallyused forholdingthe programinstructions&dataonwhichthecomputerisnotworkingoncurrently,but needstoprocessthemlater. Ø Central ProcessingUnit: Together the Control Unit &the Arithmetic Logic Unit are called as the Central Processing Unit (CPU). The CPU is the brain of the computer.Likeinhumans,themajordecisionsaretakenbythebrainitself&other bodypartsfunctionasdirectedbythebrain.Similarlyinacomputersystem,allthe majorcalculations&comparisonsaremadeinsidetheCPU.TheCPUisresponsible foractivating&controllingtheoperationofotherunitsofthecomputersystem. ArithmeticLogicUnit:Theactualexecutionoftheinstructions(arithmeticorlogical operations) takes place over here. The data & instructions stored in the primary storage are transferred as & when required. No processing is done in the primary storage.Intermediate resultsthat are generated in ALU are temporarily transferred back to the primary storage, until needed later. Hence, data may move from the primarystoragetoALU&backagaintostorage,manytimes,beforetheprocessing isdone. ControlUnit:Thisunitcontrolstheoperationsofallpartsofthecomputerbutdoes notcarryoutanyactualdataprocessing.Itisresponsibleforthetransferofdataand instructions among other units of the computer.It manages and coordinates all the units of the system.It also communicates with Input/Output devices for transfer of dataorresultsfromthestorageunits.

LECTURENOTE-2

INTRODUCTIONTOPROGRAMMING

A language that is acceptable to a computer system is called a computer language or programminglanguageandtheprocessofcreatingasequenceofinstructionsinsuchalanguage iscalledprogrammingorcoding.Aprogramisasetofinstructions,writtentoperformaspecific taskbythecomputer.A setoflargeprogramis calledsoftware.Todevelopsoftware, onemust haveknowledgeofaprogramminglanguage.

Beforemovingontoanyprogramminglanguage,itisimportanttoknowaboutthevarioustypes of languages used by the computer. Let us first know what the basic requirements of the programmerswere&whatdifficultiestheyfacedwhileprogramminginthatlanguage.

COMPUTERLANGUAGES

Languages are a means of communication. Normally people interactwith each otherthrough a language.Onthesamepattern,communicationwithcomputersiscarriedoutthroughalanguage. This language is understood both by the user and the machine. Just as every language like English,Hindihasitsowngrammaticalrules;everycomputerlanguageisalsoboundedbyrules knownassyntaxofthatlanguage.Theuserisboundbythatsyntaxwhilecommunicatingwiththe computersystem.

Computerlanguagesarebroadlyclassifiedas:

Ø LowLevelLanguage:Thetermlowlevelhighlightsthefactthatitisclosertoalanguage whichthemachineunderstands. Thelowlevellanguagesareclassifiedas: o MachineLanguage:Thisisthelanguage(intheformof0’sand1’s,calledbinary numbers) understood directly by the computer. It is machine dependent. It is difficulttolearnandevenmoredifficulttowriteprograms.

o AssemblyLanguage:Thisisthelanguagewherethemachinecodescomprisingof 0’sand1’saresubstitutedbysymboliccodes(calledmnemonics)toimprovetheir understanding. It is the first step to improve programming structure. Assembly language programming is simpler and less time consuming than machine level programming,itiseasiertolocateandcorrecterrorsinassemblylanguagethanin machine language programs. It is also machine dependent. Programmers must haveknowledgeofthemachineonwhichtheprogramwillrun.

Ø HighLevelLanguage:Lowlevellanguagerequiresextensiveknowledgeofthehardware sinceitismachinedependent.Toovercomethislimitation,highlevellanguagehasbeen evolved which uses normal English,which is easy to understand to solve any problem. Highlevellanguagesarecomputerindependentandprogrammingbecomesquiteeasyand simple.Varioushighlevellanguagesaregivenbelow: o BASIC (Beginners All Purpose Symbolic Instruction Code): It is widely used, easytolearngeneralpurposelanguage.Mainlyusedinmicrocomputersinearlier days. o COBOL (Common Business Oriented language): A standardized language used forcommercialapplications. o FORTRAN (Formula Translation): Developed for solving mathematical and scientific problems. One of the most popular languages among scientific community. o C: Structured Programming Language used for all purpose such as scientific application,commercialapplication,developinggamesetc. o C++:Popularobjectorientedprogramminglanguage,usedforgeneralpurpose. PROGRAMMINGLANGUAGETRANSLATORS

As you know that high level language is machine independent and assembly language though it is machine dependent yet mnemonics that are being used to represent instructionsarenotdirectlyunderstandablebythemachine. Hencetomake themachine understand the instructions provided by both the languages, programming language instructorsareused.Theytransformtheinstructionpreparedbyprogrammersintoaform which canbe interpreted &executed by thecomputer. Flowing are the various tools to achievethispurpose: Ø Compiler:Thesoftwarethatreadsaprogramwritteninhighlevellanguageandtranslates it into an equivalent program in machine language is called as compiler. The program written by the programmer in high level language is called source program and the programgeneratedbythecompileraftertranslationiscalledasobjectprogram. Ø Interpreter:italsoexecutesinstructionswritteninahighlevellanguage.Bothcomplier& interpreterhavethesamegoali.e.toconverthighlevellanguageintobinaryinstructions, buttheir methodof executionisdifferent. The complierconverts the entire source code intomachinelevelprogram,whiletheinterpretertakes1statement,translatesit,executes it&thenagaintakesthenextstatement.

Ø Assembler:Thesoftwarethatreadsaprogramwritteninassemblylanguageandtranslates itintoanequivalentprograminmachinelanguageiscalledasassembler.

LECTURENOTE-3

INTRODUCTIONTOC

BriefHistoryofC

Ø TheCprogramminglanguageisastructureorientedprogramminglanguage,developedat BellLaboratoriesin1972byDennisRitchie.

Ø Cprogramminglanguagefeatureswerederivedfromanearlierlanguagecalled“B” (BasicCombinedProgrammingLanguage–BCPL) Ø ClanguagewasinventedforimplementingUNIXoperatingsystem. Ø In1978,DennisRitchieandBrianKernighanpublishedthefirstedition“TheC ProgrammingLanguage”andiscommonlyknownasK&RC. Ø In 1983, the American National Standards Institute (ANSI) established a committee to provide a modern, comprehensive definition of C. The resulting definition, the ANSI standard,or“ANSIC”,wascompletedlate1988.

Ø ManyofC’sideas&principleswerederivedfromtheearlierlanguageB,therebynaming thisnewlanguage“C”.

TaxonomyofCLanguage

WHYISCPOPULAR

Ø Itisreliable,simpleandeasytouse. Ø Cisasmall,block-structuredprogramminglanguage. Ø Cisaportablelanguage,whichmeansthatCprogramswrittenononesystemcanberun onothersystemswithlittleornomodification. Ø Chasoneofthelargestassortmentsofoperators,suchasthoseusedforcalculationsand datacomparisons. Ø Although the programmer has more freedom with data storage, the languages do not checkdatatypeaccuracyfortheprogrammer.

WHYTOSTUDYC

Ø By the early 1980s, C was already a dominant language in the minicomputer world of Unix systems. Sincethen, it has spread to personal computers (microcomputers) and to mainframes. Ø Many software houses use C as the preferred language for producing word processing programs,spreadsheets,compilers,andotherproducts. Ø C is an extremely flexible language—particularly if it is to be used to write operating systems. Ø Unlikemostotherlanguagesthathaveonlyfourorfivelevelsofprecedence,Chas15.

CHARECTERESTICSOFACPROGRAM

Ø Middlelevellanguage.

HighLevel MiddleLevel LowLevel Highlevellanguages providealmosteverything thattheprogrammermight needtodoasalreadybuilt intothelanguage

Middlelevellanguagesdon’t provideallthebuilt-infunctions foundinhighlevellanguages, butprovidesallbuildingblocks thatweneedtoproducetheresult wewant

Lowlevellanguages providesnothing otherthanaccessto themachinesbasic instructionset

Examples: Java,Python

C,C++ Assembler

Ø Smallsize–hasonly32keywords Ø Extensiveuseoffunctioncalls-enablestheendusertoaddtheirownfunctionstotheC library. Ø Supportsloosetyping–acharactercanbetreatedasaninteger&viceversa. Ø Structuredlanguage

STRUCTUREOFACPROGRAM

The structure of a C program is a protocol (rules) to the programmer, which he has to follow while writing a C program. The general basic structure of C program is shown in the figure below.

Basedonthisstructure,wecansketchaCprogram.

Example:

/Thisprogramacceptsanumber&displaysittotheuser/

#include voidmain(void) {intnumber; printf("Pleaseenteranumber:"); scanf("%d",&number); printf("Youentered%d",number); return0;}

Stepwiseexplanation:

#include

Ø Thepartofthecompilerwhichactuallygetsyourprogramfromthesourcefileiscalled thepreprocessor. §#include Ø #includeisapre-processordirective.Itisnot really partofourprogram,butinsteaditis aninstructiontothecompilertomakeitdosomething.IttellstheCcompilertoinclude thecontentsofafile(inthiscasethesystemfilecalledstdio.h). Ø Thecompilerknowsitisasystemfile,andthereforemustbelookedforinaspecialplace, bythefactthatthefilenameisenclosedin<>characters

Ø stdio.h is the name of the standard library definition file for all STanDard Input and Outputfunctions. Ø Yourprogramwillalmostcertainlywanttosendinformationtothescreenandreadthings fromthekeyboard,andstdio.histhenameofthefileinwhichthefunctionsthatwewant tousearedefined. Ø Thefunctionwewanttouseiscalledprintf.Theactualcodeofprintfwillbetiedinlater bythelinker. Ø The".h"portionofthefilenameisthelanguageextension,whichdenotesanincludefile.

void

Ø This literally means that this means nothing. In this case, it is referring to thefunction whosenamefollows. Ø VoidtellstoCcompilerthatagivenentityhasnomeaning,andproducesnoerror.

main

Ø Inthisparticularexample,theonlyfunctionintheprogramiscalledmain. Ø A Cprogramistypicallymadeupoflargenumberof functions.Eachoftheseisgivena namebytheprogrammerandtheyrefertoeachotherastheprogramruns. Ø Cregardsthenamemainasaspecialcaseandwillrunthisfunctionfirsti.e.theprogram executionstartsfrommain.

(void)

Ø Thisisapairofbracketsenclosingthekeywordvoid. Ø Ittellsthecompilerthatthefunctionmainhasnoparameters. Ø Aparametertoafunctiongivesthefunctionsomethingtoworkon.

Ø Header File- A header file is a file with extension .h which contains the C function

declarationsandmacrodefinitionsandtobesharedbetweenseveralsourcefiles.

Ø ObjectFile- Anobjectfileisafilecontainingobjectcode,withanextension.o,meaning

relocatable format machinecode thatis usually not directly executable.Object filesare producedbyanassembler,compiler,orotherlanguagetranslator,andusedasinputtothe linker, which inturntypically generates an executable or library by combining parts of objectfiles. Ø ExecutableFile-Thebinaryexecutablefileisgeneratedbythelinker.Thelinkerlinksthe variousobjectfilestoproduceabinaryfilethatcanbedirectlyexecuted.

COMPLIATION&EXECUTIONOFACPROGRAM

LECTURENOTE-4

ELEMENTSOFC

Everylanguagehassomebasicelements&grammaticalrules.Beforestartingwithprogramming, weshouldbeacquaintedwiththebasicelementsthatbuildthelanguage.

CharacterSet

Communicatingwithacomputerinvolvesspeakingthelanguagethecomputerunderstands.InC, variouscharactershavebeengiventocommunicate.

CharactersetinCconsistsof;

Types CharacterSet Lowercase a-z Uppercase A-Z Digits 0-9 SpecialCharacter !@#$%^&* Whitespace Tabornewlinesorspace

Keywords

Keywords are the words whose meaning has already been explained to the C compiler. The keywords cannotbeused as variablenamesbecauseif we dosowe aretryingto assigna new meaningtothekeyword,whichisnotallowedbythecomputer.

Thereareonly32keywordsavailableinC.Belowfiguregivesalistofthesekeywordsforyour readyreference.

long 4bytes -2,147,483,648to2,147,483,647

unsignedlong 4bytes 0to4,294,967,295

Type Storagesize Valuerange Precision

float 4bytes 1.2E-38to3.4E+38 6decimalplaces

double 8bytes 2.3E-308to1.7E+308 15decimalplaces

longdouble 10bytes 3.4E-4932to1.1E+4932 19decimalplaces

Constants

Aconstantisanentitythatdoesn’tchangewhereasavariableisanentitythatmaychange.

Cconstantscanbedividedintotwomajorcategories: ¡ PrimaryConstants ¡ SecondaryConstants

Here our only focus is on primary constant. For constructing these different types of constants certainruleshavebeenlaiddown.

RulesforConstructingIntegerConstants:

Anintegerconstantmusthaveatleastonedigit.

a) Itmustnothaveadecimalpoint. b) Itcanbeeitherpositiveornegative.

c) Ifnosignprecedesanintegerconstantitisassumedtobepositive.

d) Nocommasorblanksareallowedwithinanintegerconstant.

e) Theallowablerangeforintegerconstantsis-32768to32767.

Ex.:426,+782,-8000,-7605

RulesforConstructingRealConstants:

Real constants are often called Floating Point constants. The real constants could be written in twoforms—FractionalformandExponentialform.

Rulesforconstructingrealconstantsexpressedinfractionalform:

a) Arealconstantmusthaveatleastonedigit.

b) Itmusthaveadecimalpoint.

c) Itcouldbeeitherpositiveornegative.

d) Defaultsignispositive.

e) Nocommasorblanksareallowedwithinarealconstant.

Ex.+325.34,426.0,-32.76,-48.5792

Rulesforconstructingrealconstantsexpressedinexponentialform:

a) Themantissapartandtheexponentialpartshouldbeseparatedbyalettere.

b) Themantissapartmayhaveapositiveornegativesign.

c) Defaultsignofmantissapartispositive.

d) Theexponent musthaveatleastonedigit,whichmustbe a positiveornegativeinteger. Defaultsignispositive.

e) Rangeofrealconstantsexpressedinexponentialformis-3.4e38to3.4e38.

Ex.+3.2e-5,4.1e8,-0.2e+3,-3.2e-5

RulesforConstructingCharacterConstants:

a) Acharacterconstantisasinglealphabet,asingledigitorasinglespecialsymbolenclosed withinsingleinvertedcommas. b) Themaximumlengthofacharacterconstantcanbe1character.

Ex.:‘M’,‘6’,‘+’

2. main()

{charfirst;

charmiddle;

charlast;

//Restofprogramfollows

}

ØInitializationofVariables

When a variable is declared, it contains undefined value commonly known as garbage value.Ifwewantwecanassignsomeinitialvaluetothevariablesduringthedeclaration itself.Thisiscalledinitializationofthevariable.

Eg- intpageno=10;

chargrade=’A’;

floatsalary=20000.50;

Expressions

An expression consists of a combinationofoperators,operands,variables & function calls. An expressioncanbearithmetic,logicalorrelational.Herearesomeexpressions:

a+b–arithmeticoperation

a>b-relationaloperationa

==b-logicaloperation

func(a,b)–functioncall

a*(b+c/d)/20

q=5*2x=

++q%3

q>3

As you can see, the operands can be constants, variables, or combinations of the two. Some expressionsarecombinationsofsmallerexpressions,calledsubexpressions.Forexample,c/disa subexpressionofthesixthexample.

AnimportantpropertyofCisthateveryCexpressionhasavalue.Tofindthevalue,youperform theoperationsintheorderdictatedbyoperatorprecedence.

Statements Statementsaretheprimarybuildingblocksofaprogram.Aprogramisaseriesofstatementswith

some necessary punctuation. A statement is a complete instruction to the computer. In C,

statementsareindicatedbyasemicolonattheend.Therefore

legs=4

isjustanexpression(whichcouldbepartofalargerexpression),but

legs=4;

isastatement.

What makes a complete instruction?First, C considers any expressionto be a statement if you appendasemicolon.(Thesearecalledexpressionstatements.)Therefore,C won'tobjecttolines suchasthefollowing:

8;

3+4;

However, these statements do nothing for your program and can't reallybe considered sensible statements.Moretypically,statementschangevaluesandcallfunctions:

x=25;

++x;

y=sqrt(x);

Althoughastatement(or,atleast,asensiblestatement)isacompleteinstruction,notallcomplete instructionsarestatements.Considerthefollowingstatement:

x=6+(y=5);

Init,thesubexpressiony=5isacompleteinstruction,butitisonlypartofthestatement.

Becauseacompleteinstructionisnotnecessarilyastatement,asemicolonisneededtoidentify instructionsthattrulyarestatements.