Вы находитесь на странице: 1из 246

C

Programming

BasicsofCProgramming

ContentinthisisforWindowsversionandturboCsoftware.
Codemightslightlyvarybasedonsoftwareweuse.

C Programming

BASICTERMINOLOGY

Computer:Itisanelectronicdevice.Ithasmemoryanditperformsarithmeticandlogicaloperations.
Input:Thedataenteringintothecomputeriscalledinput.
Output:Theinformationobtainedbythecomputeriscalledoutput.
Program:Asequenceofinstructionstosolvethegivenproblemisknownaprogram.
Software:Thegroupofprogramstooperateandcontroltheoperationsofacomputer.Softwarecanbeclassifiedinto
2types.SystemsoftwareandApplicationsoftware.
Hardware:Allthephysicalcomponentsorunitsconnectedtothecomputercircuitiscalledhardware.
Operatingsystem:Itisaninterfacebetweenuserandthecomputer.Inotherwords,O.Sisa
Complexsetofprograms,thatmanagetheresourcesofacomputerresourcesinclude,input,output,processoretc.
SoO.Sisaresourcemanager.
Language:itconsistsofasetofexecutableinstructions.
Package:Itisdesignedbyanyotherlanguagewithlimitedresources.

ASCIIcharacterset
(Americanstandardcodeforinformationandinterchange)
Charactertypenoofcharacters

Capitalletters26
Smallletters26
Digits10
Specialsymbols32
Controlcharacters34
Graphiccharacters128
Total

256

Outof256charactersetthefirst128arecalledasciicharacters
Thennext128arecalledgraphiccharacters(or)extendedasciicharacters.

C Programming

AtoZ6590
atoz97122
0to94857
Space32
Backspace8
Tab9
Esc27
&38

Classificationofprogramminglanguage

Programminglanguagesareclassifiedinto2types.
1.Lowlevellanguage
2.Highlevellanguage
1. Lowlevellanguage
Alowlevellanguageiscalledassemblylanguageisdesigninthebeginning.Ithassomesimpleinstructions.Butthese
instructionsarenotinbinarycodebuthecomputercanunderstandonlymachinelevellanguage.Henceaconverter
(or)translatorisdevelopedtotranslatealowlevellanguageprogramintomachinelevellanguage.Thistranslatoris
calledasassembler.
2. Highlevellanguage:
ThesearemoreEnglishlikelanguageshencetheprogrammerveryeasytolearn.
Toconverttheprogramswritteninhighlevellanguagetomachinelevellanguagecompilersandinterpretersareused.
Translators
Thereare3typesoftranslatorsavailableforthelanguages.
Assembler:Thistranslatorisusedtoconvertthelowlevellanguageintomachinelevellanguage.
Compiler:Compilersareusedtoconvertthehighlevellanguagesintomachinelevellanguage.Itcheckspererrorsin
entireprogramandconvertstheprogramintomachinelanguage.
Interpreter:Itisalsousedtoconverthighlevellanguageintomachinelevellanguage.Itcheckspererrorsstatement
bystatementandconvertsthestatementintomachinelanguage.

C Programming

VariousStepsInvolvedinProgramorApplicationDevelopment:
Thefollowingstepsareinvolvedinprogramdevelopment
1.Problemdefinition
2.Analysis&Design
3.Algorithms
4.Flowchart
5.Coding&implementation
6.Debugging&testing
7.Documentation

1. Problemdefinition
Problemdefinitionphaseisaclearunderstandingofexactlywhatisneededforcreatingaworkablesolution.It
involvesthreespecifications
1.Inputspecification
2.Outputspecification
3.Processing
2.Analysis&Design
Beforegoingtomakeafinalsolutionfortheproblem,itmustbeanalysed.Outlinesolutionispreparedinthecaseof
simpleproblems,butincaseofcomplexproblemsthemainproblemisdividedintosubproblemscalled'modules'.
Thesemodulescanbehandledandsolvedindependently.Whenthetaskistoobig,itisalwaysbettertoanalysethe
tasksuchthatitcanbedividedintonumberofmodulesandseeksolutionforeach.
3.Algorithm
Oncetheproblemisdividedintonumberofmodules,thelogicforsolvingeachmodulecanbedeveloped.Thelogicis
expressedstepbystep.Astepbystepproceduretosolvethegivenproblemiscalledalgorithm.Analgorithmis
definedasafinitesetofinstructionswhichaccomplishaparticulartask.Analgorithmcanbedescribedinanatural
languagelikeEnglish.
4.Flowchart
Aftercompletionofalgorithm,theprogramcanbevisualisedbydrawingaflowchart.Aflowchartisnothingbuta
graphicalorsymbolicrepresentationofhowinstructionswillbeexecutedoneafteranother.

C Programming

5.Coding&Implementation
Codingisaprocessofconvertingthealgorithmsolutionofflowchartintoacomputerprogram.Inthisprocess,each
andeverystepofalgorithmisconvertedtoinstructionsofselectedcomputerprogramminglanguage.
6.Debugging&Testing
Debugging:Beforeloadingtheprogramintothecomputer,wemustcorrectalltheerrors.Thisprocessiscalled
Debugging.
Therearethreetypesoferrors
1.Syntaxerrors
2.Runtimeerrors
3.Logicalerrors
Testing:Itisveryimportanttotesttheprogramwrittentoachieveaspecifictask.Testingisrunningtheprogramwith
knowndataandknownresult.
7.Documentation
Itisthemostimportantaspectofprogramming.Itisacontinuousprocessofkeepingcopyofallphasesofaprogram
development.

Algorithm

Astepbystepproceduretosolvethegivenproblemisknownasalgorithm.
Examples:
1. Findthesum,product,divisionofgiventwonumbers.
step1:Readtwonumbersa,b
step2:sum=a+b
step3:product=a*b
step4:division=a/b;
step5:printsum,product,division.
step6:stop.

C Programming

2. Findthemaximumvalueofgiventwonumbers.
step1:Readtwonumbersaandb
step2:max=a
step3:ifmax<bthenmax=b
step4:printmax
step5:stop(or)end

3. Findmaximumvalueofgiventhreenumbers.
step1:Readthreenumbersa,bandc
step2:max=a
step3:ifmax<bthenmax=b.
step4:ifmax<cthenmax=c.
step5:printmax
step6:stop(or)end.

4. Tocheckwhetherthegivennumberiseven(or)odd
step1:Readthenumbern
step2:ifn%2==0"printniseven"else"printnisodd"
step3:stop(or)end

5. Toprintnaturalnumbersfrom1togivennumber.
step1:Readthenumbern
step2:i=1
step3:printi
step4:i=i+1
step5:ifi<=nthengotostep3
step6:stop(or)end

C Programming

6. Tocalculatesumof'nnaturalnumbers.
step1:Readthenumbern
step2:i=1,sum=0
step3:sum=sum+i
step4:i=i+1
step5:ifi<=nthengotostep3
step6:printsum
step7:stop(or)end

7. Toprintfactorsofgivennumber.
step1:Readthenumbern
step2:i=1
step3:ifn%i==0thenprinti
step4:i=i+1
step5:ifi<=nthengotostep3
step6:stop(or)end.

8. Tocheckwhetherthegivennumberisprime(or)not.
step1:Readthenumbern
step2:i=1,c=0
step3:ifn%i==0thenc=c+1
step4:i=i+1
step5:ifi<=nthengotostep3
step6:ifc==2then"printnisprime"

else"nisnotprime"

step7:stop(or)end.

C Programming

9.Toprintfactorialofgivennumber
step1:Readthenumbern
step2:i=1,fact=1
step3:fact=fact*i
step4:i=i+1
step5:ifi<=nthengotostep3
step6:printfact
step7:stop(or)end

10.Toprintreversenumberofgivennumber
step1:Readthenumbern
step2:rev=0
step3:rev=rev*10+(n%10)
step4:n=n/10
step5:ifn>0thengotostep3
step6:printrev
step7:stop(or)end

11.Toprintsumofdigitsofgivennumber
step1:Readthenumbern
step2:sum=0
step3:sum=sum+(n%10)
step4:n=n/10
step5:ifn>0thegotostep3
step6:printsum
step7:stop(or)end

C Programming

12.Tocountnumberofdigitsinthegivennumber
step1:Readthenumbern
step2:nd=0
step3:nd=nd+1
step4:n=n/10
step5:ifn>0thegotostep3
step6:printnd
step7:stop(or)end

CLanguage

Cisaprogramminglanguage.ItisdesignedbyDennisRitchiein1972atAT&T(AmericanTelephonesand
telegraphs)BELLlabsinU.S.A.Itisthemostpopulargeneralpurposelanguage.
BriefHistoryofClanguage:
In1960'sCOBOLwasbeingusedforCommercialpurposeandFORTRANisusedforscientificandEngineering
applications.Atthisstagepeoplestartedtodevelopalanguagewhichissuitableforallpossibleapplications.There
foreAnInternationalCommitteewassetuptodevelopsuchalanguageALGOL60Wasreleased.Itwasnotpopular
becauseitseemedtoogeneral.ToreducethesegeneralityanewlanguagecalledCPL(Combinedprogramming
Language)wasdevelopedatCambridgeUniversity.Thensomeotherfeatureareaddedtothislanguageandanew
languagecalledBCPLdevelopedbyMartinRitchardsatCambridgeUniversity.ThenBlanguagewasdevolopedbyKen
ThompsonatAT&TBelllabs.DennisRitchieinheritedthefeaturesofBandBCPLandaddedhisownfeaturesand
developedCLanguagein1972.
1.Computerconcepts.
2.Introductionto'c'.
3.'c'tokens.
4.Controlstatements.
5.Nestedloops
6.Formattingtheoutput,patterns
7.Functions,storageclasses,recursivefunction
8.math.hfunctions
9.Arrays.

C Programming

10.Strings.
11.Pointers,Dynamicmemoryallocation.
12.Structures,unions,bitfields.
13.Files.
FeaturesofClanguage:
1.

Cisastructureprogramminglanguagewithfundamentalflowcontrolconstruction.

2.

Cissimpleandversatilelanguage.

3.

ProgrammingwritteninCisefficientandfast.

4.

Chasonly32keywords.

5.

Chasrichsetofoperators.

6.

Cpermitsalldataconversionsintoamixedmodeoperations.

7.

DynamicstorageallocationispossibleinClanguage.

8.

Extensivedatatypessuchasarrays,pointer,structuresandunionsareavailableinc

9.

Cimprovesbyitself,Ithasseveralbuiltinfunctionsandstandardfunctionsareavailable.

10.

Recursivefunctioncausesforalgorithmicapproachispossibleinc.

11. MainlyweareusingtheClanguagetoimplementthesystemsoftware.Thosearecompilers,texteditors,
networkdriversanddatabaseutilityandfinallyoperatingsystem.
12. Ccompilercombinesthecapabilityofanassemblylevellanguagewiththefeaturesofhighlevellanguage.So
itiscalledasmiddlelevellanguage.
Imppoints:
1.Cisacasesensitiveprogramminglanguage.
2.Cstatementsareenteredinlowercaselettersonly.
3.Cisafunctionorientedprogramminglanguage.
AnyCprogramcontainsone(or)morefunctionsminimumonefunctioniscompulsorybythenamecalledmain().
EveryCstatementmustbeterminatedbysemicolonexceptpreprocessorsectionandfunctiondefinition.
AfunctionisrepresentedbyfunctionnamewithapairofParenthesis.
()parenthesis[]squarebraces{}curlybraces(or)flowerbraces<>Angularbraces

C Programming

BasicstructureofCprogram

[Documentsection]

Preprocessorsection

Linksection

[Globaldeclarationsection]

main()

[localdeclarationsection]

Statements;

[Subprocessingsection]

Userdefinedfunctions

(or)

Documentsection:
ADocumentsectionconsistasetofcommentlinesgivingthenameoftheprogram,authornameandsomeother
details.
PreprocessororLinkingsection:
Itprovidesinstructionstothecompilertolinkthefunctionsfromthesystemlibrary.
Globaldeclarationsection:
VariablesthatareusedinmorethanonefunctionarecalledasGlobalvariableswhicharedeclaredvariablesinthe
Globaldeclarationsection.
Mainfunctionsection:
EveryCprogrammusthaveonefunctioni.e.mainfunction.

C Programming

Thissectioncontainstwopartsnamely:
(1)Localdeclarationsection
(2)Statementspart.
(1)Thelocaldeclarationsectiondeclaresallthevariablesusedinstatements.
(2)Thestatementspartcontainsexecutableinstructions.
Thesetwopartsmustappearbetweentheopeningandclosedcurlybraces.Theprogramexecutionbeginsatthe
openingbraceandclosingatclosingbraces.
Subprogrammingsection
Itcontainsalltheuserdefinedfunctions.
Comments
Nonexecutablelinesintheprogramarecalledascommentlines.Theselinesareskippedbythecompiler.
/*Groupoflinescomment

*/

Singlelinecomment

(or)

//Singlelinecomment
#include:
Itisapreprocessorfileinclusiondirectiveanditisusedtoincludeheaderfiles.
#include"filename"
(or)
#include<filename>
Whenthefilenameisincludedwithindoublequotationmarks,thesearchforthefileismadefirstincurrentdirectory
andthenthestandarddirectory.
WhenthefilenameisincludedwithinAngularbraces,thefileissearchonlyinstandarddirectory.
stdio.hStandardinputandoutputheaderfile
conio.hConsoleinputandoutputheaderfile

C Programming

1)Open'c'editor
a)Doubleclickondesktopc++icon.
b)Start>run>c:\tc\bin\tc.exe
c)Selectmycomputer>c>tc>bin>tc
2)Openfilemenu

pressalt+f>selectnew

fullscreenf5

3)type'c'program
4)save'c'program(.c)

pressalt+f>selectsave

5)compile

pressalt+c>selectcompile

6)run

pressalt+r>selectrun

7)output

Pressalt+w>selectuserscreen

8)quit

pressalt+f>selectquit

Shortcuts:
savef2
fullscreenf5
compilealt+f9
runctrl+f9
outputalt+f5
quitalt+x
tocloseafilealt+f3

C Programming

printf<stdio.h><conio.h>
Itisfunction,whichisusedtoprintdataonthescreen.
Declaration
intprintf("contolstring"[,arg1,arg2,argn]);

formatstring

eg
printf("welcometoclanguage");
//thisisfirstprogram
#include<stdio.h>
#include<conio.h>
voidmain()
{

printf("sachin_aswin");

}
clrscr<conio.h>
Itisafunction,itclearstextmodewindow.
Declaration
voidclrscr();
eg
clrscr();
getch<conio.h>
Itisafunction,toshowtheoutputdirectlywithoutpressingalt+f5.
Declaration
intgetch();
eg
getch()

C Programming

#include<stdio.h>
#include<conio.h>
voidmain()
{

clrscr();

printf("sachin_aswin");

getch();

}
Escapesequencecharacters:
\nnewline
\thorizontaltab(default8spaces)
\bbackspace
\vverticaltab(default1line)
\rcarriagereturn
\abeepsound

#include<stdio.h>
#include<conio.h>
voidmain()
{

clrscr();

printf("sachin\n");

printf("powerstar\naswin");

getch();

C Programming

CTokens

Thesmallestindividualelements(or)unitsusedinaprogramarecalledastokens.
Chasfollowingtokens
1.Identifiers
2.Keywords
3.Constants
4.Operators
5.Specialcharacters
1.Identifiers:
Thesecanbedefinedasnameofthevariables,arrays,functionsandsomeotherprogramelementsusingthe
combinationofthefollowingcharacters.
AlphabetsAtoZ

atoz

Digits0to9
Underscore.
Thefirstcharacterofanidentifierwillbeanalphabet(or)underscorefollowedbyalphabet,digit(or)underscore.
NOTE
Defaultidentifierlengthis32characters.
2. Keywords
KeywordsarethewordswhosemeaninghasalreadybeingexplainedintheCompiler.Thatmeansatthedesigninga
languagesomewordsarereservedtodospecifictaskssuchwordsarecalledaskeywords(or)reservedwords.Chas
32keywords.
1.auto2.break3.case4.char
5.const6.continue7.default8.do
9.double10.else11.enum12.extern
13.float14.far15.for16.goto
17.if18.int19.long20.register
21.return22.short23.signed24.sizeof

C Programming

25.struct26.static27.switch28.typedef
29.union30.unsigned31.void32.while
3. Constants
Theyrefertofixedvaluesthatdonotchangeduringtheexecutionofaprogram.Thefollowingconstantsareavailabe
inC.
(i)Integerconstants
(ii)Realconstants(float,double,longdouble)
(iii)Characterconstants
(iv)Stringconstants.
4. Operators
Itisasymbolwhichperformsaparticularoperation.ChasrichsetofOperators.
Coperatorscanbeclassifiedintothefollowingtypes:
1.Arithmeticoperators
2.Relationaloperators
3.Logicaloperators
4.Bitwiseoperators
5.Incrementanddecrementoperators.
6.Assignmentoperators
7.Specialoperators
(i)ternary(or)conditionaloperator
(ii)commaoperator
(iii)sizeofoperator
5. Specialcharacters
Allcharactersotherthanalphabets,digitsandunderscorearetreatedasspecialcharacters.
eg
<,>,&,{etc

C Programming

DATATYPES:
Akindofdatathatvariablesmayholdinaprogramminglanguageiscalleddatatype.
Chas3typesofdatatypes.
1.Primarydatatypes(or)primitive(or)predefined
2.Userdefineddatatypes
3.Deriveddatatypes
1.Primarydatatypes
AllCcompilerssupport4fundamentaldatatypesnamelyint,char,floatanddouble.
(i)

int

Itisa+ve,veandwholevaluesbutnotadecimalnumber.
eg
10,30,34,0,etc....
(ii)

char

Asinglecharactercanbedefinedasacharacterdatatypeanditcanberepresentedwithinsinglequotationmarks.
eg
'S','A','1','*'etc....
(iii)

String

Itisalsoacharacterdatatypeanditcanbedefinedwithindoublequotationmarks.
eg
"BDPS","WELCOME","12345",etc.....
(iv)

float(valuewithdecimalpoint

Thenumberswhicharestoredintheformoffloatingpointrepresentationiscalledfloatdatatype.
eg
10.423,234.33,etc....
(v)double
Theno'swhicharestoredintheformofdoubleprecisionfloatingpointrepresentationisknownasdoubledatatype.
eg

C Programming

10.423,234.33,232242.34434,22154.5455,etc.....
2.UserDefineddatatypes
Theuserdefineddatatypesenablesaprogrammertoinventhisowndatatypesanddefinewhatvaluesitcantakeon.
Thisdatatypecanhelpaprogrammertoreducingtheprogrammingerrors.
Therearetwotypesofuserdefineddatatypesnamely
1.enum(enumerateddatatype)
2.typedef(typedefinition)
3.Deriveddatatypes
Theyarebuiltfromthebasicfundamentaldatatypes.Theexamplesofderiveddatatypesarearrays,pointers,
structuresetc...

NOTE

voidisanemptydatatype

Datatypes,Formatspecifiers,Memorysizesandtheiraccessibilityranges
datatypeformatspecifiermemorysizeaccessibilityrange
1.unsignedchar%c1byte0to255
2.char%c1byte128to+127
3.int%d2bytes32,768to32,767
4.unsignedint%u2bytes0to65,535
5.longint%ld4bytes214,74,83,647to214,74,83,647
6.unsignedlongint%lu4bytes0to429,49,67,295
7.float%f4bytes3.4*10to3.4*10

8.double%lf8bytes1.7*10to1.7*10
9.longdouble%Lf10bytes3.4*10to+49321.1*10
10.char[](string)%s

C Programming

%ooctalbase
%xhexadecimalbase
varaiable
Aquantitywhichmayvaryduringtheexecutionofaprogramisknownasvariable.
Declarationofavariable
Form1:datatypeidentifier;
eg
intn;
charch;
floatft;
Form2:datatypeidentifier1,identifier2identifiern;
eg
inta,b,c;
charch1,ch2;
Initialisation:AtthetimeofdeclaringavariablewecanprovidesomedataintothatVariableisknownasinitialisation.
Declaration
datatypeidentifier=value;
eg
inta=100;
charch='s';
datatypeidentifier1=value,identifier2=value,identifiern=value;
eg
inta=100,b=200,c=300;
charch1='a',ch2='k';

C Programming

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn=100;

clrscr();

printf("Valueofn=%d",n);

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

charch='s';

intn=100;

floatft=123.90;

doubledb=12345.890;

clrscr();

printf("Character=%c",ch);

printf("\nValueofn=%d",n);

printf("\nFloatvalue=%f",ft);

printf("\nDoublevalue=%lf",db);

getch();

C Programming

Constants
Constantsrefertofixedvaluesthatdonotchangeduringtheexecutionofaprogram.
Const:Itisakeyword,andisusedtodefineconstants.
Syntax:constdatatypeidentifier=value;
eg
constintn=100;
#include<stdio.h>
#include<conio.h>
voidmain()
{

constinta=100;

clrscr();

printf("Valueofa=%d",a);

//a=200;cannotmodify

printf("\nValueofa=%d",a);

getch();

scanf
Itisafunction,whichisusedtoreaddatafromkeyboard.
Declaration
intscanf("format(s)",address1,address2,addressn);
eg
intn=scanf("%d",&n)&nisaddressofn
charch=&chAddressofch

C Programming

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Valueofn=%d",n);

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

charch;

intn;

floatft;

doubledb;

clrscr();

printf("Enteranycharacter:");

scanf("%c",&ch);

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Enteranyfloatvalue:");

scanf("%f",&ft);

C Programming

printf("Enteranydoublevalue:");

scanf("%lf",&db);

printf("Givencharacter=%c",ch);

printf("\nGivenintegervalue=%d",n);

printf("\nFloatvalue=%.2f",ft);

printf("\nDoublevalue=%.2lf",db);

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

charch;

intn;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Enteranycharacter:");

scanf("%c",&ch);

printf("\nGivenintegervalue=%d",n);

printf("\nGivencharacter=%c",ch);

getch();

C Programming

fflush
Itflushesspecifiedstream.
Declaration:intfflush(FILE*stream);
flushall
Itflushesallopenstreams.
Declaration:intflushall();

#include<stdio.h>
#include<conio.h>
voidmain()
{

charch;

intn;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Enteranycharacter:");

fflush(stdin);

//flushall();

scanf("%c",&ch);

printf("\nGivenintegervalue=%d",n);

printf("\nGivencharacter=%c",ch);

getch();

#include<stdio.h>
#include<conio.h>

C Programming

voidmain()
{

charch;

clrscr();

printf("Enteranycharacter:");

scanf("%c",&ch);

printf("Asciivalueofgivencharacter=%d",ch);

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn;

clrscr();

printf("Enteranyasciivalue(0to255):");

scanf("%d",&n);

printf("Characterofgivenasciivalue=%c",n);

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn;

C Programming

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Givennumber=%d",n);

printf("\nOctalnumber=%o",n);

printf("\nHexadecimalnumber=%x",n);

getch();

String
Agroupofcharacterscanbedefinedbetweendoublequotationmarksisastring.In'c'languageastringisnothingbut
anarrayofcharactersandterminatedbyanullcharacter(\0)
Declaration:charidentifier[size];
Eg
charst[20];
Initialisation:charidentifier[size]="string";
eg
charst[20]="welcome";

Whenthecompilerassignsacharacterstringtoacharacterarraythenitautomaticallysuppliesanullcharacteratthe
endofthestring.Thereforethesizeshouldbeequaltothemaximumnumberofcharactersinthegivenstring+1.
Formatspecifierofstringis%s

#include<stdio.h>
#include<conio.h>
voidmain()
{

charst[80];

C Programming

clrscr();

printf("Intialisedstring=%s",st);

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

charst[80];

clrscr();

printf("Enteranystring:");

scanf("%s",st);

printf("Givenstring=%s",st);

getch();

gets
Itisafunctionwhichisusedtoreadastringwithblankspacesfromkeyboardintoastringvariable.
syntax
char*gets(stringvariable);
eg
charst[80];
gets(st);

#include<stdio.h>
#include<conio.h>

C Programming

voidmain()
{

charst[80];

clrscr();

printf("Enteranystring:");

gets(st);

printf("Givenstring=%s",st);

getch();

OPERATORS

Operator
Itisasymbolwhichperformsaparticularoperation.
Operand:
Itisanentityonwhichanoperatoracts.
Unaryoperator:
Itrequiressingleoperand.
Binaryoperator:
Itrequirestwooperands.
'c'operatorscanbeclassifiedintonumberofcategories.

1.Arithmeticoperators
2.Logicaloperators
3.Relationaloperators
4.Assignmentoperators
5.Incrementanddecrementoperators

C Programming

6.Bitwiseoperators
7.Specialoperators

(a)ternaryoperator(or)conditionaloperator

(b)commaoperator

(c)sizeofoperator

1. Arthemeticoperators
Thesearebasicoperatorsin'c'language.Theseoperatorsusedforarithmeticoperation.
+Addition
Subtraction
*Multiplication
/Division
%modulas

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta,b;

clrscr();

printf("Enteranytwointegervalues:");

scanf("%d%d",&a,&b);

printf("Additionof%dand%dis%d",a,b,a+b);

printf("\nSubtractionof%dand%dis%d",a,b,ab);

printf("\nMultiplicationof%dand%dis%d",a,b,a*b);

printf("\nDivisionof%dnad%dis%d",a,b,a/b);

printf("\nModulasof%dand%dis%d",a,b,a%b)

C Programming

getch();

2. logicaloperators
Theseoperatorsareusedforcombinetheresultoftwoormoreexpressions.
(i)
(ii)
(iii)

logicalAND&&
logicalOR||
logicalNOT!

EXP1EXP2EXP1&&EXP2EXP1||EXP2

TRUETRUETRUETRUE
TRUEFALSEFALSETRUE
FALSETRUEFALSETRUE
FALSEFALSEFALSEFALSE

ExpTRUE!ExpFALSE
Expfalse!Exptrue
3. Relationaloperators
Theseoperatorsareusedtotesttherelationbetweentwovalues(or)twovariables(or)twoexpressions.
All'c'relationaloperatorsarebinaryoperatorsandhencerequirestwooperands.
<lessthan
>greatertham
<=lessthanorequalto
>=greaterthanorequalto
==equalto
!=notequalto

C Programming

4. Assignmentoperators
Theseoperatorsareusedtoassignavalueofanexpressiontoanidentifier.
=Assignmentoperator

Compoundassignmentoperators(or)shorthandoperators
+=
=
*=
/=
%=
eg
intn=10;
n=n+10;<=>n+=10;

5. Incrementanddecrementoperators
Theseoperatorsareusedtocontroltheloopsinaneffectivemethod.
Incrementoperator(++)
Thesymbol++isusedforincrementingby1.
++identifier:prefixincrement
identifier++:postfixincrement

Decrementoperator():
Thesymbolisusedfordecrementingby1
identifier:prefixdecrement
identifier:postfixdecrement
decrementoperator
Thesymbolisusedfordecrementingby1.

C Programming

identifier:prefixdecrement
identifier:postfixdecrement

6. Bitwiseoperators:
Theseoperatorsareusedforcalculatingdataatbitlevel.Bitwiseoperatorsaretwotypes
(i)
(ii)

bitwiselogicaloperators
bitwiseshiftoperators

(i).bitwiselogicaloperators:
Theseoperatorsareusedforthebitwiselogicaldecisionmaking.
(i)
(ii)
(iii)

bitwiseAND&
bitwiseOR|
bitwiseexclusiveOR^

B1B2B1&B2B1|B2B1^B2
11110
10011
01011
00000

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta=5,b=6;

clrscr();

printf("a&b=%d",a&b);

printf("\na|b=%d",a|b);

printf("\na^b=%d",a^b);

getch();

C Programming

(ii).Bitwiseshiftoperators
Theshiftoperatorstakebinarypatternsandshiftbitstoleft(or)right.
(i)
(ii)

leftshiftoperator<<
rightshiftoperator>>

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta=4,b,c;

clrscr();

b=a<<2;

c=a>>1;

printf("\na=%d",a);

printf("\nb=%d",b);

printf("\nc=%d",c);

getch();

}
7. Specialoperators:
(a)ternaryoperator(or)conditionaloperator
Aternaryoperatorpair"?:"isavailablein'c'language.Itisusedtoconstructconditionalexpression.
Thegeneralformofternaryoperatoris
exp1?exp2:exp3;
Whereexp1,exp2,exp3areexpressions.
Ifexp1istruethenexp2isevaluatedanditsvaluebecomesvalueoftheexpression.
Otherwiseifexp1isfalsethenexp3isevaluatedanditsvaluebecomesvalueoftheexpression.
eg
inta=10,b=20,c;

C Programming

c=a>b?a:b;
a10b20c20
Writeaprogramtoacceptanytwointegervaluesanddisplaymaximumandminimumvaluesusingternaryoperator.

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta,b,max,min;

clrscr();

printf("Enteranytwointegervalues:");

scanf("%d%d",&a,&b);

max=a>b?a:b;

min=a<b?a:b;

printf("Maximumvalue=%d",max);

printf("\nMinimumvalue=%d",min);

getch();

Writeaprogramtoacceptanythreeintegervaluesanddisplaymaximumandminimumvaluesusingternaryoperator.
#include<stdio.h>
#include<conio.h>
voidmain()
{

inta,b,c,max,min;

clrscr();

printf("Enteranythreeintegervalues:");

C Programming

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

max=a>b?a:b;

max=max>c?max:c;

min=a<b?a:b;

min=min<c?min:c;

printf("Maximumvalue=%d",max);

printf("\nMinimumvalue=%d",min);

getch();

Writeaprogramtoacceptanyintegervalueandcheckwhetherthegivennumberiseven(or)oddusingternary
operator
#include<stdio.h>
#include<conio.h>
voidmain()
{
intn;
clrscr();
printf("Enteranyintegervalue:");
scanf("%d",&n);
n%2==0?printf("GivennumberisEven"):printf("GivennumberisOdd");
getch();
}

(iii)

commaoperator:

Acommaoperatorcanbeusedtolinktherelatedexpressionstogether.
Thegeneralformofcommaoperatoris

C Programming

identifier=(identifier1=value,identifier2=value

identifiern=value,expression);

eg
inta,b,c;
c=(a=10,b=20,a+b);
Firstassignsthevalue10to'a'andthenassignsthevalue20to'b'
andfinallyassigns30(a+b)to'c'.

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta,b,c;

clrscr();

c=(a=10,b=20,a+b);

printf("\na=%d",a);

printf("\nb=%d",b);

printf("\nc=%d",c);

getch();

(c)sizeofoperator
Itisacompilingoperatorandisusedtogetthememorysizeofspecifieddatatype(or)variable(or)expression.
Syntax:sizeof(datatype(or)variable(or)expression);
eg
sizeof(int)2bytes
sizeof(char)1byte

C Programming

sizeof(float)4bytes.
eg2
intn
charch;
floatft;
sizeof(n)2bytes
sizeof(ch)1byte
sizeof(ft)4bytes
eg3
inta,b;
sizeof(a)2bytes
sizeof(b)2bytes
sizeof(a+b)2bytes

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn;

floatft;

clrscr();

printf("Sizeofintegervariable=%dbytes",sizeof(n));

printf("\nSizeoffloatvariable=%dbytes",sizeof(ft));

getch();

C Programming

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta,b;

clrscr();

printf("Sizeofa=%dbytes",sizeof(a));

printf("\nSizeofb=%dbytes",sizeof(b));

printf("\nSizeofa+b=%dbytes",sizeof(a+b));

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta,b,t;

clrscr();

printf("Enteranytwointegervalues:");

scanf("%d%d",&a,&b);

printf("Valuesbeforeswapping\n");

printf("a=%d",a);

printf("\nb=%d",b);

/*swapping*/

t=a;

C Programming

a=b;

b=t;

printf("\nValuesAfterswapping");

printf("\na=%d",a);

printf("\nb=%d",b);

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta,b;

clrscr();

printf("Enteranytwointegervalues:");

scanf("%d%d",&a,&b);

printf("Valuesbeforeswapping\n");

printf("a=%d",a);

printf("\nb=%d",b);

/*swapping*/

a=a+b;

b=ab;

a=ab;

printf("\nValuesAfterswapping");

printf("\na=%d",a);

printf("\nb=%d",b);

getch();}

C Programming

Compoundstatements
Acompoundstatementconsistoneormoreinstructionsandthoseinstructionsareenclosedwithincurlybraces.
1. Avariablewhichisdeclaredabovethecompoundstatementitisaccessiblebothinsideandoutsidecompound
statements.
2. Avariablewhichisdeclaredinsidethecompoundstatement,itisnotavailableoutsidethecompound
statement.

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn=100;

clrscr();

printf("\nOutercompoundstatement");

printf("\nn=%d",n);

intm=200;

printf("\nInnercompoundstatement");

printf("\nn=%d",n);

printf("\nm=%d",m);

printf("\nOutercompoundstatement");

printf("\nn=%d",n);

getch();

}
3. Avariableisdeclaredwiththesamenameinbothinnerandoutercompoundstatements.

#include<stdio.h>
#include<conio.h>

C Programming

voidmain()
{

intn=100;

clrscr();

printf("\nOutercompoundstatement");

printf("\nn=%d",n);

intn=200;

printf("\nInnercompoundstatement");

printf("\nn=%d",n);

printf("\nOutercompoundstatement");

printf("\nn=%d",n);

getch();

Typecasting
Theprocessofconvertingonedatatypetoanotherdataypeiscalledtypecasting.
In'c'languagetypeconversionisanarithmeticexpressionwillbedoneautomaticlly.Ifyouwanttostoreavalueof
onetypeintovariableofanothertypewemustcastthevaluewillbestoredbyprecedingitwiththetypenamein
paranthesis.
eg
inta,b;
floatc,d;
a5b2
c=a/b;automaticconversion(or)implicitconversion
c2.00
d=(float)a/b;explicitconversion(or)typecasting

C Programming

d2.50;

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta=5,b=2;

floatc,d;

clrscr();

c=a/b;

d=(float)a/b;

printf("c=%.2f",c);

printf("\nd=%.2f",d);

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

intcno,pmr,lmr,tu;

charcname[80];

floatbill;

clrscr();

printf("Enterconsumernumber:");

scanf("%d",&cno);

printf("Enterconsumername:");

C Programming

fflush(stdin);

gets(cname);

printf("Enterpresentmonthreading:");

scanf("%d",&pmr);

printf("Enterlastmonthreading:");

scanf("%d",&lmr);

tu=pmrlmr;

bill=tu*3.00;

printf("Totalunits=%d",tu);

printf("\nBillamount=%.2f",bill);

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

intsno,c,cpp,java,tot;

charsname[80];

floatavg;

clrscr();

printf("Enterstudentnumber:");

scanf("%d",&sno);

printf("Enterstudentname:");

fflush(stdin);

gets(sname);

printf("Entermarksinccppjava:");

C Programming

scanf("%d%d%d",&c,&cpp,&java);

tot=c+cpp+java;

avg=(float)tot/3;

printf("Totalmarks=%d",tot);

printf("\nAverage=%.2f",avg);

getch();

Controlstatements(or)controlstructures
'c'isaconsideredasastructureprogramminglanguage.oneofregionforthisishavingvariousprogramcontrol
structures.
'c'processthedecisionmakingcapabilitiesandsupportsthestatementsknownascontrolstatements.
Thereare3typesofcontrolstructures.
(1)Conditioncontrolstatements
(2)Unconditioncontrolstatements
(3)Loopcontrolstatements

(1) Conditioncontrolstatements
'c'supports5typesofconditioncontrolstatements.
(i)
(ii)
(iii)

simpleif
ifelse
nestedif

(iv)elseifladder
(iv)

switch

(i)

Simpleifstatement

Itisadecisionmakingstatementandisusedtocontroltheflowofexecution.
Syntax:
if(expression)

C Programming

statements;

}
Iftheexpressionistrue,thenthestatementblockwillbeexecutedandthecontroltransferstothenextstatement.
Otherwisetheexpressionisfalsethenthecontroldirectlygoesthenextstatement.

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta,b,max;

clrscr();

printf("Enteranytwointegervalues:");

scanf("%d%d",&a,&b);

max=a;

if(max<b)

printf("Maximumvalue=%d",max);

getch();

max=b;

Note:
Inanycontrolstatement,thestatementblockcontainsasinglestatementthebracesarenotnecessary.

C Programming

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta,b,c,max;

clrscr();

textmode(2);

printf("Enteranythreeintegervalues:");

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

max=a;

if(max<b)

if(max<c)

printf("Maximumvalue=%d",max);

getch();

max=b;

max=c;

#include<stdio.h>
#include<conio.h>
voidmain()
{

intd,m,y;

C Programming

clrscr();

printf("Enteranydate(ddmmyyyy):");

scanf("%d%d%d",&d,&m,&y);

printf("Givendate=%.2d%.2d%d",d,m,y);

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

intcd,cm,cy,bd,bm,by,y,m,d;

clrscr();

textmode(2);

printf("Entercurrentdate(ddmmyyyy):");

scanf("%d%d%d",&cd,&cm,&cy);

printf("EnterDateofbirth(ddmmyyyy):");

scanf("%d%d%d",&bd,&bm,&by);

y=cyby;

m=cmbm;

d=cdbd;

if(d<0)

d=d+30;

m=m1;

if(m<0)

C Programming

m=m+12;

y=y1;

printf("Ageis%dyears%dmonths%ddays",y,m,d);

getch();

(ii)

ifelsestatement:

Itisanextensionofsimpleifstatement.
Syntax
if(expression)
{

statement1;

}
else
{

statement2;

}
Iftheexpressionistruethenifblockstatementsareexecutedandelseblockstatementsareignored.
Otherwiseexpressionisfalsethenifblockstatementsareignoredandelseblockstatementsareexecuted.

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta,b,max;

C Programming

clrscr();

textmode(2);

printf("Enteranytwointegervalues:");

scanf("%d%d",&a,&b);

if(a>b)

else

printf("Maximumvalue=%d",max);

getch();

max=a;

max=b;

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

if(n%2==0)

printf("Givennumberiseven");

C Programming

else

getch();

printf("Givennumberisodd");

(iii)

Nesetdifstatement:

usingaifstatementwithinanotherifiscalledasnestedif.Ifaseriesofdecisionsareinvolved,weusenestedif.
Form1
if(expr1)
{

if(expr2)

if(exprn)

}
Form2:
if(expr1)
{

if(expr2)

statements;

C Programming

else

statement1;

statement2;

}
else
{

if(expr3)

else

statement3;

statement4;

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta,b,c,max;

clrscr();

printf("Enteranythreeintegervalues:");

C Programming

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

if(a>b)

if(a>c)

else

else

if(b>c)

else

printf("Maximumvalue=%d",max);

getch();

max=a;

max=c;

max=b;

max=c;

#include<stdio.h>
#include<conio.h>
voidmain()
{

intsno,c,cpp,java,tot;

charsname[80];

floatavg;

clrscr();

C Programming

printf("Enterstudentnumber:");

scanf("%d",&sno);

printf("Enterstudentname:");

fflush(stdin);

gets(sname);

printf("Entermarksinccppjava:");

scanf("%d%d%d",&c,&cpp,&java);

tot=c+cpp+java;

avg=(float)tot/3;

printf("\nTotalmarks=%d",tot);

printf("\nAverage=%.2f",avg);

if(c>=50&&cpp>=50&&java>=50)

printf("\nResult=PASS");

if(avg>=70)

else

else

printf("\nResult=Fail");

printf("\nDivision=No_Division");

getch();

printf("\nDivision=First");

printf("\nDivision=Second");

C Programming

(iv)

elseifladder:

Thisstatementisalsousedfortheseriesofdecisionsareinvolved.
Syntax
if(expr1)
{

statement1;

}
elseif(expr2)
{

statement2;

}
elseif(expr3)
{

statement3;

elseif(exprn)
{

statementn;

}
else
{

statements;

}
Inthisstatementexpressionsareevaluatedtoptobottom.Iftheconditionistruethestatementsassociatedthatblock
executedandcontroltransfertothenextstatement.

C Programming

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta,b,c,max;

clrscr();

printf("Enteranythreeintegervalues:");

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

if(a>b&&a>c)

elseif(b>c)

else

printf("Maximumvalue=%d",max);

getch();

max=a;

max=b;

max=c;

}
#include<stdio.h>
#include<conio.h>
voidmain()
{

C Programming

charch;

clrscr();

printf("Enteranycharacter:");

scanf("%c",&ch);

if((ch>=65&&ch<=90)||(ch>=97&&ch<=122))

elseif(ch>=48&&ch<=57)

else

getch();

printf("Givencharacterisalphabet");

printf("Givencharacterisdigit");

printf("Givencharacterisspecialcharacter");

#include<stdio.h>
#include<conio.h>
voidmain()
{

charch;

clrscr();

printf("Enteranycharacter:");

scanf("%c",&ch);

if((ch>=65&&ch<=90)||(ch>=97&&ch<=122))

if(ch=='A'||ch=='a'||ch=='E'||ch=='e'||ch=='O'||

ch=='o'||ch=='I'||ch=='i'||ch=='U'||ch=='u')

else

printf("Givencharacterisvowel");

C Programming

else

getch();

printf("Givencharacterisconsonent");

printf("Givencharacterisnotanalphabet");

/*
unitsrate/unit

0501.00
511002.00
1012003.00
2014004.00
400above5.00
*/
#include<stdio.h>
#include<conio.h>
voidmain()
{

intcno,pmr,lmr,tu;

charcname[80];

floatbill;

clrscr();

textmode(2);

printf("Enterconsumernumber:");

scanf("%d",&cno);

C Programming

printf("Enterconsumername:");

fflush(stdin);

gets(cname);

printf("Enterpresentmonthreading:");

scanf("%d",&pmr);

printf("Enterlastmonthreading:");

scanf("%d",&lmr);

tu=pmrlmr;

if(tu<=50)

elseif(tu<=100)

elseif(tu<=200)

elseif(tu<=400)

else

bill=tu*1.00;

bill=(50*1.00)+(tu50)*2.00;

bill=(50*1.00)+(50*2.00)+(tu100)*3.00;

bill=(50*1.00)+(50*2.00)+(100*3.00)+(tu200)*4.00;

bill=(50*1.00)+(50*2.00)+(100*3.00)+(200*4.00)+(tu400)*5.00;

printf("Totalunits=%d",tu);

printf("\nBillamount=%.2f",bill);

getch();

C Programming

#include<stdio.h>
#include<conio.h>
voidmain()
{

intm,y,nd;

clrscr();

printf("Entermonthandyear:");

scanf("%d%d",&m,&y);

if(m==2)

if((y%4==0&&y%100!=0)||(y%400==0))

else

elseif(m==1||m==3||m==5||m==7||m==8||m==10||m==12)

else

printf("Numberofdays=%d",nd);

getch();

nd=29;

nd=28;

nd=31;

nd=30;

exit<process.h>
Itterminatestheprogram.
Declaration:
voidexit(intstatus);

C Programming

eg
exit(0);
Typicallyavalueof0indicatesnormalexitandanonzerovalueindicatessomeerror.
#include<stdio.h>
#include<conio.h>
#include<process.h>
voidmain()
{

intcno,pmr,lmr,tu;

charcname[80];

floatbill;

clrscr();

printf("Enterconsumernumber:");

scanf("%d",&cno);

printf("Enterconsumername:");

fflush(stdin);

gets(cname);

printf("Enterpresentmonthreading:");

scanf("%d",&pmr);

printf("Enterlastmonthreading:");

scanf("%d",&lmr);

if(pmr<lmr)

printf("InvalidReading");

getch();

exit(0);

C Programming

tu=pmrlmr;

bill=tu*3.00;

printf("Totalunits=%d",tu);

printf("\nBillamount=%.2f",bill);

getch();

DregionsareNnorthSsouthWwestEeast

petroldieselkerosine

NORTH49.0034.0023.00
SOUTH48.0033.0021.00
EAST51.0032.0022.00
WEST52.0033.0023.00
*/
#include<stdio.h>
#include<conio.h>
#include<process.h>
voidmain()
{

intdno,np,nd,nk;

chardname[80],reg;

floatpamt,damt,kamt,tamt;

clrscr();

printf("Enterdealernumber:");

scanf("%d",&dno);

printf("Enterdealername:");

C Programming

fflush(stdin);

gets(dname);

printf("Enterdealerregion:");

scanf("%c",&reg);

if(reg>=97&&reg<=122)

if(reg!='N'&&reg!='S'&&reg!='E'&&reg!='W')

printf("Invalidregion");

getch();

exit(0);

printf("Enternumberoflitrespetrolsold:");

scanf("%d",&np);

printf("Enternumberoflitresdieselsold:");

scanf("%d",&nd);

printf("Enternumberoflitreskerosinesold:");

scanf("%d",&nk);

if(reg=='N')

pamt=np*49.00;

damt=nd*34.00;

kamt=nk*23.00;

elseif(reg=='S')

reg=reg32;

pamt=np*48.00;

C Programming

damt=nd*33.00;

kamt=nk*21.00;

elseif(reg=='E')

pamt=np*51.00;

damt=nd*32.00;

kamt=nk*22.00;

else

pamt=np*52.00;

damt=nd*33.00;

kamt=nk*23.00;

tamt=pamt+damt+kamt;

printf("\nPetrolAmount=%.2f",pamt);

printf("\nDieselAmount=%.2f",damt);

printf("\nKerosineAmount=%.2f",kamt);

printf("\nTotalAmount=%.2f",tamt);

getch();

C Programming

4. Switchstatement:
Itisamultiwayconditionalstatementusedin'c'language.Itismainlyusedinsituationwherethereisneedtopick1
alternativeamongmanyalternatives.
syntax
switch(exp(or)variable)
{

case1:

statement1;

break;

case2:

statement2;

break;

casen:

statementn;

break;

default:

defaultstatements;

}
Theswitchstatementteststhevalueofgivenvariableorexpressionagainstalistofcasevalues.andwhenamatchis
foundablockofstatementsassociatedthatcaseexecuted.Otherwisethedefaultblockstatementswillbeexecuted.
Break:
Itisunconditionalcontrolstatementandisusedtoterminateaswitchstatement.
syntax
break;
Note
1. Inswitchstatementthevariable(or)expressionisanintegralvalue.Wecannotpassstringandfloatvalues.
2. Inswitchstatementthedefaultblockisoptional.

C Programming

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta,b,opt;

clrscr();

printf("\nMENU");

printf("\n");

printf("\n1.Addition");

printf("\n2.Subtraction");

printf("\n3.Multiplication");

printf("\n4.Division");

printf("\n5.Modulas");

printf("\n");

printf("\nEnteranytwointegervalues:");

scanf("%d%d",&a,&b);

printf("Enteryouroption:");

scanf("%d",&opt);

switch(opt)

case1:

printf("Additionof%dand%dis%d",a,b,a+b);

break;

case2:

printf("Subtractionof%dand%dis%d",a,b,ab);

break;

case3:

C Programming

printf("Multiplicationof%dand%dis%d",a,b,a*b);

break;

case4:

printf("Divisionof%dand%dis%d",a,b,a/b);

break;

case5:

printf("Modulasof%dand%dis%d",a,b,a%b);

break;

default:

getch();

printf("Invalidoption");

2.Unconditionalcontrolstatements:
(i)break
Itpassescontrol
Syntax
break;
Thebreakstatementcausescontroltopasstothestatementfollowingtheinnermostenclosingwhile,do,for
statementsandswitchstatement.
(iii)

continue:

Passescontrol
Syntax
continue;
Itcausescontroltopasstotheendoftheinnermostenclosingwhile,do,forstatementatwhichpointtheloop
continuationconditionisreevaluated.

C Programming

(iv)

gotostatement:

Thegotostatementisanunconditionalcontrolstatementwhichisofftheexecutionprogramsequencebytransferof
controltosomeotherpartoftheprogram.
Syntax
gotolable;
wherelabelisvalid'c'identifierusedtolabelofthedestinationsuchthatthecontrolcouldtransferred.
syntaxoflable:
identifier:

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i=1;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Naturalnumbersfrom1to%d\n",n);

lb:

printf("%d\t",i);

i++;

if(i<=n)

getch();

gotolb;

C Programming

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

if(n==1)

if(n==2)

printf("welcome");

lb1:

lb2:

getch();

gotolb1;

gotolb2;

printf("\nLABEL1");

printf("\nLABEL2");

Indefaulttextmodethereis25rowsand80columns.

gotoxy<conio.h>
Itisafunctionwhichisusedtomovethecursortospecifiedlocationintextwindow.
Declaration:
voidgotoxy(intx,inty);

C Programming

Note:
Ifthecoordinatesareinvalid,thecalltogotoxyisignored.
#include<stdio.h>
#include<conio.h>
voidmain()
{

clrscr();

textmode(2);

gotoxy(10,5);

printf("WELCOME");

gotoxy(30,20);

printf("BDPS");

getch();

Writeaprogramtocalculatestudentresultbythefollowingformat

BDPSSOFTWARELIMITED

VIJAYAWADA

SNO:SNAME:

MARKSINC:

MARKSINCPP:

MARKSINUNIX:

TOTAL:AVERAGE:

RESULT:DIVISION

C Programming

*/
#include<stdio.h>
#include<conio.h>
voidmain()
{

intsno,c,cpp,java,tot;

charsname[80];

floatavg;

clrscr();

textmode(2);

gotoxy(25,4);

printf("");

gotoxy(30,5);

printf("BDPSSOFTWARELIMITED");

gotoxy(35,6);

printf("VIJAYAWADA");

gotoxy(25,7);

printf("");

gotoxy(25,8);

printf("SNO:");

gotoxy(45,8);

printf("SNAME:");

gotoxy(25,10);

printf("MARKSINC:");

gotoxy(25,12);

printf("MARKSINCPP:");

gotoxy(25,14);

C Programming

printf("MARKSINJAVA:");

gotoxy(25,16);

printf("TOTAL:");

gotoxy(45,16);

printf("AVERAGE:");

gotoxy(25,18);

printf("RESULT:");

gotoxy(45,18);

printf("DIVISION:");

gotoxy(31,8);

scanf("%d",&sno);

gotoxy(53,8);

fflush(stdin);

gets(sname);

lb1:

gotoxy(38,10);

scanf("%d",&c);

if(c<0||c>100)

gotoxy(35,22);

printf("INVALIDMARKS");

getch();

gotoxy(35,22);

printf("");

gotoxy(38,10);

printf("");

gotolb1;

C Programming

lb2:

gotoxy(40,12);

scanf("%d",&cpp);

if(cpp<0||cpp>100)

gotoxy(35,22);

printf("INVALIDMARKS");

getch();

gotoxy(35,22);

printf("");

gotoxy(40,12);

printf("");

gotolb2;

lb3:

gotoxy(41,14);

scanf("%d",&java);

if(java<0||java>100)

gotoxy(35,22);

printf("INVALIDMARKS");

getch();

gotoxy(35,22);

printf("");

gotoxy(41,14);

printf("");

C Programming

tot=c+cpp+java;

avg=(float)tot/3;

gotoxy(33,16);

printf("%d",tot);

gotoxy(55,16);

printf("%.2f",avg);

if(c>=50&&cpp>=50&&java>=50)

gotoxy(34,18);

printf("pass");

gotoxy(56,18);

if(avg>=70)

else

else

gotoxy(34,18);

printf("Fail");

gotoxy(56,18);

printf("No_DIVISION");

getch();

gotolb3;

printf("First");

printf("Second");

C Programming

3. loopcontrolstatements
Loop:
Theprocessofrepeatedlyexecutingablockofstatementscalledloop.
'c'supports3typesofloopcontrolstatements.
1.whileloop
2.dowhileloop
3.forloop.
Anyloophas3things
(i)
(ii)
(iii)

Initialisetheindex.
Testcondition.
Updatetheindex.

1Whileloop:
Itisaconditionalcontrolledloopstatementin'c'language.
Syntax
while(testcondition)
{

statements;

}
Firstthetestconditionisevaluated,andifitistruethenthestatementblockwillbeexecuted.
Aftertheexecutionofstatements,thetestconditionisevaluatedonceagainthenifitistruethestatementblockwill
beexecutedonceagain.
Theprocessofrepeatedexecutioncontinuousuntilthetestconditionfinallybecomesfalse.

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i=1;

clrscr();

C Programming

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Naturalnumbersfrom1to%d\n",n);

while(i<=n)

printf("%d\t",i);

i++;

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Naturalnumbersfrom%dto1\n",n);

i=n;

while(i>=1)

printf("%d\t",i);

i;

getch();

C Programming

}
#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Evennumbersfrom1to%d\n",n);

i=1;

while(i<=n)

if(i%2==0)

i++;

printf("\nOddnumbersfrom1to%d\n",n);

i=1;

while(i<=n)

if(i%2==1)

printf("%d\t",i);

printf("%d\t",i);

C Programming

getch();

i++;

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i=1;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Factorsof%d\n",n);

while(i<=n)

if(n%i==0)

i++;

getch();

#include<stdio.h>
#include<conio.h>

printf("%d\t",i);

C Programming

voidmain()
{

intn,i=1;

unsignedlongfact=1;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

while(i<=n)

fact=fact*i;

i++;

printf("Factorialofgivennumber=%lu",fact);

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i=1,c=0;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

while(i<=n)

if(n%i==0)

C Programming

i++;

if(c==2)

else

getch();

c++;

printf("Givennumberisprime");

printf("Givennumberisnotprime");

}
#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i=1,sum=0;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

while(i<=n/2)

if(n%i==0)

i++;

if(n==sum)

else

sum=sum+i;

printf("Givennumberisperfect");

printf("Givennumberisnotperfect");

C Programming

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn;

unsignedlongrev=0;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

while(n>0)

rev=rev*10+(n%10);

n=n/10;

printf("Reversenumber=%lu",rev);

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,m;

unsignedlongrev=0;

C Programming

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

m=n;

while(m>0)

rev=rev*10+(m%10);

m=m/10;

if(n==rev)

else

getch();

printf("Givennumberispallindrome");

printf("Givennumberisnotpallindrome");

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,sum=0,r,m;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

m=n;

while(m>0)

C Programming

r=m%10;

sum=sum+(r*r*r);

m=m/10;

if(sum==n)

else

getch();

printf("Givennumberisarmstrong");

printf("Givennumberisnotarmstrong");

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,sum=0;

clrscr();

textmode(2);

printf("Enteranyintegervalue:");

scanf("%d",&n);

while(n>0)

sum=sum+(n%10);

n=n/10;

printf("Sumofdigitsofgivennumber=%d",sum);

getch();

C Programming

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,sum;

clrscr();

textmode(2);

printf("Enteranyintegervalue:");

scanf("%d",&n);

sum=n%9;

if(sum==0)

else

getch();

printf("Finalsumis9");

printf("Finalsum=%d",sum);

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,pos,i=1,dg;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

C Programming

printf("Enterspecifiedposition:");

scanf("%d",&pos);

while(i<pos)

n=n/10;

i++;

dg=n%10;

printf("Specifiedpositionvalue=%d",dg);

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta,b,min,i=1,gcd;

clrscr();

printf("Enteranytwointegervalues:");

scanf("%d%d",&a,&b);

min=a<b?a:b;

while(i<=min)

if(a%i==0&&b%i==0)

gcd=i;

C Programming

printf("GCDof%dand%dis%d",a,b,gcd);

getch();

i++;

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta,b,lcm;

clrscr();

printf("Enteranytwointegervalues:");

scanf("%d%d",&a,&b);

lcm=a>b?a:b;

while(1)

if(lcm%a==0&&lcm%b==0)

lcm++;

printf("LCMof%dand%dis%d",a,b,lcm);

getch();

#include<stdio.h>
#include<conio.h>

break;

C Programming

voidmain()
{

inti=1;

clrscr();

while(i<=5)

printf("%d\t",i);

i++;

if(i==3)

getch();

break;

#include<stdio.h>
#include<conio.h>
voidmain()
{

inti=0;

clrscr();

while(i<10)

i++;

if(i==4||i==5||i==6)

printf("%d\t",i);

continue;

C Programming

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Evennumbersfrom1to%d\n",n);

i=0;

while(i<n)

i++;

if(i%2==1)

printf("%d\t",i);

printf("\nOddnumbersfrom1to%d\n",n);

i=0;

while(i<n)

i++;

if(i%2==0)

continue;

continue;

C Programming

getch();

printf("%d\t",i);

2dowhileloop
Itisanalternativeformofwhileloop.Onlydifferencebetweenwhileanddowhileisminimumnumberofexecutionof
whileis0minimumnumberifexecutionofdowhileis1.
Syntax:
do
{

statements;

}while(testcondition);
Firstthestatementblockwillbeexecutedandthentestconditionwillbeevaluated.Ifitistruethenthestatement
blockwillbeexecutedonceagain.Theprocessofrepeatedexecutioncontinuousuntilthetestconditionfinally
becomesfalse.

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i=1;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Naturalnumbersfrom1to%d\n",n);

do

printf("%d\t",i);

C Programming

}while(i<=n);

getch();

i++;

4. forloop:
Itisthemostcommonlyusedloopstatementin'c'language.Itconsistsof3expressions.
syntax

for(exp1;exp2;exp3)
{

statements;

}
Thefirstexpressionisusedtoinitialisetheindex.Thesecondexpressionisusedtocheckwhetherthelooptobe
continued(or)not.
Thethirdexpressionisusedtochangetheindexforfurtheriteration(increment(or)decrement).

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Naturalnumbersfrom1to%d\n",n);

for(i=1;i<=n;i++)

C Programming

getch();

printf("%d\t",i);

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn;

unsignedlongrev;

clrscr();

textmode(2);

printf("Enteranyintegervalue:");

scanf("%d",&n);

for(rev=0;n>0;n=n/10)

printf("Reversenumber=%lu",rev);

getch();

rev=rev*10+(n%10);

#include<stdio.h>
#include<conio.h>
voidmain()
{

C Programming

intn,t1=0,t2=1,t,i;

clrscr();

printf("Enternumberofterms:");

scanf("%d",&n);

printf("Fibbonacciseries\n");

printf("%d\t%d",t1,t2);

for(i=1;i<=n2;i++)

t=t1+t2;

printf("\t%d",t);

t1=t2;

t2=t;

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

for(i=1;i<=20;i++)

printf("\n%d*%d=%d",n,i,n*i);

C Programming

getch();

Textcolor:
textcolorselectsanewcharactercolorintextmode
Declaration:
voidtextcolor(intnewcolor);
textbackground
textbackgroundselectsanewtextbackgroundcolor
Declaration:
voidtextbackground(intnewcolor);
Textmode
Changesscreenmode(intextmode)
Declaration:
voidtextmode(intnewmode);
eg
textmode(2);25rows80columns.
textmode(1);25rows40columns.

COLORS(textmode)
BackFore
ConstantValuegrnd?grnd?

BLACK0YesYes
BLUE1YesYes
GREEN2YesYes

C Programming

CYAN3YesYes
RED4YesYes
MAGENTA5YesYes
BROWN6YesYes
LIGHTGRAY7YesYes
DARKGRAY8NoYes
LIGHTBLUE9NoYes
LIGHTGREEN10NoYes
LIGHTCYAN11NoYes
LIGHTRED12NoYes
LIGHTMAGENTA13NoYes
YELLOW14NoYes
WHITE15NoYes

BLINK128No***

***Todisplayblinkingcharactersintextmode,addBLINKtotheforegroundcolor.(DefinedinCONIO.H.)
cprintf:
Itissameasprintfandisusedtoapplycolorsintextmode.

#include<stdio.h>
#include<conio.h>
voidmain()
{

clrscr();

textmode(2);

textbackground(4);

C Programming

textcolor(14+128);

cprintf("Welcome");

getch();

delay<dos.h>
Suspendsexecutionforinterval(milliseconds)
Declaration:
voiddelay(unsignedmilliseconds);
_setcursortype
Selectscursorappearance
Declaration:
void_setcursortype(intcur_t);
Remarks
Setsthecursortypetooneofthefollowing:
_NOCURSOR0(turnsoffthecursor)
_SOLIDCURSOR1(solidblockcursor)
_NORMALCURSOR2(normalunderscorecursor)

kbhit
Checksforcurrentlyavailablekeystrokes
Declaration
intkbhit(void);

#include<stdio.h>
#include<conio.h>
#include<dos.h>

C Programming

voidmain()
{

intc1=1,c2=75,r1=1,r2=25;

clrscr();

textmode(2);

while(!kbhit())

_setcursortype(0);

clrscr();

gotoxy(c1,12);

printf("LITTLE");

gotoxy(c2,12);

printf("MASTER");

gotoxy(37,r1);

printf("SACHIN");

gotoxy(35,r2);

printf("POWERSTAR");

c1++;

c2;

r1++;

r2;

delay(100);

if(c1>75)

c1=1;

c2=75;

C Programming

if(r1>25)

r1=1;

r2=25;

Nestedloops:
Usingaloopstatementwithinanotherloopiscalledasnestedloop.

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,m,i;

unsignedlongrev;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Pallindromenumbersfrom1to%d\n",n);

for(i=1;i<=n;i++)

m=i;

rev=0;

while(m>0)

C Programming

rev=rev*10+(m%10);

m=m/10;

if(rev==i)

getch();

printf("%d\t",i);

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,sum,r,m,i;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Armstrongnumbersfrom1to%d\n",n);

for(i=1;i<=n;i++)

m=i;

sum=0;

while(m>0)

r=m%10;

sum=sum+(r*r*r);

m=m/10;

C Programming

if(sum==i)

getch();

printf("%d\t",i);

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i,j,c;

clrscr();

textmode(2);

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Primenumbersform1to%d\n",n);

for(i=1;i<=n;i++)

c=0;

for(j=1;j<=i;j++)

if(i%j==0)

if(c==2)

c++;

printf("%d\t",i);

C Programming

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i,j,sum;

clrscr();

textmode(2);

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Perfectnumbersfrom1to%d\n",n);

for(i=1;i<=n;i++)

sum=0;

for(j=1;j<=i/2;j++)

if(i%j==0)

if(sum==i)

getch();

sum=sum+j;

printf("%d\t",i);

C Programming

/*
w
we
wel
welc
welco
welcom
welcome
*/

#include<stdio.h>
#include<conio.h>
voidmain()
{

charst[10]="welcome";

inti;

clrscr();

for(i=1;i<=7;i++)

getch();

/*

printf("\n%.*s",i,st);

C Programming

writeaprogramtogeneratethefollowingpattern.
n=5
*****
*****
*****
*****
*****

*/
#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i,j;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

printf("\n");

getch();

printf("%3c",'*');

C Programming

/*
Writeaprogramtogeneratethefollowingpattern.
n=5
*
**
***
****
*****

*/
#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i,j;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

for(i=1;i<=n;i++)

for(j=1;j<=i;j++)

printf("\n");

getch();

printf("%3c",'*');

C Programming

/*

writeaprogramtogeneratethefollowingpattern.
n=5

1
22
333
4444
55555

*/

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i,j;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

for(i=1;i<=n;i++)

for(j=1;j<=i;j++)

C Programming

printf("\n");

getch();

printf("%3d",i);

}
12
123
1234
12345
*/
#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i,j;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

for(i=1;i<=n;i++)

for(j=1;j<=i;j++)

printf("\n");

printf("%3d",j);

C Programming

getch();

/*
Writeaprogramtogeneratethefollowingpattern.
n=5
*
**
***
****
*****
*/
#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i,j,s;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

s=n*2;

for(i=1;i<=n;i++)

printf("%*c",s,32);

for(j=1;j<=i;j++)

printf("%4c",'*');

C Programming

printf("\n");

s=s2;

getch();

/*
Writeaprogramtogeneratethefollowingpattern.
n=5
*
**
***
****
*****
****
***
**
*
*/
#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i,j,s,k=1;

clrscr();

printf("Enteranyintegervalue:");

C Programming

scanf("%d",&n);

s=n*2;

for(i=1;i<n*2;i++)

printf("%*c",s,32);

for(j=1;j<=k;j++)

printf("\n");

if(i<n)

k++;

s=s2;

else

k;

s=s+2;

getch();

}
/*

n=5
12345

printf("%4c",'*');

C Programming

51234
54123
54312
54321

*/
#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i,j,m;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

m=n;

for(i=1;i<=n;i++)

for(j=n;j>m;j)

for(j=1;j<=m;j++)

m;

printf("\n");

printf("%d\t",j);

printf("%d\t",j);

C Programming

getch();

}
/*
n=5
12345
109876
1112131415
2019181716
2122232425
*/

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn,i,j,k=1;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

printf("%d\t",k);

if(j<n)

C Programming

if(i%2==0)

else

k=k+n;

printf("\n");

getch();

}
/*
ABCDEFGFEDCBA
ABCDEFFEDCBA
ABCDEEDCBA
ABCDDCBA
ABCCBA
ABBA
AA
*/

#include<stdio.h>
#include<conio.h>
voidmain()
{

inti,j,p,x=7,y=7;

clrscr();

k;

k++;

C Programming

for(i=1;i<=7;i++)

p=65;

for(j=1;j<=13;j++)

if(i>1&&j>=x&&j<=y)

else

if(j<7)

else

printf("\n");

if(i>1)

x;

y++;

getch();

/*
ABCDEFGFEDCBA
ABCDEFFEDCBA

printf("%3c",32);

printf("%3c",p);

p++;

p;

C Programming

ABCDEEDCBA
ABCDDCBA
ABCCBA
ABBA
AA
ABBA
ABCCBA
ABCDDCBA
ABCDEEDCBA
ABCDEFFEDCBA
ABCDEFGFEDCBA
*/
#include<stdio.h>
#include<conio.h>
voidmain()
{

inti,j,p,x=7,y=7;

clrscr();

textmode(2);

for(i=1;i<=13;i++)

p=65;

for(j=1;j<=13;j++)

if(i>1&&j>=x&&j<=y)

textcolor(2+128);

C Programming

else

textcolor(14);

cprintf("%3c",p);

if(j<7)

else

printf("\n");

if(i>1)

if(i<7)

x;

y++;

else

x++;

y;

cprintf("%3c",'*');

p++;

p;

C Programming

getch();

}
FUNCTIONS

Definition:
Itisaselfcontainedblockstatementsanditcanbeusedseveralmultipletimesofprogrambutdefinedonlyonce.
Libraryfunctions
Thesefunctionswhichareinbuiltwiththe'c'compilerisknownaslibraryfunctions.
Userdefinedfunctions:
Usercandefinefunctionstodoataskrelevanttotheirprograms.Suchfunctionsarecalledasuserdefinedfunctions.
Anyfunctionhas3things
1.Functiondeclaration
2.Functiondefinition
3.Functioncalling
Incaseofpredefinedfunctions,thefunctiondeclarationisinheaderfilesfunctiondefinitionisin'c'libraries.callingisin
yoursourceprogram.
Butincaseofuserdefinedfunctionsallthe3thingsareinyoursourceprogram.
Functiondeclaration:
returntypefunc_name([arg_list]);
Functiondefinition:
returntypefunc_name([arg_list])
{

body;

}
Functioncalling:
func_name([para_list]);
Theargumentswhicharegivenatthetimeoffunctiondeclaration(or)definitionarecalledasarguments(or)formal
arguments.

C Programming

Theargumentswhicharegivenatthetimeoffunctioncallingarecalledasactualarguments(or)parameters.
voidemptydatatype.
#include<stdio.h>
#include<conio.h>
voidmain()
{

voidfunc();//declaration

clrscr();

textmode(2);

func();//calling

getch();

}
voidfunc()//definition
{

printf("Welcometo'c'functions");

Rulesforcreatingandaccessinguserdefinedfunction:
1.Afunctioncanbecalledbyanynumberoftimes.
2.Afunctionmayormaynotreceivearguments.
3.Afunctionmayormaynotreturnvalue.
4.Ifafunctiondoesnotreturnanyvalue,thefunctionreturndatatypewillbespecifiedasvoid.
5.Ifafunctionreturnsavalueonlyonevaluecanbereturned.
6.Ifafunctionreturnsavaluethereturningvaluemustbereturnwithareturnstatement.
7.Ifafunctionreturnsavaluetheexecutionofreturnstatementshouldbelast.
8.Afunctionreturnsanintegervaluebydefault.
9.Ifafunctionreturnsavalue,thereturningvalueshouldmatchwiththefunctiondatatype.

C Programming

10.Afunctionisdefinedafter(or)beforemainfunction.
11.Beforecallingafunction,thefunctiondeclaration(or)definitionmustandshould.
12.Ifafunctiondeclarationisspecifiedbeforethefunctioncall,thefunctiondefinitioncanbespecifiedanywherein
theprogram.
13.Ifafunctiondefinitionisspecifiedbeforethefunctioncall,thenthefunctiondeclarationisnotnecessary.
14.Ifafunctionisexecuted,thenthefunctioniscallbyitsname.
15.Thefunctiondefinitionshouldnotbeterminatedwithsemicolon.

Return:
Exitsimmediatelyfromthecurrentlyexecutingfunctiontothecallingroutine,optionallyreturningavalue.
Syntax:
return[<expression>];
#include<stdio.h>
#include<conio.h>
voidmain()
{

intfunc(int,int);//declaration

inta,b,s;

clrscr();

printf("Enteranytwointegervalues:");

scanf("%d%d",&a,&b);

s=func(a,b);//calling

printf("Sumis=%d",s);

getch();

}
intfunc(intx,inty)//definition
{

returnx+y;

C Programming

1. Functionwithnoargumentsandnoreturnvalue:
Inthistypethefunctionhasnoarguments,itdoesnotreceiveanydatafromthecallingfunctionsimilarlyitdoes
notreturnanyvalue,thecallingfunctiondoesnotreceiveanydatafromthecalledfunction.sothereisnodata
communicationbetweencallingandcalledfunctions.

#include<stdio.h>
#include<conio.h>
voidmain()
{

voidsum();

clrscr();

sum();

getch();

}
voidsum()
{

inta,b;

printf("Enteranytwointegervalues:");

scanf("%d%d",&a,&b);

printf("Additionis=%d",a+b);

2. Functionwithargumentsandnoreturnvalue:
Inthistypethefunctionhassomearguments,itreceivesdatafromthecallingfunctionbutitdoesnotreturnany
value,thecallingfunctiondoesnotreceiveanydatafromthecalledfunction.sothereisonewaydata
communicationbetweencallingandcalledfunctions.

C Programming

#include<stdio.h>
#include<conio.h>
voidmain()
{

voidsum(int,int);

inta,b;

clrscr();

printf("Enteranytwointegervalues:");

scanf("%d%d",&a,&b);

sum(a,b);

getch();

}
voidsum(intx,inty)
{

printf("Additionis=%d",x+y);

}
3. Functionwithargumentsandreturnvalue:
Inthistypethefunctionhassomearguments;itreceivesdatafromthecallingfunction.
Similarlyitreturnsavaluethecallingfunctionreceivesdatafromthecalledfunctionsothereistwowaydata
communicationbetweencallingandcalledfunctions.
#include<stdio.h>
#include<conio.h>
voidmain()
{

intsum(int,int);

inta,b,s;

clrscr();

printf("Enteranytwointegervalues:");

C Programming

scanf("%d%d",&a,&b);

s=sum(a,b);

printf("Sumis=%d",s);

getch();

}
intsum(intx,inty)
{

returnx+y;

}
4. Functionwithnoargumentsandreturnavalue
Inthistypethefunctionhasnoarguments,itdoesnotreceiveanydatafromthecallingfunctionbutitreturnsavalue,
thecallingfunctionreceivesdatafromthecalledfunctionsothereisonewaydatacommunicationbetweencalling
andcalledfunctions.

#include<stdio.h>
#include<conio.h>
voidmain()
{

intsum();

ints;

clrscr();

s=sum();

printf("Sumis=%d",s);

getch();

}
intsum()
{

inta,b;

C Programming

printf("Enteranytwointegervalues:");

scanf("%d%d",&a,&b);

returna+b;

#include<stdio.h>
#include<conio.h>
voidmain()
{

voidnat(int);

intn;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Naturalnumbersfrom1to%d\n",n);

nat(n);

getch();

}
voidnat(intx)
{

inti;

for(i=1;i<=x;i++)

printf("%d\t",i);

C Programming

#include<stdio.h>
#include<conio.h>
voidmain()
{

voidfactors(int);

intn;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Factorsof%d\n",n);

factors(n);

getch();

}
voidfactors(intx)
{

inti;

for(i=1;i<=x;i++)

if(x%i==0)

#include<stdio.h>
#include<conio.h>
voidmain()
{

printf("%d\t",i);

C Programming

voidfibbo(int);

intn;

clrscr();

printf("Enternumberofterms:");

scanf("%d",&n);

printf("Fibbonacciseries\n");

fibbo(n);

getch();

}
voidfibbo(intx)
{

inti,t1=0,t2=1,t;

printf("%d\t%d",t1,t2);

for(i=1;i<=x2;i++)

t=t1+t2;

printf("\t%d",t);

t1=t2;

t2=t;

#include<stdio.h>
#include<conio.h>
voidmain()
{

intmaxval(int,int);

C Programming

inta,b,max;

clrscr();

printf("Enteranytwointegervalues:");

scanf("%d%d",&a,&b);

max=maxval(a,b);

printf("Maximumvalue=%d",max);

getch();

}
intmaxval(intx,inty)
{

if(x>y)

else

returnx;

returny;

#include<stdio.h>
#include<conio.h>
voidmain()
{

intmaxval(int,int);

inta,b,c,max;

clrscr();

printf("Enteranythreeintegervalues:");

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

/*max=maxval(a,b);

max=maxval(max,c);*/

C Programming

max=maxval(maxval(a,b),c);

printf("Maximumvalue=%d",max);

getch();

}
intmaxval(intx,inty)
{

if(x>y)

else

returnx;

returny;

#include<stdio.h>
#include<conio.h>
voidmain()
{

unsignedlongrevnum(int);

intn;

unsignedlongr;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

r=revnum(n);

printf("Reversenumber=%lu",r);

getch();

}
unsignedlongrevnum(intx)

C Programming

unsignedlongr=0;

while(x>0)

r=r*10+(x%10);

x=x/10;

returnr;

#include<stdio.h>
#include<conio.h>
voidmain()
{

unsignedlongfact(int);

intn;

unsignedlongf;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

f=fact(n);

printf("Factorialofgivennumber=%lu",f);

getch();

}
unsignedlongfact(intx)
{

unsignedlongf=1;

C Programming

inti;

for(i=1;i<=x;i++)

returnf;

f=f*i;

}
#include<stdio.h>
#include<conio.h>
voidmain()
{

unsignedlongfact(int);

intn,r,ncr;

clrscr();

printf("Enternandrvalues:");

scanf("%d%d",&n,&r);

ncr=fact(n)/(fact(r)*fact(nr));

printf("NCRVALUE=%d",ncr);

getch();

}
unsignedlongfact(intx)
{

unsignedlongf=1;

inti;

for(i=1;i<=x;i++)

f=f*i;

C Programming

returnf;

}
#include<stdio.h>
#include<conio.h>
voidmain()
{

intsumdg(unsignedlong);

unsignedlongn;

intsum;

clrscr();

printf("Enteranyintegervalue:");

scanf("%lu",&n);

sum=sumdg(n);

printf("Sumofdigitsofgivennumber=%d",sum);

getch();

}
intsumdg(unsignedlongx)
{

intsum=0;

while(x>0)

sum=sum+(x%10);

x=x/10;

returnsum;

C Programming

#include<stdio.h>
#include<conio.h>
voidmain()
{

unsignedlongfact(int);

intn,i,j,ncr,s;

clrscr();

textmode(2);

printf("Entervalueofn:");

scanf("%d",&n);

s=n*3;

for(i=0;i<n;i++)

printf("%*c",s,32);

for(j=0;j<=i;j++)

ncr=fact(i)/(fact(j)*fact(ij));

printf("%6d",ncr);

printf("\n");

s=s3;

getch();

}
unsignedlongfact(intx)
{

unsignedlongf=1;

C Programming

inti;

for(i=1;i<=x;i++)

returnf;

f=f*i;

Storageclasses
Bythedeclarationstatementthememoryisallocatedtempararilyforallthevariables.Thesizeofmemoryvarieswith
respecttothetypeofvariable.Theavailabilityofthevariablesforaccessdependsonitsdeclarationtype.Thestorage
classspecifiersareusedtospecifythelifeandscopeofvariableswithinblock,functionsandentiresourceprogram.
'c'supports4typesofstorageclasses.
1.automaticvariables
2.staticvariables
3.global(or)externalvariables.
4.registervaraiables.
1.Automaticvariables:
Thsesvariablesaredeclaredinsideafunctionblock.
storage:mainmemory
defaultvalue:garbagevalue
scope:localtotheblockinwhichitisdefine.
life:Tillthecontrolremainswithintheblockinwhich

itisdefined.

keyword:auto

#include<stdio.h>
#include<conio.h>

C Programming

voidmain()
{

autointa,b;

clrscr();

printf("a=%d",a);

printf("\nb=%d",b);

getch();

Note
Ifnostorageclassspecifierbeforethedeclarationofavariableinsideafunctionblock,bydefaultittakesautostorage
class.

#include<stdio.h>
#include<conio.h>
voidmain()
{

autointn;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Valueofn=%d",n);

getch();

3. staticvaribles:
Memoryofstaticvariableremainsunchangeduntiltheendoftheprogram.
storage:mainmemory

C Programming

defaultvalue:0
scope:localtotheblockinwhichitisdefine.
life:Thememoryofstaticvariblepersistsbetweendifferentfunctioncall.thatmeansitcannotreintialise
betweenthedifferentfunctioncall.
keyword:static.

#include<stdio.h>
#include<conio.h>
voidmain()
{

staticinta,b;

clrscr();

printf("a=%d",a);

printf("\nb=%d",b);

getch();

#include<stdio.h>
#include<conio.h>
voiddisp()
{

staticintn=1;

printf("%d\t",n);

n++;

}
voidmain()
{

inti;

C Programming

clrscr();

for(i=1;i<=10;i++)

getch();

disp();

3.Globalvariables(or)externvaraibles
Thesevariablesarebothaliveandactivethroughouttheentireprogram.
storage:mainmemory
defaultvalue:0
scope:global
life:Aslongastheprogramexecutiondoesnotcometoend.
keyword:extern.
#include<stdio.h>
#include<conio.h>
inta,b;
voidmain()
{

clrscr();

printf("a=%d",a);

printf("\nb=%d",b);

getch();

4.registervaribles

C Programming

wecanuseregistervariablesforfrequentlyusedvariablestoimprovethefasterexecutionoftheprogram.
storage:cpu
defaultvalue:garbagevalue
scope:localtotheblockinwhichitisdefine.
life:Tillthecontrolremainswithintheblockinwhichitisdefined.
keyword:register.

#include<stdio.h>
#include<conio.h>
voidmain()
{

registerinta,b;

clrscr();

printf("a=%d",a);

printf("\nb=%d",b);

getch();

}
Note
Registerstorageclasssupportonlyintegraldata.
Recursivefunction(or)recursionfunction:
callingafunctionwithinthesamefunctioniscalledrecursionfunction(or)recursivefunction.
Ifwewanttoworkwithrecursivefunctionwemustfollowingthe2accepts.
1.callingbyitself.
2.terminationcondition.

#include<stdio.h>
#include<conio.h>

C Programming

voidmain()
{

voidnat(int);

intn;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Naturalnumbersfrom1to%d\n",n);

nat(n);

getch();

}
voidnat(intx)
{

if(x>1)

printf("%d\t",x);

nat(x1);

#include<stdio.h>
#include<conio.h>
voidmain()
{

unsignedlongfact(int);

intn;

unsignedlongf;

clrscr();

printf("Enteranyintegervalue:");

C Programming

scanf("%d",&n);

f=fact(n);

printf("Factorialofgivennumber=%lu",f);

getch();

}
unsignedlongfact(intx)
{

if(x<=1)

else

return1;

returnx*fact(x1);

}
#include<stdio.h>
#include<conio.h>
voidmain()
{

unsignedlongrevnum(int);

intn;

unsignedlongrev;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

rev=revnum(n);

printf("Reversenumber=%lu",rev);

getch();

}
unsignedlongrevnum(intx)

C Programming

staticunsignedlongrev=0;

rev=rev*10+(x%10);

x=x/10;

if(x>0)

returnrev;

revnum(x);

#include<stdio.h>
#include<conio.h>
voidmain()
{

voidfibbo(int);

intn;

clrscr();

printf("Enternumberofterms:");

scanf("%d",&n);

printf("Fibbonacciseries\n");

fibbo(n);

getch();

}
voidfibbo(intx)
{

staticinti,t1=0,t2=1,t;

if(t==0)

C Programming

printf("%d\t%d",t1,t2);

x=x2;

t=t1+t2;

printf("\t%d",t);

x=x1;

if(x>=1)

t1=t2;

t2=t;

fibbo(x);

#include<stdio.h>
#include<conio.h>
#include<process.h>
voidmain()
{

staticinti=1,n;

if(i==1)

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

printf("Naturalnumbersfrom1to%d\n",n);

C Programming

printf("%d\t",i);

i++;

if(i<=n)

getch();

exit(0);

main();

math.hfunctions

abs<math.h>
abs(amacro)getstheabsolutevalueofaninteger.
declaration
intabs(intx);
#include<stdio.h>
#include<conio.h>
#include<math.h>
voidmain()
{

intn,a;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

a=abs(n);

printf("Absolutevalueofgivennumber=%d",a);

getch();

C Programming

pow<math.h>
Itcalculatesexponentialvalueofgivenbaseandpower.
declaration
doublepow(doublex,doubley);

#include<stdio.h>
#include<conio.h>
#include<math.h>
voidmain()
{

intb,p;

doublee;

clrscr();

printf("Enterbaseandpower:");

scanf("%d%d",&b,&p);

e=pow(b,p);

printf("Exponentialvalueof%dand%dis%.3lf",b,p,e);

getch();

sqrt<math.h>
Itcalculatessquarerootofgivennumber.
declaration
doublesqrt(doublex);

#include<stdio.h>
#include<conio.h>

C Programming

#include<math.h>
voidmain()
{

intn;

doubles;

clrscr();

printf("Enteranyintegervalue:");

scanf("%d",&n);

s=sqrt(n);

printf("Squarerootofgivennumber=%.3lf",s);

getch();

ceil<math.h>
Itroundsupthegivenvalue.
declaration
doubleceil(doublex);

floor<math.h>
Itroundsdownthegivenvalue.
declaration
doublefloor(doublex);

#include<stdio.h>
#include<conio.h>
#include<math.h>
voidmain()

C Programming

floatn,c,f;

clrscr();

printf("Enteranyfloatvalue:");

scanf("%f",&n);

c=ceil(n);

f=floor(n);

printf("Ceilvalue=%.2f",c);

printf("\nFloorvalue=%.2f",f);

getch();

#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<process.h>
voidmain()
{

floata,b,c,s,area;

clrscr();

printf("Enteranythreesides:");

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

if((a+b)<=c||(b+c)<=a||(c+a)<=b)

printf("Unabletoformtriangle");

getch();

exit(0);

C Programming

s=(a+b+c)/2;

area=sqrt(s*(sa)*(sb)*(sc));

printf("Areaoftriangle=%.2f",area);

getch();

ARRAYS

Agroupofdataitemsofsamedatatypestoredinacontinuousmemorylocationanditcanberepresentedbyasigle
identifier,thatmeansagroupofdataitemsthatsharedacommonname.
Aparticularvalueisincatedbywritinganocalledindex(or)subscriptinsquarebracesafterthearrayname.'C'
supportsthreetypesofarrays.
1.Singledimensionalarray.
2.Twodimensionalarray.
3.Threedimensionalarray.

1.Singledimensionalarray:
Alistofitemscanbegivenonevariablenameusingonlyoneindex.suchvariableiscalledsingledimensionalarray.In
singledimensionalarraytheelementsarerepresentoneafterotherinedgesofmemorybytes.
declaration
datatypearr_name[size];
eg
inta[5];
elements
a[0],a[1],a[2],a[3]anda[4].
Inanyarraythearrayindexis0to(n1).
intialisation
datatypearr_name[size]={value1,value2,valuen};

C Programming

optional
eg
inta[5]={1,2,3,4,5};
inta[]={100,200,300};
floatft[4]={123.78,1.1,2.3,4.89};

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta[5]={11,34,78,45,21},i;

clrscr();

for(i=0;i<5;i++)

getch();

printf("\na[%d]=%d",i,a[i]);

#include<stdio.h>
#include<conio.h>
#include<process.h>
voidmain()
{

inta[20],n,i;

clrscr();

printf("Enternumberofelements:");

C Programming

scanf("%d",&n);

if(n>20)

printf("Arrayindexoutofbounds");

getch();

exit(0);

printf("Enterarrayelements\n");

for(i=0;i<n;i++)

printf("Entervalueintoa[%d]=",i);

scanf("%d",&a[i]);

printf("Arrayelements\n");

for(i=0;i<n;i++)

getch();

printf("\nGivenvalueina[%d]=%d",i,a[i]);

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta[20],n,i;

clrscr();

C Programming

printf("Enternumberofelements:");

scanf("%d",&n);

printf("Enterarrayelements\n");

for(i=0;i<n;i++)

printf("Arrayelements\n");

for(i=0;i<n;i++)

getch();

scanf("%d",&a[i]);

printf("%d\t",a[i]);

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta[20],n,i;

clrscr();

printf("Enternumberofelements:");

scanf("%d",&n);

printf("Enterarrayelements\n");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

C Programming

printf("Arrayelementsinreverseorder\n");

for(i=n1;i>=0;i)

getch();

printf("%d\t",a[i]);

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta[20],n,i,max,min;

clrscr();

printf("Enternumberofelements:");

scanf("%d",&n);

printf("Enterarrayelements\n");

for(i=0;i<n;i++)

max=a[0];

min=a[0];

for(i=1;i<n;i++)

scanf("%d",&a[i]);

if(a[i]>max)

C Programming

if(a[i]<min)

printf("Maximumvalue=%d",max);

printf("\nMinimumvalue=%d",min);

getch();

max=a[i];

min=a[i];

writeaprogramtoacceptasingledimensionalintegerarrayandsearchspecifiedelementinthegivenarray

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta[20],n,i,se,ck=0;

clrscr();

printf("Enternoofelements:");

scanf("%d",&n);

printf("Enterarrayelements\n");

for(i=0;i<n;i++)

printf("Enterelementtosearch:");

scanf("%d",&se);

for(i=0;i<n;i++)

scanf("%d",&a[i]);

C Programming

if(a[i]==se)

ck=1;

printf("Elementisfoundata[%d]",i);

if(ck==0)

getch();

printf("Elementnotfound");

writeaprogramtoacceptasingledimensionalintegerarrayanddeletespecifiedelementinthegivenarray.
#include<stdio.h>
#include<conio.h>
voidmain()
{

inta[20],n,i,j,de,ck=0;

clrscr();

printf("Enternoofelements:");

scanf("%d",&n);

printf("Enterarrayelements\n");

for(i=0;i<n;i++)

printf("Enterelementtodelete:");

scanf("%d",&a[i]);

C Programming

scanf("%d",&de);

for(i=0;i<n;i++)

if(a[i]==de)

ck=1;

for(j=i;j<n;j++)

n;

if(ck==0)

else

printf("Arrayelementsafterdeletion\n");

for(i=0;i<n;i++)

getch();

a[j]=a[j+1];

printf("Elementnotfound");

printf("%d\t",a[i]);

writeaprogramtoacceptasingledimensionalintegerarrayandinsertanelementinthegivenarrayatspecified
position.

C Programming

#include<stdio.h>
#include<conio.h>
#include<process.h>
voidmain()
{

inta[20],n,i,pos,ie,t;

clrscr();

printf("Enternoofelements:");

scanf("%d",&n);

printf("Enterarrayelements\n");

for(i=0;i<n;i++)

printf("Enterposition:");

scanf("%d",&pos);

if(pos>n)

printf("Invalidposition");

getch();

exit(0);

printf("Arrayelementsbeforeinsertion\n");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

printf("%d\t",a[i]);

C Programming

printf("\nEnterelementtoinsert:");

scanf("%d",&ie);

if(pos==n)

a[pos]=ie;//a[n]=ie;

n++;

else

for(i=pos;i<=n;i++)

t=a[i];

a[i]=ie;

ie=t;

n++;

printf("Arrayelementsafterinsertion\n");

for(i=0;i<n;i++)

getch();

printf("%d\t",a[i]);

writeaprogramtoacceptasingledimensionalintegerarrayanddisplayarrayelementsinascendingorder.

C Programming

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta[20],n,i,j,t;

clrscr();

printf("Enternoofelements:");

scanf("%d",&n);

printf("Enterarrayelements\n");

for(i=0;i<n;i++)

printf("Givenelementsbeforesorting\n");

for(i=0;i<n;i++)

/*sorting*/

for(i=0;i<n1;i++)

for(j=i+1;j<n;j++)

if(a[i]>a[j])

t=a[i];

a[i]=a[j];

scanf("%d",&a[i]);

printf("%d\t",a[i]);

C Programming

printf("\nGivenelementsaftersorting\n");

for(i=0;i<n;i++)

getch();

a[j]=t;

printf("%d\t",a[i]);

writeaprogramtoacceptasingledimensionalintegerarray,itcannotacceptduplicateelementsinthegivenarray.
#include<stdio.h>
#include<conio.h>
voidmain()
{

inta[20],n,i,j;

clrscr();

printf("Enternoofelements:");

scanf("%d",&n);

printf("Enterarrayelements\n");

for(i=0;i<n;i++)

lb:

scanf("%d",&a[i]);

for(j=0;j<i;j++)

C Programming

if(a[i]==a[j])

printf("Elementalreadyexists\n");

printf("Enternewelement:");

gotolb;

printf("Givenelements\n");

for(i=0;i<n;i++)

getch();

printf("%d\t",a[i]);

}
Twodimensionalarrays

Twodimnsionalarraycanstoreatableofvalueswhichcontainsrowsandcolumns.
InTwodimensionalarrayweusetwoindexvaluesoneforrowsandanotherforcolumns.
declaration
datatypearr_name[rowsize][colsize];
eg
inta[2][3];
elements
a[0][0]a[0][1]a[0][2]
a[1][0]a[1][1]a[1][2]

C Programming

Intialisation
Form1
datatypearr_name[rowsize][colsize]={value1,value2,value3,valuen};

optional

eg
inta[2][3]={1,2,3,4,5,6};
Form2
datatypearr_name[rowsize][colsize]={{value1,value2,valuen},

{value1,value2,valuen},

{value1,value2,valuen}

};

eg
inta[3][3]={{1,2,3},{4,5,6},{7,8,9}};

#include<stdio.h>
#include<conio.h>
voidmain()
{

/*inta[3][3]={1,2,3,4,5,6,7,8,9};*/

inta[3][3]={{1,2,3},{4,5,6},{7,8,9}};

inti,j;

clrscr();

printf("Intialisedelements\n");

for(i=0;i<3;i++)

C Programming

for(j=0;j<3;j++)

getch();

printf("\na[%d][%d]=%d",i,j,a[i][j]);

}
#include<stdio.h>
#include<conio.h>
#include<process.h>
voidmain()
{

inta[20][20],r,c,i,j;

clrscr();

printf("Enternumberofrowsandcolumns:");

scanf("%d%d",&r,&c);

if(r>20||c>20)

printf("Arrayindexoutofbounds");

getch();

exit(0);

printf("Enterarrayelements\n");

for(i=0;i<r;i++)

for(j=0;j<c;j++)

C Programming

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

scanf("%d",&a[i][j]);

printf("Arrayelements\n");

for(i=0;i<r;i++)

for(j=0;j<c;j++)

printf("\nGivenvalueina[%d][%d]=%d",i,j,a[i][j]);

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta[20][20],r,c,i,j;

clrscr();

printf("Enternumberofrowsandcolumns:");

scanf("%d%d",&r,&c);

printf("Enterarrayelements\n");

for(i=0;i<r;i++)

C Programming

for(j=0;j<c;j++)

printf("Arrayelements\n");

for(i=0;i<r;i++)

for(j=0;j<c;j++)

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

printf("\n");

getch();

scanf("%d",&a[i][j]);

}
#include<stdio.h>
#include<conio.h>
voidmain()
{

voidaccept(int[][20],int,int);

voiddisp(int[][20],int,int);

inta[20][20],r,c;

clrscr();

printf("Enternumberofrowsandcolumns:");

C Programming

scanf("%d%d",&r,&c);

printf("Enterarrayelements\n");

accept(a,r,c);

printf("Givenelements\n");

disp(a,r,c);

getch();

}
voidaccept(intarr[][20],intm,intn)
{

inti,j;

for(i=0;i<m;i++)

for(j=0;j<n;j++)

scanf("%d",&arr[i][j]);

}
voiddisp(intarr[][20],intm,intn)
{

inti,j;

for(i=0;i<m;i++)

for(j=0;j<n;j++)

printf("%d\t",arr[i][j]);

C Programming

printf("\n");

writeaprogramtoacceptanymatrixanddisplayitstranposematrix.
#include<stdio.h>
#include<conio.h>
voidmain()
{

voidaccept(int[][20],int,int);

voiddisp(int[][20],int,int);

voidtrans(int[][20],int[][20],int,int);

inta[20][20],at[20][20],r,c;

clrscr();

printf("Enterrowsandcolumns:");

scanf("%d%d",&r,&c);

printf("Enteranymatrix\n");

accept(a,r,c);

printf("Givenmatrix\n");

disp(a,r,c);

trans(a,at,r,c);

printf("Transposematrix\n");

disp(at,c,r);

getch();

}
voidaccept(inta[][20],intr,intc)
{

C Programming

inti,j;

for(i=0;i<r;i++)

for(j=0;j<c;j++)

scanf("%d",&a[i][j]);

}
voiddisp(inta[][20],intr,intc)
{

inti,j;

for(i=0;i<r;i++)

for(j=0;j<c;j++)

printf("\n");

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

}
voidtrans(inta[][20],intat[][20],intr,intc)
{

inti,j;

for(i=0;i<r;i++)

for(j=0;j<c;j++)

C Programming

at[j][i]=a[i][j];

writeaprogramtodisplayadditionoftwomatricesusingfunctions
#include<stdio.h>
#include<conio.h>
voidmain()
{

voidaccept(int[][20],int,int);

voiddisp(int[][20],int,int);

voidaddition(int[][20],int[][20],int[][20],int,int);

inta[20][20],b[20][20],add[20][20],r,c;

clrscr();

printf("Enterrowsandcolumns:");

scanf("%d%d",&r,&c);

printf("Enterfirstmatrix\n");

accept(a,r,c);

printf("Entersecondmatrix\n");

accept(b,r,c);

addition(a,b,add,r,c);

printf("Firstmatrix\n");

disp(a,r,c);

printf("Secondmatrix\n");

disp(b,r,c);

C Programming

printf("Additionoftwomatrices\n");

disp(add,r,c);

getch();

}
voidaccept(intarr[][20],intm,intn)
{

inti,j;

for(i=0;i<m;i++)

for(j=0;j<n;j++)

scanf("%d",&arr[i][j]);

}
voiddisp(intarr[][20],intm,intn)
{

inti,j;

for(i=0;i<m;i++)

for(j=0;j<n;j++)

printf("\n");

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

C Programming

voidaddition(inta[][20],intb[][20],intadd[][20],intm,intn)
{

inti,j;

for(i=0;i<m;i++)

for(j=0;j<n;j++)

add[i][j]=a[i][j]+b[i][j];

writeaprogramtodisplaymultiplicationoftwomatricesusingfunctions
#include<stdio.h>
#include<conio.h>
#include<process.h>
voidmain()
{

voidaccept(int[][20],int,int);

voiddisp(int[][20],int,int);

voidmul(int[][20],int[][20],int[][20],int,int,int);

inta[20][20],b[20][20],c[20][20],m,n,p,q;

clrscr();

printf("Enterrowsandcolumnsforfirstmatrix:");

scanf("%d%d",&m,&n);

printf("Enterrowsandcolumnsforsecondmatrix:");

scanf("%d%d",&p,&q);

C Programming

if(n!=p)

printf("Matrixmultiplicationisnotpossible");

getch();

exit(0);

printf("Enterfirstmatrix\n");

accept(a,m,n);

printf("Entersecondmatrix\n");

accept(b,p,q);

printf("Firstmatrix\n");

disp(a,m,n);

printf("Secondmatrix\n");

disp(b,p,q);

mul(a,b,c,m,n,q);

printf("Multoplicationoftwomatrices\n");

disp(c,m,q);

getch();

}
voidaccept(intarr[][20],intm,intn)
{

inti,j;

for(i=0;i<m;i++)

for(j=0;j<n;j++)

scanf("%d",&arr[i][j]);

C Programming

}
voiddisp(intarr[][20],intm,intn)
{

inti,j;

for(i=0;i<m;i++)

for(j=0;j<n;j++)

printf("\n");

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

}
voidmul(inta[][20],intb[][20],intc[][20],intm,intn,intq)
{

inti,j,k;

for(i=0;i<m;i++)

for(j=0;j<q;j++)

c[i][j]=0;

for(k=0;k<n;k++)

c[i][j]=c[i][j]+a[i][k]*b[k][j];

C Programming

writeaprogramtoacceptanymatrixandcheckwhetherthegivenmatrixisidentityornot
#include<stdio.h>
#include<conio.h>
voidmain()
{

voidaccept(int[][20],int,int);

voiddisp(int[][20],int,int);

intidentity(int[][20],int,int);

inta[20][20],r,c,k;

clrscr();

printf("Enternoofrowsandcolumns:");

scanf("%d%d",&r,&c);

if(r!=c)

printf("Identitymatrixisnotpossible");

getch();

exit(0);

printf("Enterthematrix\n");

accept(a,r,c);

printf("Givenmatrix\n");

disp(a,r,c);

k=identity(a,r,c);

C Programming

if(k==1)

printf("Givenmatrixisidentitymatrix");

else

printf("Givenmatrixisnotidentitymatrix");

getch();

}
voidaccept(inta[][20],intr,intc)
{

inti,j;

for(i=0;i<r;i++)

for(j=0;j<c;j++)

scanf("%d",&a[i][j]);

}
voiddisp(inta[][20],intr,intc)
{

inti,j;

for(i=0;i<r;i++)

for(j=0;j<c;j++)

printf("\n");

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

C Programming

}
intidentity(inta[][20],intr,intc)
{

inti,j;

for(i=0;i<r;i++)

for(j=0;j<c;j++)

if(i==j)

if(a[i][j]!=1)

return0;

else

{if(a[i][j]!=0)

return1;

return0;

C Programming

Multidimensionalarrays

'c'supportsarraysof3ormoredimensions.Inmultidimensionalarraysweusemorethantwoindexvalues.
ThegeneralformofMultidimensionalarrayis
datatypearr_name[s1][s2][sn];
wheres1,s2,snaresizes.
eg
inta[2][2][3];
elements
a[0][0][0]a[0][0][1]a[0][0][2]
a[0][1][0]a[0][1][1]a[0][1][2]
a[1][0][0]a[1][0][1]a[1][0][2]
a[1][1][0]a[1][1][1]a[1][1][2]

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta[2][2][3],i,j,k;

clrscr();

printf("Enterarrayelements\n");

for(i=0;i<2;i++)

for(j=0;j<2;j++)

for(k=0;k<3;k++)

C Programming

printf("Entervalueintoa[%d][%d][%d]=",i,j,k);

scanf("%d",&a[i][j][k]);

printf("Arrayelements\n");

for(i=0;i<2;i++)

for(j=0;j<2;j++)

for(k=0;k<3;k++)

printf("\nGivenvalueina[%d][%d][%d]=%d",i,j,k,a[i][j][k]);

getch();

}
Strings

Agroupofcharactersdefinedbetweendoublequotationmarksisastring.Butin'c'languageastringisnothingbutan
arrayofcharactersandteminatedbyanullcharacter(\0).
Declaration
charidentifier[size];
eg:
charst[20];
Initialisation
charidentifier[size]="string";

C Programming

eg
charst[20]="welcome";
whenthecompilerassignsacharacterstringtoacharacterarray,itautomaticallysuppliesanullcharacter(\0)atthe
endofthestringthereforethesizeshouldbeequaltothemaximumnoofcharactersinthegivenstring+1.
formatspecifierofstringis%s.

#include<stdio.h>
#include<conio.h>
voidmain()
{

charst[20]="welcome";

clrscr();

printf("Givenstring=%s",st);

getche();

gets
Itgetsastringfromstdin.
declaration
char*gets(char*s);

puts
Itoutputsastringtostdout.
declaration
intputs(constchar*s)(andappendsanewlinecharacter)

#include<stdio.h>
#include<conio.h>

C Programming

voidmain()
{

charst[40];

clrscr();

puts("Enteranystring:");

gets(st);

puts("Givenstring");

puts(st);

getch();

getch
getchgetsacharacterfromkeyboardbutdoesnotechotothescreen.
declaration
intgetch();

getche
getchegetsacharacterfromkeyboardandechoestothescreen.
Declaration

intgetche();
#include<stdio.h>
#include<conio.h>
voidmain()
{

charch;

clrscr();

C Programming

printf("Enteranycharacter:");

ch=getch();

//ch=getche();

printf("\nGivencharcter=%c",ch);

getch();

getchar
Itisamacrothatgetscharacterfromstdin.
declaration
intgetchar(void);

putchar
putcharisamacrothatoutputsacharacteronstdout.
declaration
intputchar(intc);

#include<stdio.h>
#include<conio.h>
voidmain()
{

charch;

clrscr();

printf("Enteranycharacter:");

ch=getchar();

printf("Givencharacter:");

putchar(ch);

C Programming

getch();

Stringhandlingfunctions
1.strlen<string.h>
Itcalculateslengthofthegivenstring.
declaration
size_tstrlen(constchar*s);

#include<stdio.h>
#include<conio.h>
#include<string.h>
voidmain()
{

charst[40];

intlen;

clrscr();

printf("Enteranystring:");

gets(st);

len=strlen(st);

printf("Lengthofthegivenstring=%d",len);

getch();

2.strcpy<string.h>
Itcopiesonestringtoanother.

C Programming

declaration
char*strcpy(char*dest,constchar*src);

#include<stdio.h>
#include<conio.h>
#include<string.h>
voidmain()
{

charst1[40],st2[40];

clrscr();

printf("Enteranystring:");

gets(st1);

strcpy(st2,st1);

printf("Givenstring=%s",st1);

printf("\nCopiedstring=%s",st2);

getch();

3.strncpy<string.h>
Itcopiesspecifednumberofcharactersfromonestringtoanother.
declaration
char*strncpy(char*dest,constchar*src,size_tmaxlen);

#include<stdio.h>
#include<conio.h>
#include<string.h>
voidmain()

C Programming

charst1[40],st2[40];

intn;

clrscr();

printf("Enteranystring:");

gets(st1);

printf("Enterspecifiednumberofcharacterstobecopied:");

scanf("%d",&n);

strncpy(st2,st1,n);

st2[n]='\0';

printf("Givenstring=%s",st1);

printf("\nCopiedstring=%s",st2);

getch();

4.strrev<string.h>
Itreversesthegivenstring.
declaration
char*strrev(char*s);

#include<stdio.h>
#include<conio.h>
#include<string.h>
voidmain()
{

charst[40];

clrscr();

C Programming

printf("Enteranystring:");

gets(st);

printf("Givenstring=%s",st);

strrev(st);

printf("\nReversestring=%s",st);

getch();

5.strcat<string.h>
Itappendsonestringtoanother.
declaration
char*strcat(char*dest,constchar*src);

#include<stdio.h>
#include<conio.h>
#include<string.h>
voidmain()
{

charst1[80],st2[40];

clrscr();

printf("Enterfirststring:");

gets(st1);

printf("Entersecondstring:");

gets(st2);

strcat(st1,st2);

printf("Concatenationoftwostrings=%s",st1);

getch();

C Programming

6.strupr<string.h>
Itconvertslowercaseletters(atoz)inthegivenstringto
uppercase(AtoZ)
declaration
char*strupr(char*s);

7.strlwr<string.h>
Itconvertsuppercaseletters(AtoZ)inthegivenstringtolowercase(atoz)
declaration
char*strlwr(char*s);

#include<stdio.h>
#include<conio.h>
#include<string.h>
voidmain()
{

charst[80];

clrscr();

printf("Enteranystring:");

gets(st);

printf("Givenstring=%s",st);

strupr(st);

printf("\nGivenstringinuppercase=%s",st);

strlwr(st);

printf("\nGivenstringinlowercase=%s",st);

C Programming

getch();

8.strcmp(function)<string.h>
Itcomparestwostringswithcasesensitivity.
intstrcmp(constchar*s1,constchar*s2);

9.stricmp(function)<string.h>
Itcomparestwostringswithoutcasesensitivity.
intstricmp(constchar*s1,constchar*s2);

10.strcmpi(macro)<string.h>
Itcomparestwostringswithoutcasesensitivity.

intstrcmpi(constchar*s1,constchar*s2);
returnvalue
Theseroutinesreturnanintvalue
i.e;<0ifs1<s2
==0ifs1==s2
>0ifs1>s2

#include<stdio.h>
#include<conio.h>
#include<string.h>
voidmain()
{

charst1[80],st2[80];

C Programming

intk;

clrscr();

printf("Enterfirststring:");

gets(st1);

printf("Entersecondstring:");

gets(st2);

/*k=strcmp(st1,st2);

k=strcmpi(st1,st2);*/

k=stricmp(st1,st2);

if(k==0)

printf("Twostringsareequal");

elseif(k<0)

printf("Firststringislessthansecondstring");

else

printf("Firststringisgreaterthansecondstring");

getch();

#include<stdio.h>
#include<conio.h>
#include<string.h>
voidmain()
{

charst1[80],st2[40];

intk;

clrscr();

printf("Enteranystring:");

C Programming

gets(st1);

strcpy(st2,st1);

strrev(st2);

k=strcmp(st1,st2);

if(k==0)

else

getch();

printf("Givenstringispallindrome");

printf("Givenstringisnotpallindrome");

#include<stdio.h>
#include<conio.h>
#include<string.h>
voidmain()
{

charst[80];

intns=0,nw=0,nc=0,na=0,nd=0,nsp=0,i;

clrscr();

printf("Enteranystring:");

gets(st);

for(i=0;i<=strlen(st);i++)

if(st[i]==32)

ns++;

nw++;

C Programming

elseif((st[i]>=65&&st[i]<=90)||(st[i]>=97&&st[i]<=122))

na++;

nc++;

elseif(st[i]>=48&&st[i]<=57)

nc++;

nd++;

elseif(st[i]=='\0')

else

nc++;

nsp++;

nw++;

printf("Noofspaces=%d",ns);

printf("\nNoofwords=%d",nw);

printf("\nNoofcharacters=%d",nc);

printf("\nNoofalphabets=%d",na);

printf("\nNoofdigits=%d",nd);

C Programming

printf("\nNofofspecialcharacters=%d",nsp);

getch();

#include<stdio.h>
#include<conio.h>
#include<string.h>
voidmain()
{

charst[80];

staticinta[256],i;

clrscr();

printf("Enteranystring:");

gets(st);

for(i=0;i<strlen(st);i++)

printf("CHARFRE");

printf("\n\n");

for(i=0;i<=255;i++)

if(a[i]!=0)

a[st[i]]=a[st[i]]+1;

printf("\n%c%d",i,a[i]);

C Programming

getch();

Twodimensionalcharacterarrays
Alistofnamescanbetreatedastableofstringsandatwodimensional
characterarraycanbeusedtostoretheentirelist.
foreg
charst[5][20]maybeusedtostorealistofnames,eachoflengthnotmorethan20charactres.

#include<stdio.h>
#include<conio.h>
voidmain()
{

charst[20][20];

intn,i;

clrscr();

printf("Enteranumberofstrings:");

scanf("%d",&n);

printf("Enterany%dstrings\n",n);

fflush(stdin);

for(i=0;i<n;i++)

printf("Givenstrings\n");

for(i=0;i<n;i++)

gets(st[i]);

C Programming

getch();

puts(st[i]);

}
#include<stdio.h>
#include<conio.h>
#include<string.h>
voidmain()
{

charst[20][20],temp[20];

intn,i,j,k;

clrscr();

printf("Enteranumberofstrings:");

scanf("%d",&n);

printf("Enterany%dstrings\n",n);

fflush(stdin);

for(i=0;i<n;i++)

printf("GivenstringsBeforesorting\n");

for(i=0;i<n;i++)

/*sorting*/

gets(st[i]);

puts(st[i]);

C Programming

for(i=0;i<n1;i++)

for(j=i+1;j<n;j++)

k=strcmp(st[i],st[j]);

if(k>0)

strcpy(temp,st[i]);

strcpy(st[i],st[j]);

strcpy(st[j],temp);

printf("\nGivenstringsAftersorting\n");

for(i=0;i<n;i++)

getch();

puts(st[i]);

}
POINTERS

Cprovidestheimportantfeatureofdatamanipulationswiththeaddressofthevariables,andhencetheexecution
timeismuchreduced.Suchconceptispossiblewiththespecialdatatypescalledpointers.
Pointer
Apointerisavariablewhichcanstoretheaddressofanothervariable.

C Programming

Declaration
Pointerdeclarationissimilartonormaldeclarationbutprecededbyasterik(*).
datatype*identifier;
eg
int*p;
Initialisation
datatype*identifer=address;
eg
intn;
int*p=&n;
Note
Foranytypeofpointer,thetotalnumberofbytesallocatedisalways2bytes.Becausethepointervariablestores
addressofthememorylocations.

#include<stdio.h>
#include<conio.h>
voidmain()
{

int*p1;

char*p2;

float*p3;

double*p4;

clrscr();

textmode(2);

printf("Sizeofintegerpointer=%dbytes",sizeof(p1));

printf("\nSizeofcharacterpointer=%dbytes",sizeof(p2));

printf("\nSizeoffloatpointer=%dbytes",sizeof(p3));

printf("\nSizeofdoublepointer=%dbytes",sizeof(p4));

C Programming

getch();

void*
Itisagenericpointerreferstheaddressofanytypeofvariableandalsoitwillassigntoanytypeofpointer.

#include<stdio.h>
#include<conio.h>
voidmain()
{

intn=100;

int*p=&n;

clrscr();

textmode(2);

printf("Valueofn=%d",n);

printf("\nAddressofn=%u",&n);

printf("\nValueofnusingp=%d",*p);

printf("\nAddressofnusingp=%u",p);

*p=500;/*n=500*/

printf("\nChangedvalueofn=%d",n);

getch();

Pointersandfunctions
callbyvalue(passbyvalue)
Theprocessofpassingthevaluetothefunctioncallisknownascallbyvalue.

C Programming

#include<stdio.h>
#include<conio.h>
voidmain()
{

voidfunc(int);

clrscr();

func(100);

getch();

}
voidfunc(intk)
{

printf("k=%d",k);

#include<stdio.h>
#include<conio.h>
voidmain()
{

voidfunc(int,int);

inta,b;

clrscr();

printf("Enteranytwointegervalues:");

scanf("%d%d",&a,&b);

func(a,b);

getch();

}
voidfunc(intx,inty)

C Programming

printf("sumis%d",x+y);

callbyreference
Theprocessofcallingafunctionusingpointerstopasstheaddressofvariablesiskunownascallbyreference.

#include<stdio.h>
#include<conio.h>
voidmain()
{

voidsetdata(int*);

intn;

clrscr();

setdata(&n);

printf("n=%d",n);

getch();

}
voidsetdata(int*k)
{

*k=500;

#include<stdio.h>
#include<conio.h>
voidmain()
{

C Programming

voidaccept(int*);

intn;

clrscr();

accept(&n);

printf("n=%d",n);

getch();

}
voidaccept(int*p)
{

printf("Enteranyintegervalue:");

scanf("%d",p);

#include<stdio.h>
#include<conio.h>
voidmain()
{

voidaccept(int*,char*,float*);

inteno;

charename[80];

floatsal;

clrscr();

accept(&eno,ename,&sal);

printf("Empnumber=%d",eno);

printf("\nEmpname=%s",ename);

printf("\nEmpsalary=%.2f",sal);

getch();

C Programming

}
voidaccept(int*no,char*name,float*s)
{

printf("Enterempnumber:");

scanf("%d",no);

printf("Enterempname:");

fflush(stdin);

gets(name);

printf("Entersalary:");

scanf("%f",s);

Pointersandarrays
Whenanarrayisdeclaredthecompilerallocatesthebaseaddressandsufficientamountofstoragecontainallthe
arraycontinuousmemorylocation.
Thebaseaddressisthelocationoftheaddressisthefirstelement(index0)ofthearray.
Thecompileralsodefinesthearraynameasaconstantpointertopointtothefirstelement.
supposewedeclareanarray'a'(arrayname)asfollows.
inta[5]={1,2,3,4,5};
supposethebaseaddressof'a'is1000.andassumingtheeachintegerrequires2bytes,thefiveelementswillbestored
asfollows.Thename'a'isdefinedasconstantpointertopointtothefirstelementa[0].
Thevalueof'a'is1000,thelocationwherea[0]isstored.
a=&a[0]=1000.

#include<stdio.h>
#include<conio.h>
voidmain()

C Programming

inta[5];

clrscr();

printf("Baseaddress=%u",&a[0]);

printf("\nBaseaddress=%u",a);

getch();

}
ifwedeclared'p'isaninetegerpointer,thenwecanmakethepointer'p'topointtothearray'a'bythefollowing
assignment.
int*p;
p=a;(or)p=&a[0];
Nowwecanaccesseveryvalueof'a'usingp++(or)p+1tomoveoneelement
toanother.Therelationshipbetween'p'and'a'isshownbelow.
p+0=&a[0]=1000
p+1=&a[1]=1002
p+2=&a[2]=1004
p+3=&a[3]=1006
p+4=&a[4]=1008
whenhandlingarraysinsteadofusingarrayindex,wecanusepointerstoaccessarrayelements.
Notethat*(p+k)givesthevalueofa[k].Thepointeraccessingmethodismuchfasterthanarrayindexing.

#include<stdio.h>
#include<conio.h>
voidmain()
{

inta[20],i,n,*p;

clrscr();

C Programming

p=a;/*p=&a[0]*/

printf("Enterarrayelements:");

scanf("%d",&n);

printf("Enterarrayelements\n");

for(i=0;i<n;i++)

printf("Arrayelements\n");

for(i=0;i<n;i++)

getch();

scanf("%d",p+i);

printf("%4d",*(p+i));

Dynamicmemoryallocation:
The'c'languagerequiresthenumberofelementsinanarraytobesoecifiedatcompiletime.Butwemaynotbeable
todoalways.
Ourinitialjudgementofsize,ifitiswrongmaycausefailureoftheprogram(or)wastageofmemoryspace.
AtthisstageweuseDynamicmemoryallocation.
Definition
TheprocessofallocatingmemoryatruntimeisknownasDynamicmemoryallocation.
malloc<alloc.h>
Itisusedtoallocatingmemoryatruntime.
syntax
void*malloc(size_tsize);
pointer=(typecast)malloc(memorysize);

C Programming

eg
int*p;
p=(int*)malloc(sizeof(int));1location
p=(int*)malloc(5*sizeof(int));5locations

calloc<alloc.h>
syntax
void*calloc(size_tnitems,size_tsize);
pointer=(typecast)calloc(noofitems,sizeofeachitem);
eg
int*p;
p=(int*)calloc(1,sizeof(int));1location
p=(int*)calloc(5,sizeof(int));5locations
Note
callocallocatesablock(nitems*size)bytesandclearsitto0.

free
Itfreesallocatedblocks
declaration
voidfree(void*block);

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
voidmain()
{

int*a,n,i;

C Programming

clrscr();

textmode(2);

printf("Enternumberofelements:");

scanf("%d",&n);

a=(int*)malloc(n*sizeof(int));

printf("Enterelements\n");

for(i=0;i<n;i++)

printf("Givenelements\n");

for(i=0;i<n;i++)

free(a);

getch();

scanf("%d",a+i);

printf("%d\t",*(a+i));

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
voidmain()
{

int**a,r,c,i,j;

clrscr();

textmode(2);

C Programming

printf("Enternumberofrowsandcolumns:");

scanf("%d%d",&r,&c);

a=(int**)malloc(r*sizeof(int*));

for(i=0;i<r;i++)

printf("Enterelements\n");

for(i=0;i<r;i++)

for(j=0;j<c;j++)

printf("Givenelements\n");

for(i=0;i<r;i++)

for(j=0;j<c;j++)

printf("\n");

free(a);

getch();

*(a+i)=(int*)malloc(c*sizeof(int));

scanf("%d",*(a+i)+j);

printf("%3d",*(*(a+i)+j));

C Programming

realloc
Itreallocatesmainmemoryatruntime.
syntax
void*realloc(void*block,size_tsize);

int*p;
p=(int*)malloc(5*sizeof(int));
p=(int*)realloc(p,8*sizeof(int));

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
voidmain()
{

char*st;

clrscr();

st=(char*)malloc(10*sizeof(char));

strcpy(st,"hello");

printf("Stringis=%s",st);

st=(char*)realloc(st,25*sizeof(char));

strcat(st,"welcometobdps");

printf("\nNewstringis=%s",st);

free(st);

getch();

C Programming

Preprocessorstatements(or)preprocessordirectives
Preprocessorisaprogramthatprocessthesourcecodebeforeitprocessthroughthecompiler.
Thecommandsusedtocontroltheprocessorisknownaspreprocessordirectives.
Thesedirectivesaredividedinto3types.
1.fileinclusiondirectives.
2.macrosubstitutiondirectives.
3.compilercontroldirectives.

1.Fileinclusiondirectives
Itisusedtoincludeheaderfiles.Itprovidesinstructionstolinkthefunctionswiththeprogramfromthesystemlibrary.

#include"filename"

(or)

#include<filename>

whenthefilenameisincludedwithindoublequotationmarksthesearchforthefileismadefirstthecurrentdirectory
andthenthestandarddirectorywhenthefilenameisincludedwithinangularbracesthefilesearchonlyinthe
standarddirectory.

2.Macrosubstitutiondirectives
macroisaprocesswhereanidentifierinaprogramreplacedbyapredefinedstring(or)value.
#defineisapreprocessorstatementandisusedtodefinemacros.
syntax
#defineidentifierpredefinedstring(or)value
eg
#definepprintf

C Programming

#include<stdio.h>
#include<conio.h>
#definepprintf
#defineclsclrscr
#definegtgetch
#definevmvoidmain
vm()
{

cls();

p("Welcome");

gt();

#include<stdio.h>
#include<conio.h>
#definepprintf
#definesscanf
#defineclsclrscr
#definegtgetch
#definevmvoidmain
#definevalz100

vm()
{

intn;

cls();

p("Enteranyintegervalue:");

C Programming

s("%d",&n);

p("n=%d",n);

p("\nvalue=%d",val);

gt();

Macrowitharguments
Syntax
#defineidentifier(arg1,arg2,argn)definition
eg
#definesquare(x)x*x

#include<stdio.h>
#include<conio.h>
#definesquare(x)x*x
/*
intsquare(intx)
{

returnx*x;

}
*/
voidmain()
{

intn,s;

clrscr();

textmode(2);

printf("Enteranyinetegervalue:");

C Programming

scanf("%d",&n);

s=square(n);

printf("Squarevalueofgivennumber=%d",s);

getch();

#include<stdio.h>
#include<conio.h>
#definesquare(x)x*x
voidmain()
{

intn;

clrscr();

textmode(2);

n=100/square(5);

printf("n=%d",n);

getch();

FunctionMacro

1.Itisaselfcontainedblockofstatements1.Itisapreprocessorstatementstatements

2.Itsreplacesitsreturnvalue.2.Itreplacesitsdefinition

3.Wecanuseonlyspecifieddatatypesonly3.Datatypesaregeneric.

C Programming

4.Executiontimeismore.

4.Executiontimeisless.

5.Itrequireslessmemory.

5.Itrequiresmorememory.

#include<stdio.h>
#include<conio.h>
#definemaxval(x,y)x>y?x:y
voidmain()
{

inta,b,max;

clrscr();

printf("Enteranytwointegervalues:");

scanf("%d%d",&a,&b);

max=maxval(a,b);

printf("Maximumvalue=%d",max);

getch();

3.compilercontroldirectives
Thesedirectivesusedtocontrolthecompiler.
#if
#else
#elif(elseif)
#endif

#include<stdio.h>
#include<conio.h>
#definen10

C Programming

#ifn<=10

#defineval100

#else

#defineval200

#endif
voidmain()
{

clrscr();

printf("value=%d",val);

getch();

Structures

Definition
Agroupofdataitemsofdifferentdatatypesstoredinacontinuousmemorylocationisknownasastructure.
Struct:Itisakeywordandisusedtodeclareastructure.
Declarationofastructure

Form1

structstrut_name

datatypeitem1;

datatypeitem2;

datatypeitemn;

C Programming

};

eg

structemp

inteno;

charename[20];

floatsal;

};

Declarationofastructurevariable
structstruct_nameidentifier;
eg
structempe;
.(Accessoperator)
Itisusedtoaccessthedataitemsinthestructurewiththehelpofstructurevariable.
eg
e.eno
e.ename
e.sal
intn=100;
Intialisation
structstruct_nameidentifier={value1,......valuen};
eg
structempe={101,"abcd",5000};
Form2
Declarationofastructure&structurevariableinasinglestatement

C Programming

structstruct_name
{

datatypeitem1;

datatypeitem2;

datatypeitemn;

}va_list;
eg
structemp
{

inteno;

charename[20];

floatsal;

}e;
Initialisation
eg
structemp
{

inteno;

charename[20];

floatsal;

}e={101,"RAJU",50000};

#include<stdio.h>
#include<conio.h>
structemp

C Programming

inteno;

charename[80];

floatsal;

}e={300,"xyz",10000.00};
voidmain()
{

clrscr();

printf("Empnumber=%d",e.eno);

printf("\nEmpname=%s",e.ename);

printf("\nEmpsalary=%.2f",e.sal);

getch();

#include<stdio.h>
#include<conio.h>
structemp
{

inteno;

charename[80];

floatsal;

};
voidmain()
{

structempe;

clrscr();

textmode(2);

C Programming

printf("Enterempnumber:");

scanf("%d",&e.eno);

printf("Enterempname:");

fflush(stdin);

gets(e.ename);

printf("Entersalary:");

scanf("%f",&e.sal);

printf("Empnumber=%d",e.eno);

printf("\nEmpname=%s",e.ename);

printf("\nEmpsalary=%.2f",e.sal);

getch();

#include<stdio.h>
#include<conio.h>
structstudent
{

intsno,c,cpp,java,tot;

charsname[80],res[20],div[20];

floatavg;

};
voidmain()
{

structstudents;

clrscr();

textmode(2);

printf("Enterstudentnumber:");

scanf("%d",&s.sno);

C Programming

printf("Enterstudentname:");

fflush(stdin);

gets(s.sname);

printf("Entermarksinccppjava:");

scanf("%d%d%d",&s.c,&s.cpp,&s.java);

s.tot=s.c+s.cpp+s.java;

s.avg=(float)s.tot/3;

printf("Totalmarks=%d",s.tot);

printf("\nAverage=%.2f",s.avg);

if(s.c>=50&&s.cpp>=50&&s.java>=50)

strcpy(s.res,"pass");

printf("\nResult=%s",s.res);

if(s.avg>=70)

strcpy(s.div,"first");

printf("\nDivision=%s",s.div);

else

strcpy(s.div,"second");

printf("\nDivision=%s",s.div);

else

strcpy(s.res,"fail");

C Programming

printf("\nResult=%s",s.res);

strcpy(s.div,"NO_DIVISION");

printf("\nDivision=%s",s.div);

getch();

}
#include<stdio.h>
#include<conio.h>
structitem
{

intino;

chariname[80];

floatcost;

};
voidmain()
{

structitemit;

clrscr();

textmode(2);

printf("Enteritemnumber:");

scanf("%d",&it.ino);

printf("Enteritemname:");

fflush(stdin);

gets(it.iname);

printf("Entercost:");

scanf("%f",&it.cost);

C Programming

printf("Itemnumber=%d",it.ino);

printf("\nItemname=%s",it.iname);

printf("\nItemcost=%.2f",it.cost);

getch();

Arrayofstructures
Likeanyotherdatatypestructurearrayscanbedefined.sothateacharrayelementcanbeofstructuredatatype.
Foreg
structitem
{

intino;

chariname[80];

floatcost;

};
structitemit[20]definesanarraycalledit,thatcontains20elementseachelementisdefinedtobethestructitem.

#include<stdio.h>
#include<conio.h>
structitem
{

intino;

chariname[80];

floatcost;

};
voidmain()

C Programming

structitemit[20];

intn,i;

float*f,f1;

clrscr();

textmode(2);

f=&f1;

*f=f1;

printf("Enternumberofrecords:");

scanf("%d",&n);

for(i=0;i<n;i++)

printf("Enterrecord%d\n",i+1);

printf("Enteritemnumber:");

scanf("%d",&it[i].ino);

printf("Enteritemname:");

fflush(stdin);

gets(it[i].iname);

printf("Entercost:");

scanf("%f",&it[i].cost);

printf("%10s%15s%s","INO","INAME","COST");

printf("\n");

for(i=0;i<n;i++)

printf("\n%10d%15s%.2f",it[i].ino,it[i].iname,it[i].cost);

C Programming

getch();

Structuresandpointers
Apointercanalsopointtoastructure.
structitem
{

intino;

chariname[80];

floatcost;

};
structitemit;
structitem*p;
p=&it;
Aftermakingsuchanassignment,wecanaccesseverydataitemof"item"
structureindirectlythrough"p"asfollows:

(*p).ino

(*p).iname

(*p).cost

Hereinsteadofwriting"."and"*",weusethestructurepointer
operator"arrow>"whichisaminus("")followedby
greaterthansign(">").Thismeanswecanaccesseverydataitemof
"item"structuredirectlythrough"p"asfollows:

p>ino

C Programming

p>iname

p>cost

#include<stdio.h>
#include<conio.h>
structitem
{

intino;

chariname[80];

floatcost;

};
voidmain()
{

structitemit,*p;

float*f,f1;

clrscr();

f=&f1;

*f=f1;

p=&it;

/*

printf("Enteritemnumber:");

scanf("%d",&(*p).ino);

printf("Enteritemname:");

fflush(stdin);

gets((*p).iname);

printf("Entercost:");

scanf("%f",&(*p).cost);

indirectmethod

C Programming

printf("Itemnumber=%d",(*p).ino);

printf("\nItemname=%s",(*p).iname);

printf("\nItemcost=%.2f",(*p).cost);*/

/*

Directmethod*/

printf("Enteritemnumber:");

scanf("%d",&p>ino);

printf("Enteritemname:");

fflush(stdin);

gets(p>iname);

printf("Entercost:");

scanf("%f",&p>cost);

printf("Itemnumber=%d",p>ino);

printf("\nItemname=%s",p>iname);

printf("\nItemcost=%.2f",p>cost);

getch();

#include<stdio.h>
#include<conio.h>
structitem
{

intino;

chariname[80];

floatcost;

};
voidmain()

C Programming

structitem*it;

float*f,f1;

clrscr();

textmode(2);

f=&f1;

*f=f1;

it=(structitem*)malloc(sizeof(structitem));

printf("Enteritemnumber:");

scanf("%d",&it>ino);

printf("Enteritemname:");

fflush(stdin);

gets(it>iname);

printf("Entercost:");

scanf("%f",&it>cost);

printf("Itemnumber=%d",it>ino);

printf("\nItemname=%s",it>iname);

printf("\nItemcost=%.2f",it>cost);

getch();

#include<stdio.h>
#include<conio.h>
structitem
{

intino;

chariname[80];

C Programming

floatcost;

};
voidmain()
{

structitem*it;

intn,i;

float*f,f1;

clrscr();

textmode(2);

f=&f1;

*f=f1;

printf("Enternumberofrecords:");

scanf("%d",&n);

it=(structitem*)malloc(n*sizeof(structitem));

for(i=0;i<n;i++)

printf("Enterrecord%d\n",i+1);

printf("Enteritemnumber:");

scanf("%d",&(it+i)>ino);

printf("Enteritemname:");

fflush(stdin);

gets((it+i)>iname);

printf("Entercost:");

scanf("%f",&(it+i)>cost);

printf("%10s%15s%s","INO","INAME","COST");

printf("\n");

C Programming

for(i=0;i<n;i++)

printf("\n%10d%15s%.2f",(it+i)>ino,(it+i)>iname,(it+i)>cost);

getch();

FunctionsandStructures
Passingastructureasafunctionargument(or)parameter.
Likeanyotherdatatype,astructuremaybeusedasfunctionargument.
Returningastructure
Afunctioncannotonlyreceiveastructureasitsargumentsbutalsocanreturnthem.

#include<stdio.h>
#include<conio.h>
structemp
{

inteno;

charename[80];

floatsal;

};
structempaccept()
{

structempe;

printf("Enterempnumber:");

scanf("%d",&e.eno);

printf("Enterempname:");

C Programming

fflush(stdin);

gets(e.ename);

printf("Entersalary:");

scanf("%f",&e.sal);

returne;

}
voiddisp(structempe)
{

printf("Empnumber=%d",e.eno);

printf("\nEmpname=%s",e.ename);

printf("\nEmpsalary=%.2f",e.sal);

}
voidmain()
{

structempe;

clrscr();

textmode(2);

e=accept();

disp(e);

getch();

Nestedstructures(or)structurewithinstructure
Form1
DeclaringastructurewithinanotherstructureisknownasNestedstructure.

C Programming

structstudentAccessingdataitems
{

intsno,c,cpp,java;s.sno

charsname[80];s.sname

structresults.c

{s.cpp

inttot;s.java

floatavg;s.r.tot

charres[20],div[20];s.r.avg

}r;s.r.res

}s;s.r.div

Form2
Declaringstructurevariablewithinanotherstructureisknownasnestedstructure.

Accessingdataitems

structstudent
{r.s.sno

intsno,c,cpp,java;r.s.sname

charsname[80];r.s.c

};r.s.cpp
structresultr.s.java
{r.tot

structstudents;r.avg

inttot;r.res

C Programming

floatavg;r.div

charres[20],div[20];

}r;

#include<stdio.h>
#include<conio.h>
structstudent
{

intsno,c,cpp,java;

charsname[80];

structresult

inttot;

charres[20],div[20];

floatavg;

}r;

}s;
voidmain()
{

structstudents;

clrscr();

printf("Enterstudentnumber:");

scanf("%d",&s.sno);

printf("Enterstudentname:");

fflush(stdin);

gets(s.sname);

printf("Entermarksinccppjava:");

C Programming

scanf("%d%d%d",&s.c,&s.cpp,&s.java);

s.r.tot=s.c+s.cpp+s.java;

s.r.avg=(float)s.r.tot/3;

printf("Totalmarks=%d",s.r.tot);

printf("\nAverage=%.2f",s.r.avg);

if(s.c>=50&&s.cpp>=50&&s.java>=50)

strcpy(s.r.res,"pass");

printf("\nResult=%s",s.r.res);

if(s.r.avg>=70)

strcpy(s.r.div,"first");

printf("\nDivision=%s",s.r.div);

else

strcpy(s.r.div,"second");

printf("\nDivision=%s",s.r.div);

else

strcpy(s.r.res,"fail");

printf("\nResult=%s",s.r.res);

strcpy(s.r.div,"NO_DIVISION");

printf("\nDivision=%s",s.r.div);

C Programming

getch();

unions
Wnionissimilartostruct,exceptitallowsyoudefinevariablesthatsharestoragespace.
syntax
unionunion_name
{

datatypeitem1;

datatypeitem2;

datatypeitemn;

}va_list;

Differencesbetweenstructandunion

struct

union

1.Agroupofdataitemsthatbelongs1.Itisalsosameasstructure.butonly
todifferentdatatypes.

majordifferenceismemoryallocation.

2.Itallocates thememoryofall2.Itallocatesmemoryofbiggestdataitem
declareddataitemsinit.

init.

3.Wecanaccessalldataitemsata3.Wecanaccessonlyonedataitemata
time.

time.

C Programming

4.Eachandeverydataitemhasits4.Alldataitemsaresharedcommonstorage
ownstoragespace.

space.

#include<stdio.h>
#include<conio.h>
unionemp
{

inteno;

charename[80];

floatsal;

};
voidmain()
{

unionempe;

clrscr();

printf("Enterempnumber:");

scanf("%d",&e.eno);

printf("Empnumber=%d",e.eno);

printf("\nEnterempname:");

fflush(stdin);

gets(e.ename);

printf("Empname=%s",e.ename);

printf("\nEntersalary:");

scanf("%f",&e.sal);

printf("Empsalary=%.2f",e.sal);

C Programming

getch();

FILES

Clanguagepermitstheusageoflimitedinputandoutputfunctionstoreadandwritedata.Thesefunctionsareused
foronlysmallervolumesofdataanditbecomesdifficulttohandlelargedatavolumes.Alsotheentiredataislost
whentheprogramisover.
Toovercomethesedifficulties,aflexiblemethodwasdevelopedbyemployingtheconceptofFILEStostore,toread
ortowritedataandtoreturnthemevenwhentheprogramisrunning.

Definitionoffile
Afileisone,whichenabletheusertoread,writeandstoreagroupofrelateddata.

(or)

Afileisacollectionofrelateddatastoredinparticularareaonthedisk.

'C'supportsanumberoffunctionstohavetheabilitytoperformthebasicfileoperationswhichincludethefollowing
Namingafile
Openingafile
Readingdatafromthefile
Writingdatatothefile
Closingthefile

FILE:Itisapredefinedstructureandisusedtodeclareafilepointer.

Usingthispointer,wecanperformallfileoperations.

Declaration:

FILE*identifier;

C Programming

eg:

FILE*fp;

fopen():

Itopensafilestream.

Declaration:

FILE*fopen(constchar*filename,constchar*mode);

filenamespecifiesthefiletobeopened.

modestringusedtoaccesafileindifferentmodes

String

Description

Opensthefileforreadingpurposeonly

Createsanewfileforwritingpurpose

Ifafilebythatnamealreadyexists,itwillbeoverwritten

aOpenforwritingattheendofthefile(or)

Createsanewfileforwritingifthefiledoesnotexist

r+

Openanexistingfileforreadingandwritingpurpose

w+

Createsanewfileforreadingandwritingpurpose

Ifthefilebythatnamealreadyexists,itwillbeoverwritten

a+openforupdationattheendoffile(or)

Createanewoneifthefiledonotexist

C Programming

Tospecifythatagivenfileisbeingopenedorcreatedintextmode,append't'tothestring(rt,at,r+t,w+tetc.)
Tospecifybinaryfile,append'b'tothestring
(wb,ab,r+b,a+betc.)

fclose()

Itclosesafilestream.

Declaration:

intfclose(FILE*stream);

fcloseall()

Itclosesallopenedstreams.

Declaration:

intfcloseall(void);

getc:

getcisamacrothatgetsonecharacterfromafilestream

Declaration:

intgetc(FILE*stream);

putc:

putcisamacrothatoutputsacharactertoafilestream

Declaration:

intputc(intc,FILE*stream);

fgetc():

Itisafunctionwhichgetsacharacterfromafilestream.

Declaration:

intfgetc(FILE*stream);

C Programming

fputc():

fputcoutputsacharactertoafilestream

Declaration:

intfputc(intc,FILE*stream);

EOF(ASCIIValue26)

Aconstantindicatingthatendofthefilehasbeenreached.Toget

thischaracterfromkeyboardpress"ctr+z"

#include<stdio.h>
#include<conio.h>
voidmain()
{

FILE*fp;

charch;

clrscr();

textmode(2);

printf("Entertextdataintofile(ctrl+z)tostop\n");

fp=fopen("a.txt","w");

ch=getchar();

while(ch!=EOF)

putc(ch,fp);

ch=getchar();

fclose(fp);

printf("Datastoredsuccesfully");

C Programming

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

FILE*fp;

charch;

clrscr();

textmode(2);

printf("Enterfilenametodisplay:");

gets(fname);

fp=fopen("a.txt","r");

printf("Readingdatafromfile\n");

ch=getc(fp);

while(ch!=EOF)

printf("%c",ch);

delay(10);

ch=getc(fp);

fclose(fp);

getch();

C Programming

fgets
fgetsgetsastringfromastream.
Declaration
char*fgets(char*s,intn,FILE*stream);

Remarks
fgetsreadscharactersfromstreamintothestrings.Itstopswhenitreadseithern1charactersoranewline
character,whichevercomesfirst.
fputs
fputsoutputsastringtoastream
declaration
intfputs(constchar*s,FILE*stream);

Remarks
fputscopiesthenullterminatedstringstothegivenoutputstream.Itdoesnotappendanewlinecharacter,andthe
terminatingnullcharacterisnotcopied.

feof
Macrothattestsifendoffilehasbeenreachedonastream.
Declaration
intfeof(FILE*stream);
reurnvalue
returnsnonzeroifanendoffileindicatorwasdetected

#include<stdio.h>
#include<conio.h>
voidmain()
{

C Programming

FILE*fp;

charst[80];

clrscr();

fp=fopen("str.txt","w");

printf("Enterstringdataintofile('end'tostop)\n");

gets(st);

while(strcmp(st,"end")!=0)

fputs(st,fp);

fputs("\n",fp);

gets(st);

fclose(fp);

printf("Datastoredsuccessfully");

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

FILE*fp;

charst[80];

clrscr();

textmode(2);

fp=fopen("str.txt","r");

printf("Readingstringdatafromfile\n");

C Programming

fgets(st,80,fp);

while(feof(fp)==0)

printf("%s",st);

fgets(st,80,fp);

delay(10);

fclose(fp);

getch();

rewind
Repositionsfilepointertostream'sbeginning.
Declaration
voidrewind(FILE*stream);

#include<stdio.h>
#include<conio.h>
#include<dos.h>
voidmain()
{

FILE*fp;

charch;

clrscr();

textmode(2);

printf("Entertextdataintofile(ctrl+z)tostop\n");

fp=fopen("a.txt","a+");

C Programming

ch=getchar();

while(ch!=EOF)

putc(ch,fp);

ch=getchar();

printf("Datastoredsuccesfully");

printf("Readingdatafromfile\n");

rewind(fp);

ch=getc(fp);

while(ch!=EOF)

printf("%c",ch);

delay(10);

ch=getc(fp);

fclose(fp);

getch();

fprintf
declaration
intfprintf(FILE*stream,constchar*format[,argument,...]);

fscanf
declaration
intfscanf(FILE*stream,constchar*format[,address,...]);

C Programming

Note
Infprintf(or)fscanfbetweenformatspecifiersatleastonespaceisnecessary.

#include<stdio.h>
#include<conio.h>
voidmain()
{

FILE*fp;

inteno;

charename[80];

floatsal;

clrscr();

fp=fopen("emp.txt","w");

printf("Enterempnumber:");

scanf("%d",&eno);

printf("Enterempname:");

fflush(stdin);

gets(ename);

printf("Entersalary:");

scanf("%f",&sal);

fprintf(fp,"%d%s%f",eno,ename,sal);

fclose(fp);

printf("Recordstoredsuccessfully");

getch();

C Programming

#include<stdio.h>
#include<conio.h>
voidmain()
{

FILE*fp;

inteno;

charename[80];

floatsal;

clrscr();

fp=fopen("emp.txt","r");

printf("Readingdatafromfile\n");

fscanf(fp,"%d%s%f",&eno,ename,&sal);

printf("Empnumber=%d",eno);

printf("\nEmpname=%s",ename);

printf("\nEmpsalary=%.2f",sal);

fclose(fp);

getch();

#include<stdio.h>
#include<conio.h>
voidmain()
{

FILE*fp;

inteno;

charename[80],ch;

floatsal;

C Programming

clrscr();

textmode(2);

fp=fopen("emp.txt","a+");

do

printf("Enterempnumber:");

scanf("%d",&eno);

printf("Enterempname:");

fflush(stdin);

gets(ename);

printf("Entersalary:");

scanf("%f",&sal);

fprintf(fp,"%d%s%f\n",eno,ename,sal);

printf("Recordstoredsuccessfully\n");

printf("Doyouwanttocontinue(y/n):");

fflush(stdin);

scanf("%c",&ch);

}while(ch!='n');

printf("%10s%15s%s","ENO","ENAME","SALARY");

printf("\n");

rewind(fp);

while(feof(fp)==0)

fscanf(fp,"%d%s%f\n",&eno,ename,&sal);

printf("\n%10d%15s%.2f",eno,ename,sal);

fclose(fp);

C Programming

getch();

ftell
Returnsthecurrentfilepointerposition.
Declaration
longftell(FILE*stream);

fseek
Repositionsthefilepointerofastream
Declaration
intfseek(FILE*stream,longoffset,intwhence);
offset
Differenceinbytesbetweenoffsetandwhence.
whence
SEEK_SET0seeksfrombeginingoffile
SEEK_CUR1seeksfromcurrentposition
SEEK_END2seeksfromendoffile

#include<stdio.h>
#include<conio.h>
voidmain()
{

FILE*fp;

charch;

clrscr();

textmode(2);

C Programming

fp=fopen("a.txt","w");

printf("Currentfilepointerposition=%ld",ftell(fp));

printf("\nEntertextdataintofile\n");

ch=getchar();

while(ch!=EOF)

putc(ch,fp);

ch=getchar();

printf("Presentfilepointerposition=%ld",ftell(fp));

fseek(fp,2,1);

printf("\nNewfilepointerposition=%ld",ftell(fp));

fclose(fp);

getch();

Binaryfiles
putw
Itoutputsanintegeronastream.
declaration
intputw(intw,FILE*stream);

getw
getwgetsanintegerfromstream.
declaration
intgetw(FILE*stream);

C Programming

#include<stdio.h>
#include<conio.h>
voidmain()
{

FILE*fp;

intn;

clrscr();

textmode(2);

fp=fopen("num.dat","a+b");

printf("Enternumberdataintofile(0tostop)\n");

scanf("%d",&n);

while(n!=0)

putw(n,fp);

scanf("%d",&n);

printf("Datastoredsuccessfully");

rewind(fp);

printf("\nNumberdatafromfile\n");

n=getw(fp);

while(n!=EOF)

printf("%d\n",n);

n=getw(fp);

fclose(fp);

getch();

C Programming

fwrite
Itappendsspecifiednumberofequalsizedataitemstoanoutputfile.
Declaration
size_tfwrite(constvoid*ptr,size_tsize,size_tn,FILE*stream)

fread
Itreadsaspecifiednumberofequalsizeddataitemsfromaninputstreamintoablock.
Declaration
size_tfread(void*ptr,size_tsize,size_tn,FILE*stream);
ArgumentWhatItIs/Does

ptrPointstoablockintowhichdataisread
sizeLengthofeachitemread,inbytes
nNumberofitemsread
streamPointstoinputstream

#include<stdio.h>
#include<conio.h>
structemp
{

inteno;

charename[80];

floatsal;

};
voidmain()

C Programming

structempe;

FILE*fp;

clrscr();

fp=fopen("emp.dat","wb");

printf("Enterempnumber:");

scanf("%d",&e.eno);

printf("Enterempname:");

fflush(stdin);

gets(e.ename);

printf("Entersalary:");

scanf("%f",&e.sal);

fwrite(&e,sizeof(e),1,fp);

fclose(fp);

printf("RecordstoredSuccesfully");

getch();

#include<stdio.h>
#include<conio.h>
structemp
{

inteno;

charename[80];

floatsal;

};
voidmain()

C Programming

structempe;

FILE*fp;

clrscr();

fp=fopen("emp.dat","rb");

fread(&e,sizeof(e),1,fp);

printf("Empnumber=%d",e.eno);

printf("\nEmpname=%s",e.ename);

printf("\nEmpsalary=%.2f",e.sal);

fclose(fp);

getch();

}
#include<stdio.h>
#include<conio.h>
structemp
{

inteno;

charename[80];

floatsal;

};
voidmain()
{

structempe;

FILE*fp;

charch;

clrscr();

fp=fopen("emp.dat","a+b");

C Programming

do

printf("Enterempnumber:");

scanf("%d",&e.eno);

printf("Enterempname:");

fflush(stdin);

gets(e.ename);

printf("Entersalary:");

scanf("%f",&e.sal);

fwrite(&e,sizeof(e),1,fp);

printf("RecordStoredsuccessflluy\n");

printf("Douwanttocontinue(y/n):");

fflush(stdin);

scanf("%c",&ch);

}while(ch!='n');

rewind(fp);

printf("%10s%15s%s","ENO","ENAME","SALARY");

printf("\n");

fread(&e,sizeof(e),1,fp);

while(!feof(fp))

printf("\n%10d%15s%.2f",e.eno,e.ename,e.sal);

fread(&e,sizeof(e),1,fp);

fclose(fp);

getch();

C Programming

Commandlinearguments

Itisparametersuppliedtoaprogramwhentheprogramisinvocked.Thisparametermayrepresentafilename,the
programshouldprocess.commandlineargumentsaretypedbytheuser.Thefirstargumentisalwaysthefilename.we
knowthatevery'c'programshouldhaveonemainfunctionanditcantakeargumentslikeotherfunctions.Ifyouwant
toworkwithcommandlineargumentsthemainfunctioncantake2argumentscalledargc,argv.andtheinformation
obtainedinthecommandlineisprocessedontotheprogramthroughthesearguments.Thevariableargcisan
argumentcounterthatcountsthenumberofargumentsonthecommandline.Theargvisanargumentvectorand
representsanarrayofcharacterpointersthatpointstothecommandlinearguments.thesizeofthisarraywillbe
equaltothevalueofargc.

#include<stdio.h>
#include<conio.h>
voidmain(intargc,char*argv[])
{

inti;

printf("Numberofarguments=%d",argc);

for(i=0;i<argc;i++)

printf("\nargv[%d]=%s",i,argv[i]);

Вам также может понравиться