Vous êtes sur la page 1sur 419

CLanguage

Computer:

Itisanelectronicdevice,Ithasmemoryanditperforms
arithmeticandlogicaloperations.

Computerfullform

Commonly Operated Mechine Particurly Used for


TradeEducationandResearch.
(or)

Commonly Operating MechinePerforming Users


TechnologiesandEducationalResearch.

Input:

Thedataenteringintocomputerisknownasinput.

Output:

The resultant information obtained by the computer is


knownasoutput.

Program:


Asequenceofinstructionsthatcan beexecutedbythe
computer to solve the given problem is known as
program.

Software:

A set of programs to operate and controls the operation
ofthecomputerisknownassoftware.
theseare2types.
1. Systemsoftware.
1. Applicationsoftware.

SystemSoftware:

Itisusedtomanagessystemresources.

Eg
:
OperatingSystem.

Operatingsystem:

Itisaninterfacebetweenuserandthecomputer.Inother
words operating system is a complex set of programs
which manages the resources of a computer. Resources
include input, output, processor,memory,etc. So it is
calledasResourceManager.

Eg:
Windows98,WindowsXp,Windows7,Unix,
Linux,etc.

ApplicationSoftware:

ItisUsedtodeveloptheapplications.
Itisagainof2types.
1 Languages
1 Packages.
Language:

Itconsistsofsetofexecutableinstructions.Usingthese
instructions we can communicate with the computer and
gettherequiredresults.

Eg:
C,C++,Java,etc.

Package:

It is designed by any other languages with limited


resources.

Eg:
MSOffice,AccountPackage,etc.

Hardware:


All the physical components or units which are
connectingtothecomputercircuitisknownasHardware.

ASCIIcharacterSet
ASCII American Standard Code for Information
Interchange
Thereare256distinctASCIIcharactersareusedbythe
micro computers. These values range from 0 to 255.
Thesecanbegroupedasfollows.
CharacterType
NoofCharacters

CapitalLetters(AtoZ)
26

SmallLetters(atoz)
26

Digits(0to9)
10

SpecialCharacters
32

ControlCharacters
34

GraphicCharacters
128

Total
256

Out of 256, the first 128 are called as ASCII character


set and the next 128 are called as extended ASCII
character set. Each and every character has unique
appearance.

Eg:
AtoZ 65to90
atoz
97to122
0to9
48to57
Esc
27
Backspace 8
Enter
13
SpaceBar
32
Tab
9
etc.

Classificationofprogramminglanguages:

Programminglanguagesareclassifiesinto2types
1. Lowlevellanguages
1. Highlevellanguages

Lowlevellanguages:

It is also known as Assembly language and


was designed in the beginning. It has some
simple instructions. These instructions are not
binary codes, but the computer can understand
only the machine language, which is in binary
format. Hence a converter or translator is used
to translate the low level language instructions
into machine language. This translator is called
as
assembler.

Highlevellanguages:

These are more English like languages and


hence the programmers found them very easy
to learn. To convert high level language
instructions to machine language
compilers
andinterpreters
areused.

Translators:
These are used to convert low or high level
language instructions to machine language with
the help of ASCII character set. There are 3
typesoftranslatorsforlanguages.

Assembler:
It is used to convert low level language
instructionsintomachinelanguage.

1) Compiler:

It is used to convert high level


instructions into machine language. It
checks for the errors in the entire program
and converts the program into machine
language.
1)

3)
Interpreter:

It is also used to convert high level


language instructions into machine language,
But It checks for errorsbystatementwiseand
convertsintomachinelanguage.

Debugging:

The process of correcting errors in the


programis
calledasdebugging.


Various Steps involved in program
development:

There are 7 steps involved in program


development.

1) Problemdefinition:

Defininga problemisnothingbutunderstanding
the problem. It involves 3 specifications
regardingaproblemsolution.
1 Inputspecification
1 Outputspecification
1 Processing

2)Analysisanddesign:

Before going to make final solution for the


problem, the problemmust beanalyzed.Outline
solution is prepared for the simple problems. In
case of complex problems, the main problem is
divided into sub problems called as
modules.

Each module can be handled and solved


independently. When the task is too large, it is
always better todividethe problemintonumber
of modulus and seek solution for individual
module.

3.Algorithm:

A step by step procedure to solve the given


problemis called as algorithm. Analgorithmcan
be described in a natural language such as
English.

4.Flowchart:

A symbolic or graphical representation of given


algorithmiscalledasflowchart.

5.Codingandimplementation:

Coding is a process of converting the


algorithm or flow chart into computer program.

In this process each and every step of an


algorithm will be converted into instructions of
selectedcomputerprogramminglanguage.
Before selecting a programminglanguagewe
mustfollowthefollowing3considerations.
a)Natureofprogram.

b)

Programming language available on


Computersystem.

c)
Limitationsofthecomputer.

6.Debuggingandtesting:

Before loading the program into computer,


we must locate and correct all the errors. The
process of correcting errors in a program is
calledasdebugging.
There are 3 types of errors that generally occur
inaprogram.
a)Syntaxerrors
b)Runtimeerrors
c)Logicalerrors

It is very important to test the program


written to achieve a specific task. Testing

involves running the program with known data


of which the results are known. As the results
are known, the results produced by the
computercanbeverified.

7.Documentation:

It is the most important aspect of


programming. Itisacontinuousprocesstokeep
the copyof allthephasesinvolvedinaproblem
definition,, debugging and testing are
parts of documentation. This phase involves to
producingawrittendocumentfortheuser.

Algorithms:

1)To find addition, subtraction, multiplication,


divisionandmodulusofgiven2numbers.
Steps:
1.
start
2.ReadTwoNumbersAandB
3.add=A+B

1.
1.
1.
2.
3.
4.

sub=AB
mul=A*B
div=A/B
mod=A%B
printadd,sub,mul,divandmod
stop.

2)Tofindmaximumvalueofgiven2numbers.

Steps:

1. start
1. ReadAandB
1. max=A
1. if(max<B)thenmax=B
1. printmax
1. stop

3)Tofindmaximumvalueofgiven3numbers.

Steps:

1. start
1. ReadA,BandC
1. max=A
1. if(max<B)thenmax=B
1. if(max<C)thenmax=C

1.
1.

printmax
stop

4)Tocheckwhetherthegivennumberisevenorodd.

Steps:

1. start
1. Readn
1. if(n%2=0) then print "Given number is even
elseprint"Givennumberisodd"
2. stop

5)Todisplaynnaturalnumbers.

Steps:

1. start
1. Readn
1. i=1
1. printi
1. i=i+1
1. if(i<=n)thengotostep4
1. stop

6)Todisplaythesumofnnaturalnumbers.

Steps:

1. start
1. Readn
1. sum=0,i=1
1. sum=sum+i
1. i=i+1
1. if(i<=n)gotostep4
1. printsum
1. stop

7)Tofindfactorialofagivennumber.

Steps:

1. start
1. Readn
1. fact=1
1. fact=fact*n
1. n=n1
1. if(n>=1)thengotostep4
1. printfact
1. stop

8)Tofindreversenumberofagivennumber.

Steps:

1. start
1. Readn
1. rev=0
1. rev=(rev*10)+(n%10)
1. n=n/10
1. if(n>0)thengotostep4
1. printrev
1. stop

9)

Steps:

1. start
1. Readn
1. rev=0,m=n
1. rev=(rev*10)+(m%10)
1. m=m/10
1. if(m>0)thengotostep4
2. if(n=rev)thenprint"GivenNumberisPalindrome"
elseprint"GivenNumberisnotPalindrome"

1. stop

IntroductiontoC:

C isprogramminglanguage. Itisdesigned by
Dennis

Ritchie
in 1972 at AT &T(American Telephones and
Telegraphs)BELLlabsinUSA.

It is the most popular general purpose programming


language. We can use the 'C' lnaguage to implement any
type of applications.Mainly we are using C language to
implement
system softwares. These are compilers
,editors,drivers,databasesandoperatingsystems.

HistoryofCLanguage:

In 1960's COBOL was being used for commercial


applications and FORTRAN is used for scientific and
engineering applications. At this stage people started to
develop a language which is suitable for all possible

applications. Therefore an international committee was


setup to develop such a language " ALGOL 60 " was
released. It was not popular , because it seemed too
general. To reduce these generality a new language
CPL(combined programming language) was developed at
Cambridge University. It has very less features. Then some
other features were added to this language and a new
language called BCPL(Basic combined programming
language) developed by "Martin Richards" at Cambridge
University. Then " B " language was developed by Ken
ThompsonatAT&TBELLlabs.

DennisRitchieinheritedthefeaturesofBandBCPL,
added his own features and developed C language in
1972.

FeaturesofCLanguage:

1.
C is a structured programming language
withfundamentalflowcontrolconstruction.

2.Cissimpleandversatilelanguage.

3.ProgramswritteninCareefficientandfast.

4.Chasonly32keywords.


5.C ishighlyportableprogramminglanguage.
The programswritten for onecomputercan
be run on another with or without any
modifications

6.

Chasrichsetofoperators.

7.
C permits all data conversions and
mixedmodeoperations

8.
Dynamic memory allocation(DMA) is
possibleinC.

9.
Extensive varieties of datatypes suchas
arrays, pointers, structures and unions are
availableinC.

10. C improves by itself. It has several


predefine
functions.

11. C easily manipulates bits, bytes and

addresses.

12. Recursive function calls for algorithmic


approachispossibleinC.

13. Mainly we are using C language to


implement

system softwares. These are compilers


,editors,
drivers,databasesandoperatingsystems.

14. C compiler combines thecapability of an


assembly level language with the features
of high level language. So it is called as
middlelevellanguage.

Importantpoints:
1 . C wasbasicallydesignedforUnixoperating
system. 93% of instructions, which are
writteninC.

.Ciscasesensitiveprogramminglanguae.C
statements are entered in
lower case
lettersonly.
. C is function oriented programming
language. Any C program contains one or
more functions . Minimum One function is
compulsory by the name called
main.
WithoutmainwecantexecuteaCprogram.
. Every C statement must be terminated by
semicolon ( ; ), except preprocessor
statementsandfunctiondefinition.
.A function is representedby functionname
withapairofparenthesis().

BlockdiagramofexecutionofCprogram:


Once the program is completed, the program is feed
into the computer using the compiler to produce
equivalent machine language code. In C program
compilationthereare2mechanisms.
1. Compiler
1. Linker.

The Compiler receives the source file as inputand


convertsthatfileintoobjectfile.Thenthe
Linker
receives
the object file as its input and linking with C libraries.
After linking it produces an executable file for the given
code. After creation of executable file, then start the
program execution and loads the information of the
program into primary memory through LOADER. After
loading the information the processor processing the
informationandgivesoutput.

BasicstructureofCprogram

[Documentsection]

Preprocessorsection
(or)
Linksection

[Globaldeclarationsection]

main()
{

[Localdeclarationsection]

Statements
}

[Subprogramsection]
(includeuserdefinedfunctions)

Documentsection:

Itconsistsasetofcommentlinesgivingthenameof
the program, author name and some other details about
theentireprogram.

PreprocessorSection(or)Linksection:

It provides instructions to the compiler to link the


functionsfromthesystemlibrary.

GlobaldeclarationSection:

The Variables that are used in morethanonefunction


are called as global variables and these are declared in
globaldeclarationsection.

Main
function
section:

Every C program must have one function. i.e. main


function.Thissectioncontains2parts.
1. Localdeclarationsection.
1. Statements.
The Local declaration section declares all the variables
used in statements. The statements part consists a
sequence of executable statements.These 2 parts must
appear between opening and closing curly braces. The
program execution begins at the opening brace and ends
atclosingbrace.

Subprogrammingsection:
Itcontainsalltheuserdefinedfunctions.
Thissectionmaybeplacedbeforeoraftermainfunction.

Comments:

Unexecutable lines in a program are called as


comments.Theselinesareskippedbythecompiler.

/*

*/Multilinecomment.

//
single line comment(C++
comment).

Preprocessorstatements:

The preprocessor is a program that process the source


codebeforeitpassesthroughthecompiler.

#include:

Itispreprocessorfileinclusiondirectiveandisusedto
include header files. It provides instructions to the
compilertolinkthefunctionsfromthesystemlibrary.

Syntax:

#include"file_name"
(or)
#include<file_name>

Whenthefilenameisincludedwithinthedouble
quotationmarks, thesearchforthefileismadefirstinthe

currentdirectoryandthenthestandarddirectories(TC).

When the file name is included within angular


braces,thefileissearchonlyinstandarddiretories(TC).

stdio.h:standardinputandoutputheaderfile.
conio.h:consoleinputandoutputheaderfile.
consoleunits:keyboardandmonitor.

These 2 headers are commonly included in all C


programs.

If you want to work with Turbo c/c++ ,first install


Turboc/c++
softwareandthenfollowthefollowingsteps.

StepsinvolvedinCprogramming:

1)HowtoopenaCeditor:

1. Start Menu
Run
type C:\TC\Bin\TC.exe then
pressEnterkey
2. At the time of installation create Shortcut to C on
Desktop, then it will create an icon(TC++3.0) on
desktop.Doubleclickonthaticon.

2)AfterenteringintoCeditor,checkthepathas:
gotoOptionsmenu

Directories

1. C:\TC\Include
1. C:\TC\Lib
1.
1.

3)TypeCprogramas,gotoFilemenu

New

4)Saveprogramas,gotoFilemenu

Save

5)CompileProgramas,gotoCompilemenu

Compile

6)RuntheProgramas,gotoRunmenu

Run

7)Seetheoutputas,gotoWindowmenu

Userscreen

8)ExitfromCeditoras,gotoFilemenu

Quit

ShortcutKeys:

Open
:
F3

Save
:
F2

Closefile
:
Alt+F3

FullScreen
:
F5

Compile
:
Alt+F9

Run
:
Ctrl+F9

Output
:
Alt+F5

Changetoanotherfile:
F6

Help
:
Ctrl+F1

Tracing:F7

Quit
:
Alt+X

printf:
It is afunctionandis usedtoprintdataonthestandard
outputdevice(monitor).

Syntax:
formatstring

int
pritntf(control
string
[,arg1,arg2,.argn])


Eg:
printf(WelcometoCProgramming)

Program:

/*FirstProgram*/
#include<stdio.h>
#include<conio.h>
voidmain()
{
printf(WelcometoCPrograsmming)
}

clrrscr
:

Itclearstextmodewindow.

syntax:
voidclrscr()

getch:

It is a function and it gets a character from standard
inputdevice,butitdoesnotechotothescreen.

Syntax:
intgetch()

Escapesequencecharacters:
Cusessomebackslashcharactersinoutputfunctionsfor
formating the output.ThesecharacterarecalledasEscape
sequencecharacters.
In these characters it consists of two characters ,But it is
treatedasasinglecharacter.

\nnewline
\thorizontaltab(default8spaces)
\vverticaltab(default1line)
\bbackspace
\aalert(beepsound)(ASCIIvalueof\ais7)
\rCarriagereturn
\fformfeed
\0null
\"doublequotes

Program:

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

{
printf(Welcome\n)
printf(GoodMorning)
}

Output:

Welcome
GoodMorning

Program
:esc_b.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
printf(Welcome\b)
printf(GoodMorning)
}

Output:

WelcomGoodMorning

Program:
esc_r.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
printf(GoodMorning\r)
printf(Welcome)
}

Output:

Welcomerning

CTokens:

Thesmallestindividualelementsorunitsinaprogram
arecalledasTokens.Chasfollowingtokens.

1 Identifiers
1 Keywords
1 Constants
1 Operators
1 Specialcharacters

Identifiers:

Identifiers refer to the name of the variables,


functions, arrays,etc. created by the user or programmer,

usingthecombinationoffollowingcharacters.

1 Alphabets:AtoZ(or)atoz
1 Digits:0to9
1 Underscore:_

Note:
1 . The first character of an identifier must be an
alphabetorunderscore,wecanotusedigit.
1 .Defaultidentifierlengthis32characters.

Keywords
Keywords are the words whose meaning has been
alreadyexplainedbythecompiler.Thatmeansatthetime
of designing a language, some words are reserved to do
specific tasks. Such words are called as keywords (or)
reservedwords.AllCcompilerssupport32keywords.
Theyare:
1. auto
1. break
1. case
1. char
1. const
1. continue
1. default
1. do

1.
1.
1.
1.
1.
1.
1.
1.
1.
1.
1.
1.
1.
1.
1.
1.
1.
1.
1.
1.
1.
1.
1.
1.

double
else
enum
extern
float
far
for
goto
if
int
long
register
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
while

constants:

constantsdefinefixedvalues,thatdonotchangeduring
the execution of program. C supports the following
constants.
1 Integerconstants
1 Characterconstants
1 Realorfloatingconstants
1 Stringconstants

Operators:

Operator is a symbol which performs particular


operation. C supports a rich set of operators. C operators
can be classified into No of categories. They include
arithmetic operators, logical operators, bitwise operators,
etc.

Specialcharacters:

All characters other than alphabets and digits are


treatedasspecialcharacters.
Eg:
*,%,$,{,etc.

DatatypesinC:

The kind of data that variables may hold in a

programming language are called as data types. C data


typescanbeclassifiesinto3categories.
1 Primarydatatypes
1 Deriveddatatypes
1 Userdefineddatatypes

Primarydatatypes:

AllCcompilersupports4fundamentaldatatypes.
Namelyint,char,floatanddouble.

int: It is positive, negative and whole values but not a


decimalnumber.
Eg:
10,20,30,0etc.

char: A single character can be treated as character data


typeandisdefinedbetweensinglequotationmarks.
Eg:
r,H,5,*,etc.

Note: String is also a character data type. A group of


characters defined between double quotation marks is a
String.

Eg:
HHHH,abc985,etc.

float: The numbers which are stored in the form of

floatingpointrepresentationiscalledasfloatdatatype.

Eg:
10.25,478.1234,56.37821,etc.

double: The numbers which are stored in the form of


double
precisionfloatingpointrepresentationiscalledasdouble
datatype.

Eg:
1023.56789,12345.56789,0.456321,567.4556etc.

Deriveddatatypes:

These data types are created from the basic integers,


charactersandfloatingdatatypes.
Eg:

arrays,pointers,structuresetc.

Userdefineddatatypes:
Theuserdefineddatatypesenableaprogramtoinvent
hisowndatatypesanddefinewhatvaluesitcantakenon.
Thus these data types can helpaprogrammertoreducing
programmingerrors.
Csupports2typesofuserdefineddatatypes.
1 typedef(typedefinition)
1 enum(enumerateddatatype)

Typemodifiers:
(signed,unsigned,short,long)

Atypemodifiersalertthemeaningofthebasedatatype
toyieldanewtype.
1 Each of these type modifiers can be applied to the
basetype
int
.

2 Type modifiers signed and unsigned can also be


appliedtothe
basetype
char.

3Inaddition,long

canbeappliedto
double.

Sub classification of Primary data types, format


specifiers,memorysizeandtheiraccessibilityrange:

Datatype
FormatSpecMemsize

Accessbilityrange

unsignedchar
%c 1Byte 0to255

char
%c 1Byte 128to127

int

%d
2 Bytes
32768 to

32767

unsignedint
%u
2Bytes 0to65535

long(or)
%ld
4Bytes
2147483648 to
2147483647
longint

unsignedlong(or)
%lu
4Bytes
0 to
4294967295
unsignedlongint

float
%f
4Bytes
3.4*(10power
38)

to

3.4*(10
power38)

double
%lf
8Bytes
1.7*(10power
308)
to

1.7*(10power308)

longdouble
%Lf
10Bytes
3.4*(10 power
4932)
to

1.1*(10power
4932)

char[](string)
%s

%o OctalBase
%x Hexadecimalbase
%p Memoryaddress

Variable:
A quantity which may vary during the execution of a
programiscalledasvariable.

DeclarationofaVariable:

datatypeidentifier

(or)
datatypeidentifier1,identifier2,,identifiern

Eg:
intn
charch
floatf
doubledb
inta,b,c,d
charch1,ch2,ch3

Initializationofvariable:

At the time of declaringavariable,wecanstoresome

valueintothatvariableisknownasinitialization.

Syntax:

datatypeidentifier=value

Eg:

intn=100
charch=H
floatft=10.569
doubledb=1417.1418
inta=10,b=20,c=30
intx=100,y,z=200

Program:

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn=100
clrscr()
printf(%d,n)
printf(\nvalueofn=%d,n)
getch()
}

Output

100
valueofn=100

Note:

In C language, all declarations will be done before the


firstexecutablestatement.

Program:

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn=18
charc=R
floatf=17.148
doubled=1714.1418
clrscr()
printf(n=%d,n)
printf(\nc=%c,c)
printf(\nf=%f,f)
printf(\nd=%lf,d)
getch()
}


Output

N=18
C=R
F=17.148000
D=1714.141800

Note:

Floating values displays 6 digits after the decimal point,


bydefault.
If we want to display specified number of digits after
decimal point for floating values, use the following
technique.
Example:

#include<stdio.h>
#include<conio.h>
voidmain()
{
floatf=12.4466
doubled=1234.56789
clrscr()
printf(F=%f,f)
printf(D=%lf,d)
printf(F=%.2f,f)

printf(D=%.2lf,d)
getch()
}

Output

F=12.4466
D=1234.56789
F=12.45
D=1234.57

Constants:

Constants in C refertofixedvaluedthat donotchange


duringtheexecutionofaprogram.

const:

Itisakeywordandisusedtodeclareconstants.

Syntax
:

constdatatypeidentifier=value
Or
const
datatype
identifier1=value,.,identifiern=value


Eg:
constinta=100
constinta=10,b=20,c=30

Example:

#include<stdio.h>
#include<conio.h>
voidmain()
{
constinta=100
clrscr()
printf(a=%d,a)
/*a=200*/
(ifwegivelikethis,wewillgetanerror
cantmodifya
constantvalue
)
printf(\na=%d,a)
getch()
}

Output

A=100
A=100

Symbolicconstants:

#define:

It is a preprocessor statement and is used to define


symbolicconstants.

Syntax:
#defineidentifiervalue

Eg:
#definepi3.14
#defineg9.8

Example:

#include<stdio.h>
#include<conio.h>
#definepi3.14
#defineg9.8
#defineval100
voidmain()
{
clrscr()
printf(pi=%.2f,pi)
printf(g=%.21,g)
printf(val=%d,val)

getch()
}

Output:

PI=3.14
G=9.8
VAL=100

scanf:
Itisafunctionandisusedtoreaddatafromthestandard
inputdevice.
Syntax:

int
scanf(format(s),address1,address2,..addressn)

eg:
intn
addressofn=&n
scanf(%d,&n)

Example:

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

{
intn
clrscr()
printf(Enteranyvalue:)
scanf(%d,&n)
printf(Givenvalue:%d,n)
getch()
}

Example:

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn
charc
floatf
doubled
clrscr()
printf(Enteranycharactervalue:)
scanf(%c,&c)
printf(EnteranyIntvalue:)
scanf(%d,&n)
printf(Enteranyfloatvalue:)
scanf(%f,&f)
printf(Enteranydoublevalue:)

scanf(%lf,&d)
printf(GivenInt:%d\n,n)
printf(Givenchar:%c\n,c)
printf(Givenfloat:%f\n,f)
printf(Givendouble:%lf,d)
getch()
}

Skippingproblem:

Example:

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn
charc
clrscr()
printf(enteranynumber:)
scanf(%d,&n)
printf(enteranycharacter:)
scanf(%c,&c)
printf(n=%d\n,n)
printf(c=%c\n,c)
getch()
}

Output

enteranynumber:100
enteranycharacter:
n=100
c=

Intheaboveprogram,itcannotreadacharacter
into the character variable, because previous integer
readingstatementcreatesanewlinecharacterintheinput
stream. That character will assign to the character
variable.

To avoid this problem we use


fflush or
flushall
functions.

fflush:
Itflushesthespecifiedstream.

Syntax:
fflush(stream_name)

Eg:
fflush(stdin)

flushall:
Itflushesallopenstreams.

Syntax:
flushall()

Example:

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn
charc
clrscr()
printf(enteranynumber:)
scanf(%d,&n)
printf(enteranycharacter:)
fflush(stdin)(or)flushall()
scanf(%c,&c)
printf(N=%d\n,n)
printf(C=%c\n,c)
getch()
}
\ncharacter:

Sometimes, instead of fflush() or flushall() we canuse\n


toavoidskippingproblem.

Example:

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn
charc
clrscr()
printf(enteranynumber:)
scanf(%d,&n)
printf(enteranycharacter:)
scanf(\n%c,&c)
printf(N=%d\n,n)
printf(C=%c\n,c)
getch()
}

Example:

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn
charc
clrscr()
printf(enteranynumberandacharacter:)
scanf(%d\n%c,&n,&c)

printf(N=%d\n,n)
printf(C=%c\n,c)
getch()
}

String:

Agroupofcharactersdefinedbetweendoublequotation
marks is a string. It is a constant string. In C language, a
string variable is nothing but an array of characters and
terminatedbyanullcharacter(\0).

Declaration:
charidentifier[size]

Eg
:charst[20]

Initialization:
Atthetimeofdeclaringastringvariable,wecanstore
a constant string into that variable is called as
initialization.
optional

syn:
charidentifier[size]=string

Eg:
chars[10]=WELCOME


charst[]=ABCD

The compiler assigns a constant string to the string


variable. It automatically supplied a null character at the
end of string. Therefore the size should be equal to the
maximumnumberofcharactersinthestringplus(+)1.

Note: In C language, string initialization is possible,but


stringassigningisnotpossible.

Example:

#include<stdio.h>
#include<conio.h>
voidmain()
{
charst[10]=GoodMorning
chars[]=Welcome
printf(%s,st)
printf(%s,s)
getch()
}

Program : To accept a string from key board and to

displaythestring.

Example:

#include<stdio.h>
#include<conio.h>
voidmain()
{
charst[50]
clrscr()
printf(Enterastring:)
scanf(%s,st)
printf(Givenstringis:%s,st)
getch()
}

Output:

1. Enterastring:welcome
Givenstring:welcome

1. Enter
a string: welcome to SIDDHRTHA
ELECTRICALASSOCIATION
Givenstring:welcome

scanf()statementcannotreadspacesintoastringvariable.
If we want to read a string with spaces from key board

usingscanf()statementbythefollowingway.

scanf(%[^\n]s,st)

ItreadscharactersuntilwepressEnterkey

Example:

#include<stdio.h>
#include<conio.h>
voidmain()
{
charst[50]
clrscr()
printf(Enterastring:)
scanf(%[^\n]s,st)
printf(Givenstringis:%s,st)
getch()
}

gets():

It is a function used to read a string(including spaces)


fromthestandardinputdevice.

Syntax:
gets(string_varibale)

Eg:
gets(st)

Example:

#include<stdio.h>
#include<conio.h>
voidmain()
{
charst[50]
clrscr()
printf(Enterastring:)
gets(st)
printf(Givenstringis:%s,st)
getch()
}

Program:

ToenteranycharacteranddisplayitsASCIIvalue
#include<stdio.h>
#include<conio.h>
voidmain()
{
charc
clrscr()
printf(enteranycharacter:)
scanf(%c,&c)

printf(ASCIIvalueofgivencharacter:%d,c)
getch()
}

Program:

ToenteranyASCIIvalueanddisplayitscharacter

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn
clrscr()
printf(enteranyASCIIvaluefrom0to255:)
scanf(%d,&n)
printf(characterofgiveASCIIvalue:%c,n)
getch()
}

Prgram:

Toenteranydateindateformatandtodisplaythegiven
date.

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

voidmain()
{
intd,m,y
clrscr()
printf("Enteranydateintheformatddmmyyyy:")
scanf("%d%d%d",&d,&m,&y)
printf("Givendateis:%.2d%.2d%d",d,m,y)
getch()
}

OperatorsinC:

Operator:
It is a symbol and it performs particular
operation.

Operand:

Itisanentity,onwhichanoperatoracts.

Binaryoperator:

Itrequires2operands.

Unaryoperator:

Itrequiresonlyasingleoperand.

Coperatorscanbeclassified intonumberofcategories.
Theyare

1.
1.
1.
1.
1.
1.
1.

Arithmeticoperators
Relationaloperators
Logicaloperators
Assignmentoperators
IncrementandDecrementoperators
Bitwiseoperators
Specialoperators
a) TernaryorConditionaloperator
b) Commaoperator
c) sizeofoperator

Arithmeticoperators:

These are the basic operators in C language. These are


usedforarithmeticcalculations.
+Addition
Subtraction
*Multiplication
/
Division
% Modulus(Remainder)

Program:

arithm.c

To enter any 2 numbers and test all arithmetic


operations.

#include<stdio.h>

#include<conio.h>
voidmain()
{
inta,b
clrscr()
printf("Enter2numbers:")
scanf("%d%d",&a,&b)
printf("\nAdditionof%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%dand%dis%d",a,b,a/b)
printf("\nModulusof%dand%dis%d",a,b,a%b)
getch()
}

Relationaloperators:

Theseareusedtotesttherelationbetween2valuesor2
expressions. All C relational operators are binary
operatorsandhenceitrequires2operands.

< lessthan
> greaterthan
<= lessthanorequalto
>= greaterthanorequalto
== equalto

!= notequalto

Logicaloperators:

These are used to combine the result of 2 or more


expressions.

&&LogicalAND

|| LogicalOR

! LogicalNOT

Exp1
Exp2
Exp1&&Exp2
Exp1||Exp2

True
True
True
True
True
False False True
False
True
False True
False
False
False False

1.
1.

IfExp=True

!Exp=False
IfExp=False

!Exp=True

AssignmentOperators:

These are used to assign a constantvalueorvaluesonan


expressiontoanidentifier.

Theyareof2types.

1. Simpleassignment:
=

Eg:
n=10

1. Shorthandorcompoundassignment

+=
=
*=
/=
%=

etc.

Eg:

intn=10,ifwewanttoadd5tonthenwewill
given=n+5orn+=5,whichiscompoundassignment.

IncrementandDecrementOperators:

These operators are used to control the loops in an


effectivemethod.
1 Incrementoperator:

Thesymbol++isusedforincrementingby1.
Itisof2types.
1)++identifierprefixincrement
2)identifier++postfixincrement

Eg:

1)
inta=10
++a(or)a++
a=11

1)
inta=10,b
b=++a
a=11
b=11

1)
inta=10,b
b=a++
a=11
b=10


intx=10
printf(%d\t%d,x,x++)
o/p:1110

Decrementoperator:

Thesymbolisusedfordecrementingby1.
Itisof2types.
1)identifierprefixdecrement
2)identifierpostfixdecrement

Eg:

1)inta=10
a(or)a
a=9

2)inta=10,b
b=a
a=9
b=9

3)inta=10,b
1)

b=a
a=9
b=10

4)
intx=10
printf(%d\t%d,x,x)
output:
9
10

BitwiseOperators:

These operators are used for manipulation of data at bit


level.
Theseareclassifiedinto2types.Namely,
1. Bitwiselogicaloperators
1. Bitwiseshiftoperators.

Bitwiselogicaloperators:

Theseareusedforbitwiselogicaldecisionmaking.

&BitwiselogicalAND

|BitwiselogicalOR
^BitwiselogicalXOR


B1
B2 B1&B2 B1|B2B1^B2

11110
10011
01011
00000

Eg:
inta=5,b=6

a=5>101
b=6>110

101
110

a&b:100=4

101
110

a|b:111=7


101
110

a^b:011=3

Example:

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta,b
printf(Entervaluesintaandb:)
scanf(%d%d,&a,&b)
printf(\na&b=%d,a&b)
printf(\na|b=%d,a|b)
printf(\na^b=%d,a^b)
getch()
}

Bitwiseshiftoperartor:

The shift operations take binary patterns and shift the


bitstotheleftorright.

<<leftshift
>>rightshift

Eg:

inta=4,b,c
a=4

a=100(binaryform)
b=a<<2 meansaistobeleftshiftedby2bitsandstoreit
inb.

1 0 0

Henceitbecame,

1 0 0
0 0
thenthevalueofb:

10000=2power4=16


a=4

a=100(binaryform)
c=a>>1 meansaistoberightshiftedby1bitandstoreit
inc.

1 0 0

Henceitbecame,

1
0

thenthevalueofc:

010=2power1=2

Example:

#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()
}

Specialoperators:

1)
Ternary(or)Conditionaloperator:

Aternaryoperatorpair "?" and": "isavailablein


C language. It is used to construct a conditional
expression.
Thegeneralformofternaryoperatoris:

Exp1?Exp2:Exp3

InthisoperatorfirstExp1isevaluated,ifitistruethen
Exp2 is evaluated and its value becomes the value of the
Expression, otherwise Exp3 is evaluated and its value
becomesthevalueoftheExpression.

Eg:


inta=10,b=20,c
c=a<b?a:b
outputwillbec=10

Program:

max1_ter.c

To find the maximum and minimum values of given 2


numbers.

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta,b,max,min
clrscr()
printf("Enter2numbers:")
scanf("%d%d",&a,&b)
max=a>b?a:b
min=a<b?a:b
printf("Maximimvalue:%d",max)
pri`ntf("\nMinimumvalue:%d",min)
getch()
}


Program:

evod_ter.c

Tocheckwhetherthegivennumberisevenorodd.

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn
clrscr()
printf("Enteranumber:")
scanf("%d",&n)

n%2==0 ? printf("Given number is even") :


printf("Givennumberisodd")
getch()
}

Program:

max2_ter.c

To find the maximum and minimum values of given 3


numbers.

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta,b,c,max,min

clrscr()
printf("Enter3numbers:")
scanf("%d%d%d",&a,&b,&c)
max=a>b&&a>c?a:(b>c?b:c)
min=a<b&&a<c?a:(b<c?b:c)
printf("Maximimvalue:%d",max)
printf("\nMinimumvalue:%d",min)
getch()
}

2)
commaoperator:

Itcanbeusedtolinktherelatedexpressionstogether.
Thegeneralformofcommaoperatoris:

var=(var1=value,var2=value,..,varn=value ,
expression)

Eg:
inta,b,c
c=(a=10,b=20,a+b)

Herefirstassignsthevalueof10toa,thenassigns20tob
andfinallyassigns30(a+b)toc.

Example:
comma.c


#include<stdio.h>
#include<conio.h>
voidmain()
{
inta,b,c
clrscr()
c=(a=10,b=20,2*a+b)
printf("a=%d",a)
printf("\nb=%d",b)
printf("\nc=%d",c)
getch()
}

3)
sizeofoperator:

Itisusedtogetthememorysizeofspecifiedvariable
orexpressionordatatype.

Syntax:

sizeof(variable/expression/datatype)

Eg1:
1.sizeof(int)2
2.sizeof(float)4

eg2:
inta,b
sizeof(a)2
sizeof(b)2
sizeof(a+b)2

Example:1

sizeof_1.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn
charc
floatf
doubled
clrscr()
printf("sizeofint:%dbytes",sizeof(n))
printf("\nsizeofchar:%dbytes",sizeof(c))
printf("\nsizeoffloat:%dbytes",sizeof(f))
printf("\nsizeofdouble:%dbytes",sizeof(d))
getch()
}

Example:2

sizeof_2.c

#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()
}

PrecedenceofOperators:

S.No
Category
Operator
Whatitis
(ordoes)

1Highest()Functioncall

[]Arraysubscript


2Unary!LogicalNot

+Unaryplus

Unaryminus

++
Preorpost
increment

Preorpost
decrement

&address

sizeof
returnssizeof
operandin

bytes

3Multiplicative*Multiply

/Divide

Remainder(modulus)

4
Additive
+
Binary
plus(addition)

Binary
minus(subtraction)

5shift<<shiftleft

>>shiftright

6Relational<Lessthan

<=
Lessthanor
equalto

>Greaterthan

>=
Greaterthanor
equalto

7Equality==Equalto
!=Notequalto

8&BitwiseAND

9^BitwiseXOR

10|BitwiseOR

11&&LogicalAND

12||LogicalOR

13
Conditional
?:
(a?x:ymeansif
aistrue,

thenx
elsey)

14
Assignment
=
Simple
assignment

*=Assignproduct

/=Assignquotient

%=
Assign
remainder

+=Assignsum


=
Assign
difference

15Comma,Evaluate

TypecastingorTypeconversion:

The process of converting one data type to another is


calledastypecastingortypeconversion.

In C language type conversion is an arithmetic


expression will be done automatically. This is called
implicit conversion. If we want to store a value of one
type into a variable of another type, we must caste the
value to be stored by preceding it with the type name in
parenthesis.This is called explicit conversion or type
casting.

Eg:

inta,b

floatc,d
a=5,b=2
c=a/b

c=2.00
conversion
d=(float)a/b
d=2.50
conversion

Example:

typecast.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta,b
floatc,d
clrscr()
printf("Enter2numbers:")
scanf("%d%d",&a,&b)
c=a/b
d=(float)a/b
printf("c=%.2f",c)
printf("\nd=%.2f",d)
getch()
}

Program:

tri_area.c

automatic or implicit
type casting or explicit


To enter base and height of a triangle and to calculate
itsarea.

#include<stdio.h>
#include<conio.h>
voidmain()
{
floatb,h,area
clrscr()
printf("Enterbaseoftriangle:")
scanf("%f",&b)
printf("Enterheightoftriangle:")
scanf("%f",&h)
area=(float)1/2*b*h/*orarea=0.5*b*h*/
printf("Areaoftriangle:%.2fsquareunits",area)
getch()
}

Program:

circl_ar.c

Toenterradiusofacircleandtocalculateitsarea.

#include<stdio.h>
#include<conio.h>
#definepi3.14
voidmain()

{
floatr,area
clrscr()
printf("Enterradiusofcircle:")
scanf("%f",&r)
area=pi*r*r
printf("Areaofcircle:%.2fsquareunits",area)
getch()
}

Program:

simp_int.c

To enter principle amount, time period, and rate of


interest and to calculate and display simple interestand
totalamount.

#include<stdio.h>
#include<conio.h>
voidmain()
{
inty,m,t
floatp,r,si,tamt
clrscr()
printf("Enterprincipalamount:")
scanf("%f",&p)
printf("Enterrateofinterest:")
scanf("%f",&r)

printf("Enternumberofyearsandmonths:")
scanf("%d%d",&y,&m)
t=m+(y*12)
si=(p*t*r)/100
tamt=p+si
printf("SimpleInterest:%.2f",si)
printf("\nToatalAmount:%.2f",tamt)
getch()
}

Program:

swap1.c

swappingofgivenvariablesusingtemporaryvariable

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta,b,t
clrscr()
printf("Enter2numbers:")
scanf("%d%d",&a,&b)
printf("\nBeforeswapping")
printf("\na=%d",a)
printf("\nb=%d\n\n",b)
t=a
a=b

b=t
printf("Afterswapping")
printf("\na=%d",a)
printf("\nb=%d",b)
getch()
}

Program:

swap2.c

swapping of given variable with out using temporay


variable

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta,b
clrscr()
printf("Enter2numbers:")
scanf("%d%d",&a,&b)
printf("\nBeforeswapping")
printf("\na=%d",a)
printf("\nb=%d\n\n",b)
a=a+b
b=ab
a=ab
printf("Afterswapping")

printf("\na=%d",a)
printf("\nb=%d",b)
getch()
}

Compoundstatement(or)block:

A group of statements enclosed within curly braces is


calledascompoundstatementorblock.

Accessibility of variables inside and outside of compound


statement:

1.
A variable which is declared above (outside) the

compound statement, it is accessible both inside and


outsidethecompoundstatement.

2. A variable which is declared inside the compound


statement it is not accessible outside the compound
statement.

3. It is possible to declare a variable with the same name


bothinsideandoutsidethecompoundstatement.

Example:

compd1.c


#include<stdio.h>
#include<conio.h>
voidmain()
{
inta=100
clrscr()
{
intb=200
printf("InsideCompoundStatement\n")
printf("a=%d\n",a)
printf("b=%d\n",b)
}
printf("\nOutsideCompoundStatement\n")
printf("a=%d\n",a)
// printf("%d",b) > not accessible outside compound
statement//
getch()
}

Example:

compd2.c

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

clrscr()
printf("OutsideCompoundStatement\n")
printf("a=%d\n\n",a)
{
inta=200
printf("InsideCompoundStatement\n")
printf("a=%d\n\n",a)
}
printf("OutsideCompoundStatement\n")
printf("a=%d\n",a)
getch()
}

Program:

cur_bill.c

program to enter consumer number,name,present


month reading,last month reading, andtocalculateand
display total units and bill amount.Rate per unit is Rs
4.00

#include<stdio.h>
#include<conio.h>
voidmain()
{
intcno,pmr,lmr,tu
charcname[20]
floattamt

clrscr()
printf("EnterConsumernumber:")
scanf("%d",&cno)
printf("EnterConsumername:")
fflush(stdin)
gets(cname)
printf("Enterpresentmonthreading:")
scanf("%d",&pmr)
printf("Enterlastmonthreading:")
scanf("%d",&lmr)
tu=pmrlmr
tamt=tu*4.00
clrscr()
printf("ConsumerNumber:%d",cno)
printf("\nConsumerName:%s",cname)
printf("\nPresentmonthreading:%d",pmr)
printf("\nLastmonthreading:%d",lmr)
printf("\nTotalnumberofunits:%d",tu)
printf("\nTotalBillAmount:%.2f",tamt)
getch()
}

Program:

student.c

program to enter student number,name,marks in


C,CPP,Java and to calculate and display total marks

andaveragemarks.
#include<stdio.h>
#include<conio.h>
voidmain()
{
intsno,c,cpp,java,tot
charsname[20]
floatavg
printf("Enterstudentnumber:")
scanf("%d",&sno)
printf("Enterstudentname:")
fflush(stdin)
gets(sname)
printf("EntermarksinC:")
scanf("%d",&c)
printf("EntermarksinCPP:")
scanf("%d",&cpp)
printf("EntermarksinJava:")
scanf("%d",&java)
tot=c+cpp+java
avg=(float)tot/3
clrscr()
printf("StudentNumber:%d",sno)
printf("\nStudentName:%s",sname)
printf("\nMarksinC:%d",c)
printf("\nMarksinCPP:%d",cpp)
printf("\nMarksinJava:%d",java)

printf("\nTotalMarks:%d",tot)
printf("\nAverageMarks:%.2f",avg)
getch()
}

Controlstatements(or)Controlstructures:

C is a structured programming language. One of the


reasons for this is having various program control
statements. C process the decision making capabilities
andsupportsthestatementsknownascontrolstatements.
Csupports3typesofcontrolstatements.Theyare:

1.Conditionalcontrolstatements.
2.Unconditionalcontrolstatements.
3.Loopcontrolstatements.

Conditionalcontrolstatements:

Csupports5typesofconditionalcontrolstatements.

1)simpleifstatement
2)ifelsestatement
3)Nestedifstatement
4)elseifladderstatement

5)switchstatement

simpleifstatement:

It is a conditional controlled statement and is used to


controltheflowofexecution.

Syntax:

if(expr)
{
statements
}

In this statement, first the expression will be


evaluated.If it is true then the statement block will be
executed and the control transfer to the next statement.
Otherwise if the expression is false, then the control
directlygoestothenextstatement.

flowchart

Note:

In any control statement, the statement block contains


onlyasinglestatement,curlybracesarenotnecessary.

Example
:
sim_if1.c

Tofindmaximumof2numberusingsimpleif

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta,b,max
clrscr()
printf("Enteranytwonumbers:")
scanf("%d%d",&a,&b)
max=a
if(max<b)
{
max=b
}
printf("MaximumValue:%d",max)
getch()
}

Example
:
sim_if2.c

Tofindmaximumof3numbersusingsimpleif

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta,b,c,max
clrscr()
printf("Enter3numbers:")
scanf("%d%d%d",&a,&b,&c)
max=a
if(max<b)
max=b

if(max<c)
max=c
printf("MaximumValue:%d",max)
getch()
}

Example:
age
.c

To enter current date and date of birth. Calculate and


displaypresentage.

#include<stdio.h>
#include<conio.h>
voidmain()
{
intcd,cm,cy,bd,bm,by,d,m,y
clrscr()
printf("Entercurrentdate(ddmmyyyy):")
scanf("%d%d%d",&cd,&cm,&cy)
printf("Enterbirthdate(ddmmyyyy):")
scanf("%d%d%d",&bd,&bm,&by)
d=cdbd
m=cmbm
y=cyby
if(d<0)
{
d=d+30
m
}
if(m<0)
{
m=m+12
y
}
printf("Present age is : %d years %d months %d
days",y,m,d)
getch()
}


ifelsestatement:

Itisanextensionofsimpleifstatement.

Syntax:

if(expr)
{
Statements1
}
else
{
Statements2
}

In this statement, first the expression will be evaluated,


and if it is true then the if block statements are executed
andtheelseblockstatementsareignored.Otherwiseifthe
expression is false, then else block statements are
executedandifblockstatementsareignored.

flowchart

Example
:
else_if.c

Tofindmaximumof2numbersusingelseif
#include<stdio.h>
#include<conio.h>
voidmain()
{
inta,b,max
clrscr()
printf("Enter2numbers:")
scanf("%d%d",&a,&b)
if(a>b)
max=a
else
max=b
printf("Maximumvalue:%d",max)
getch()
}

Example:

else_if2.c

Tocheckwhetherthegivennumberisevenorodd

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
if(n%2==0)
printf("GivennumberisEven")
else
printf("GivennumberisOdd")
getch()
}

Nestedifstatements:

Usingaifstatementwithinanotherifiscalledasnested
if. If a series of decisions are involved, we use nested if
statement.
Form:1

if(expression1)
{
if(expression2)

{
.
if(expressionn)
{
statements
}
...
}
}

Form:2

if(expression1)
{
if(expression2)
{
Statement1
}
else
{
Statement2
}

}
else
{
if(expression3)
{
Statement3
}
else
{
Statement4
}
}

Example
:nest_if.c

Tofindmaximumof3numbersusingnestedif

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta,b,c,max
printf("Enteranythreenumbers:")
scanf("%d%d%d",&a,&b,&c)
if(a>b)
{

if(a>c)
max=a
else
max=c
}
else
{
if(b>c)
max=b
else
max=c
}
printf("Maximumvalue:%d",max)
getch()
}

elseifladder:

Thisstatementisalsousedforaseriesofdecisionsare
involved.

Syntax:

if(expression1)
{
Statements1

}
elseif(expression2)
{
Statement2
}
..
..
elseif(expressionn)
{
Statementn
}
else
{
elseblockstatements
}

In this statement, the expressions are evaluated


from top to bottom, if the condition is true then the
statements associated that block is executed and the
controltransferstothenextstatement.Otherwisewhenall
expressions are false then the final else block statements
willbeexecuted.

Example:

elif_lad.c

Tofindmaximumof3numbersusingelseifladder

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta,b,c,max
printf("Enteranythreenumbers:")
scanf("%d%d%d",&a,&b,&c)
if(a>b&&a>c)
max=a
elseif(b>c)
max=b
else
max=c
printf("Maximumvalue:%d",max)
getch()
}

Example:

ck_char.c

To check whether the given number is alphabet or


numberorspecial

character

#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<='Z')||(ch>='a'&&ch<='z'))
printf("Givencharacterisaalphabet")
elseif(ch>=48&&ch<=57)
//elseif(ch>='0'&&ch<='9')
printf("Givencharacterisadigit")
else
printf("Givencharacterisaspecialcharacter")
getch()
}

Example:

vow_cons.c

To check whether the given character is vowel or


consonant

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

charch
clrscr()
printf("Enteranycharacter:")
scanf("%c",&ch)
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
{

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


ch=='I'||ch=='o'||

ch=='O'||ch=='u'||
ch=='U')
printf("Givencharacterisavowel")
else
printf("Givencharacterisaconsonant")
}
else
printf("GivencharacterisnotanAlphabet")
getch()
}

Example
:
st_det.c

To enter student number, name, marks in C,CPP,java


and to calculate and displaytotalmarks,average,result
anddivision
#include<stdio.h>
#include<conio.h>
voidmain()

{
intsno,c,cpp,java,tot
charsname[20],res[5],div[10]
floatavg
clrscr()
printf("Enterstudentnumber:")
scanf("%d",&sno)
printf("Enterstudentname:")
fflush(stdin)
gets(sname)
printf("EntermarksinC:")
scanf("%d",&c)
printf("EntermarksinCPP:")
scanf("%d",&cpp)
printf("EntermarksinJava:")
scanf("%d",&java)
tot=c+cpp+java
avg=(float)tot/3
clrscr()
printf("StudentNumber:%d",sno)
printf("\nStudentName:%s",sname)
printf("\nMarksinC:%d",c)
printf("\nMarksinCPP:%d",cpp)
printf("\nMarksinJava:%d",java)
printf("\nTotalMarks:%d",tot)
printf("\nAverageMarks:%.2f",avg)

if(c>=50&&cpp>=50&&java>=50)
{
printf("\nResult:PASS")
if(avg>=60)
printf("\nDivision:FIRST")
else
printf("\nDivision:SECOND")
}
else
{
printf("\nResult:FAIL")
printf("\nDivision:NODIVISION")
}
getch()
}

Example:

ndays.c

To enter month and year and to calculate and display


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

{
intd,m,y
clrscr()
printf("Entermonthandyear(mmyyyy):")
scanf("%d%d",&m,&y)
if(m==2)
{
if((y%4==0&&y%100!=0)||(y%400==0))
d=29
else
d=28
}
elseif(m==2||m==4||m==6||m==9||m==11)
d=30
else
d=31
printf("Numberofdays:%d",d)
getch()
}

exit:
<process.h>

Itterminatestheprogram.

Syntax:
voidexit(intstatus)

Status: Typicallyvalueofzero,indicatesanormalexit,

andanonzeroindicatessomeerror.

Example:

cbill.c

To enter consumer number, name, present month


reading, last month reading. calculate and display total
unitsandbillamountbythefollowingtable.

Unitsrate/unit

0501.45(min)
511002.80
1012003.05
2013004.75
>3005.50

#include<stdio.h>
#include<conio.h>
voidmain()
{
intcno,pmr,lmr,tu
charcname[20]

floatbamt
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)
}
tu=pmrlmr
if(tu<=50)
bamt=50*1.45
elseif(tu<=100)
bamt=50*1.45+(tu50)*2.80
elseif(tu<=200)
bamt=(50*1.45)+(50*2.80)+(tu100)*3.05
elseif(tu<=300)
bamt=(50*1.45)+(50*2.80)+(100*3.05)+(tu200)*4.75
else


bamt=(50*1.45)+(50*2.80)+(100*3.05)+(100*4.75)+(tu
300)*5.50
clrscr()
printf("\nConsumerNumber:%d",cno)
printf("\nConsumerName:%s",cname)
printf("\nPresentmonthreading:%d",pmr)
printf("\nLastmonthreading:%d",lmr)
printf("\nTotalunits:%d",tu)
printf("\nTotalBillAmount:%.2f",bamt)
getch()
}

Example
:emp_sal.c

To enter emp number, name, grade, basic salary.


Calculate and display HRA,DA,TA,IT,PF,gross
salary,deductionsandnetsalarybythefollowingtable.

Grade
Basic
HRA
DA
TA
ITPF

A
<=2000
10%
15%
3%
05%

A
>2000&<=5000
15
38

A
>5000
20
512

B
<=3000
8
04

B
>3000 & <=5000
10
28

B
>5000
15
410

#include<stdio.h>
#include<conio.h>
voidmain()
{
inteno
charename[20],gr
floatbasic,hra,da,ta,it,pf,gs,ded,ns
clrscr()
printf("EnterEmployeeNumber:")

20

25

10

12

12

18

scanf("%d",&eno)
printf("EnterEmployeeName:")
fflush(stdin)
gets(ename)
printf("EnterEmployeeGrade:")
scanf("%c",&gr)
if(gr=='A'&&gr=='B'&&gr=='a'&&gr=='b')
{
printf("InvalidGrade")
getch()
exit(0)
}
printf("EnterBasicSalary:")
scanf("%f",&basic)
if(gr=='a'||gr=='A')
{
if(basic<=2000)
{
hra=basic*10/100
da=basic*15/100
ta=basic*3/100
it=0
pf=basic*5/100
}
elseif(basic<=5000)
{
hra=basic*15/100

da=basic*20/100
ta=basic*5/100
it=basic*3/100
pf=basic*8/100
}
else
{
hra=basic*20/100
da=basic*25/100
ta=basic*8/100
it=basic*5/100
pf=basic*12/100
}
}
else
{
if(basic<=3000)
{
hra=basic*8/100
da=basic*10/100
ta=basic*2/100
it=0
pf=basic*4/100
}
elseif(basic<=5000)
{
hra=basic*10/100

da=basic*12/100
ta=basic*4/100
it=basic*2/100
pf=basic*8/100
}
else
{
hra=basic*15/100
da=basic*18/100
ta=basic*5/100
it=basic*4/100
pf=basic*10/100
}
}
gs=basic+hra+da+ta
ded=it+pf
ns=gsded
clrscr()
printf("\t\t\tEMPLOYEEDETAILS\n\n")
printf("\nEmployeeNumber:%d",eno)
printf("\nEmployeeName:%s",ename)
printf("\nEmployeeGrade:%c",gr)
printf("\nBasicSalary:%.2f",basic)
printf("\nHouseRentAllowance:%.2f",hra)
printf("\nDearnessAllowance:%.2f",da)
printf("\nTravellingAllowance:%.2f",ta)
printf("\nIncometax:%.2f",it)

printf("\nProvidentFund:%.2f",pf)
printf("\nGrossSalary:%.2f",gs)
printf("\nDeductions:%.2f",ded)
printf("\nNetSalary:%.2f",ns)
getch()
}
Program:

dealer.c

To enter dealer number, name, number of litres petrol


sold, no of lit diesel sold, no of lit kerosene sold and
dealer
regions
are
northN,westW,eastE,southS.Calculate and display
totalamountbythefollowingtable.

Region
Petrol
Diesel
Kerosene

(rate/litre)
(rate/lit)
(rate/lit)

N
50.75
31.85
22.15

S
49.85
30.25
21.50


W
52.35
33.75
24.65

E
51.45
32.15
23.75

#include<stdio.h>
#include<conio.h>
voidmain()
{
intdno,np,nd,nk
chardname[20],reg
floatpa,da,ka,ta
clrscr()
printf("Enterdealernumber:")
scanf("%d",&dno)
printf("Enterdealername:")
fflush(stdin)
gets(dname)
printf("Enterdealerregion:")
fflush(stdin)
scanf("%c",&reg)
if(reg>=97&&reg<=122)
reg=reg32 // this is to convert lower case letters to
uppercaseletters//

if(reg!='N'&&reg!='W'&&reg!='S'&&reg!='E')
{
printf("InvalidRegion")
getch()
exit(0)
}
printf("Enternumberoflitresofpetrolsold:")
scanf("%d",&np)
printf("Enternumberoflitresofdieselsold:")
scanf("%d",&nd)
printf("Enternumberoflitresofkerosenesold:")
scanf("%d",&nk)
if(reg=='N')
{
pa=np*50.75
da=nd*31.85
ka=nk*22.15
}
elseif(reg=='S')
{
pa=np*49.85
da=nd*30.25
ka=nk*21.50
}
elseif(reg=='W')
{
pa=np*52.35

da=nd*33.75
ka=nk*24.65
}
else
{
pa=np*51.45
da=nd*32.15
ka=nk*23.75
}
clrscr()
ta=pa+da+ka
printf("DealerNumber:%d",dno)
printf("\nDealerName:%s",dname)
printf("\nDealerRegion:%c",reg)
printf("\nLitresofpetrolsold:%d",np)
printf("\nLitresofdeeselsold:%d",nd)
printf("\nLitresofkeroenesold:%d",nk)
printf("\nPetrolAmount:%.2f",pa)
printf("\nDeeselAmount:%.2f",da)
printf("\nKeroseneAmount:%.2f",ka)
printf("\nTotalAmount:%.2f",ta)
getch()
}

Switchstatement:


It is a multiway condition statement used in C
language. It is mainly used in situations where there is
needtopickonealternativeamongmanyalternatives.

Syntax:

switch(variable/expression)
{
casevalue1:
statements1;
break;

casevalue2:
statements2;
break;

..
.

casevaluen:
statementsn;
break;

default:
defaultstatements;
}

The switch statement tests the value of given


variable or expression against a list of case values.
Whenamatchisfound,thestatementassociatedto
that caseis executedandthecontroltransfertothe
next statement, otherwise the default statements
willbeexecuted.

break:

It is an uncondition control statement and used to


terminateaswitchstatementoraloopstatement.

Syntax:
break

Note:

1. In switch statement the variable or expression is an


integral value(integer or character), we cannot use
floatandstringvalues.

1. Inswitchstatement,thedefaultcaseisoptional.

Program
:
switch_1.c


Totestallarithmeticoperationsusingswitchstatement

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta,b,opt
clrscr()
printf("Entertwonumbers:")
scanf("%d%d",&a,&b)

printf("1Addition\n2Subtraction\n3Multiplication\n4D
ivision

\n5Modulus\nEnteryour
option:")
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:

printf("Multiplication of %d and %d is
%d",a,b,a*b)
break

case4:

printf("Division of %d and %d is
%.2f",a,b,(float)a/b)
break
case5:
printf("Modulusof%dand%dis%d",a,b,a%b)
break

default:
printf("InvalidOption")
}
getch()
}

Program
:
switch_2.c

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

inta,b
charopt
clrscr()
printf("Enter2numbers:")
scanf("%d%d",&a,&b)

printf("AAddition\nSSubtraction\nMMultiplication\nD
Division
\nRModulus\nEnteryouroption:")
fflush(stdin)
scanf("%c",&opt)
switch(opt)
{
case'A':
case'a':

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

case'S':
case's':
printf("Subtractionof%dand%dis%d",a,b,ab)
break

case'M':
case'm':

printf("Multiplication of %d and %d is

%d",a,b,a*b)
break

case'D':
case'd':
printf("Divisionof%dand%dis%d",a,b,a/b)
break

case'R':
case'r':
printf("Modulusof%dand%dis%d",a,b,a%b)
break

default:
printf("InvalidOption")
}
getch()
}

Program:

ele_bill.c

Write a menu driven program(mdp) to compute the


electricitybillforthefollowingpurpose

CommercialPurpose

UnitsRate/Unit


0503.95(min)

>506.20

Extras:

Rs.0.06perunitpowertax

servicechrge:

Rs.10singlephase
Rs.20threephase

DomesticPurpose

UnitsRate/Unit

0501.45(min)

511002.80

1012003.05

2013004.75

>3005.50

Extras:

Rs.0.06perunitpowertax

servicecharge:

Rs.20singlephase
Rs.50threephase

#include<stdio.h>
#include<conio.h>
voidmain()
{
intcno,pmr,lmr,tu,opt,ph
charcname[20]
floatpt,sc,bamt,tamt
clrscr()
printf("\t\tMENU\n\n")
printf("")
printf("\n1DomesticPrupose\n")
printf("\n2CommericalPurpose\n")
printf("\nEnteryouroption(1or2):")
scanf("%d",&opt)
if(opt!=1&&opt!=2)

{
printf("\n\t\tInvalidOption")
getch()
exit(0)
}
printf("\nEnterPhaseType(1or3)")
scanf("%d",&ph)
if(ph!=1&&ph!=3)
{
printf("\n\t\tInvalidPhase")
getch()
exit(0)
}
clrscr()
printf("\nEnterConsumerNumber:")
scanf("%d",&cno)
printf("\nEnterConsumerName:")
fflush(stdin)
gets(cname)
printf("\nEnterPresentMonthReading:")
scanf("%d",&pmr)
printf("\nEnterLastMonthReading:")
scanf("%d",&lmr)
if(lmr>pmr)
{
printf("\n\t\tInvalidReading")
getch()

exit(0)
}
tu=pmrlmr
switch(opt)
{
case1:
if(tu<=50)
bamt=50*1.45
elseif(tu<=100)
bamt=(50*1.45)+(tu50)*2.80
elseif(tu<=200)
bamt=(50*1.45)+(50*2.80)+(tu100)*3.05
elseif(tu<=300)

bamt=(50*1.45)+(50*2.80)+(100*3.05)+(tu200)*4.75
else

bamt=(50*1.45)+(50*2.80)+(100*3.05)+(100*4.75)+(tu
300)*5.50
pt=0.06*tu

if(ph==1)
sc=10.00
else
sc=20.00
break

case2:
if(tu<=50)
bamt=50*3.95
else
bamt=(50*3.95)+(tu50)*6.20
pt=0.06*tu
if(ph==1)
sc=20.00
else
sc=50.00
break
}
tamt=bamt+pt+sc
clrscr()
printf("\t\t\tConsumerDetails\n")
printf("\n")
printf("\nConsumerNumber:%d",cno)
printf("\nConumerName:%s",cname)
printf("\nPresentMonthReading:%d",pmr)
printf("\nLastMonthReading:%d",lmr)
printf("\nTotalUnits:%d",tu)
printf("\nPowerTax:%.2f",pt)
printf("\nServiceCharge:%.2f",sc)
printf("\nBillAmount:%.2f",bamt)
printf("\nTotalAmount:%.2f",tamt)
getch()
}

Unconditioncontrolstatements:

C supports 3 types of unconditional control statements.


Theyare
1) break
1) continue
1) goto

break :
It is an unconditional control statement and is
usedtoterminateaswitchstatementoraloopstatement.

Syntax:
break

continue:
Itpassedthecontrol

Syntax:
continue

Causes the control to pass to the end of theinnermost


enclosing while, do or for statement, at which point the
loopcontinuationconditionisrevaluated.

goto:Itisunconditioncontrol statementwhichisusedto
altertheexecutionoftheprogramsequencebytransferof
controltosomeotherpartoftheprogram.

Syntax:
gotolabel

Where labelisvalidCidentifierusedtothelabelof
thedestinationsuchthatthecontrolcouldtransferred.

Syntaxoflabel:

identifier:

Program:
nat_goto
.c

To display natural numbers from 1 to given number


usinggotostatement

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn,i=1
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
printf("NaturalNumbersfrom1to%d:",n)
lb:

printf("\t%d",i)
i++
if(i<=n)
gotolb
getch()
}

Program:
goto1
.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn
clrscr()
printf("Entervalueofn:")
scanf("%d",&n)
if(n==1)
gotolb1
if(n==2)
gotolb2
printf("\nWelcome")
lb1:
printf("\nLabel1")
lb2:

printf("\nLabel2")
getch()
}

Program:
goto2
.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn
clrscr()
printf("Entervalueofn:")
scanf("%d",&n)
if(n==1)
gotolb1
if(n==2)
gotolb2
printf("\nWelcome")
gotolb
lb1:
printf("\nLabel1")
gotolb
lb2:
printf("\nLabel2")
lb:
getch()

gotoxy:

It moves the cursor to the given position in the current


textwindow.

Syntax:
voidgotoxy(intx,inty)

xcols
yrows

defaultColumns(80)andRows(25)
Note : If the coordinates are invalid,thecalltogotoxy()
isignored.

Program:
gotoxy
.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
clrscr()
gotoxy(35,12)
printf("WELCOME")
getch()

Program:
st_formt
.c

To calculate and display student result by the following


format

SEASAW
VRSEC

SID:SNAME:

MARKSINC:
MARKSINCPP:
MARKSINJAVA:

TOTALMARKS:AVERAGE:
RESULT:DIVISION:

#include<stdio.h>
#include<conio.h>
voidmain()
{
intsid,c,cpp,java,tot

charsname[20]
floatavg
clrscr()
gotoxy(15,3)
printf("")
gotoxy(28,5)
printf("SEASAW")
gotoxy(33,7)
printf("VRSEC")
gotoxy(15,9)
printf("")
gotoxy(15,11)
printf("SID:")
gotoxy(40,11)
printf("SNAME:")
gotoxy(15,14)
printf("MARKSINC:")
gotoxy(15,16)
printf("MARKSINCPP:")
gotoxy(15,18)
printf("MARKSINJAVA:")
gotoxy(15,21)
printf("TOTALMARKS:")
gotoxy(40,21)
printf("AVERAGE:")
gotoxy(15,23)
printf("RESULT:")

gotoxy(40,23)
printf("DIVISION:")
gotoxy(15,25)
printf("")
gotoxy(21,11)
scanf("%d",&sid)
gotoxy(51,11)
fflush(stdin)
gets(sname)

lb1:
gotoxy(31,14)
scanf("%d",&c)
if(c>100)
{
gotoxy(30,30)
printf("InvalidMarksofC")
getch()
gotoxy(30,30)
printf("")
gotoxy(31,14)
printf("")
gotolb1
}
lb2:
gotoxy(31,16)
scanf("%d",&cpp)

if(cpp>100)
{
gotoxy(30,30)
printf("InvalidMarksofCPP")
getch()
gotoxy(30,30)
printf("")
gotoxy(31,16)
printf("")
gotolb2
}
lb3:
gotoxy(31,18)
scanf("%d",&java)
if(java>100)
{
gotoxy(30,30)
printf("InvalidMarksofJava")
getch()
gotoxy(30,30)
printf("")
gotoxy(31,18)
printf("")
gotolb3
}
tot=c+cpp+java
avg=(float)tot/3

gotoxy(31,21)
printf("%d",tot)
gotoxy(51,21)
printf("%.2f",avg)
if(c>=50&&cpp>=50&&java>=50)
{
gotoxy(31,23)
printf("PASS")
gotoxy(51,23)
if(avg>=60)
printf("FIRST")
else
printf("SECOND")
}
else
{
gotoxy(31,23)
printf("FAIL")
gotoxy(51,23)
printf("NODIVISION")
}
getch()
}

Loopcontrolstatements:

Theprocessofrepeatedlyexecutingablockofstatement
uptospecifiednumberoftimesiscalledasloop.

Csupports3typesofloopingstatements.Theyare:

1)whileloop
2)dowhileloop
3)forloop

Whileloop(Entrycontrolloopstatement):

It is a conditional controlled loop statement in C


language.

Syntax:

while(testcondition)
{
Statements
}

Inthisloopfirstthetestconditionwillbeevaluated.
If it is true, then the statement block will be executed.
After the execution of statements, the test condition will
be evaluated once again, if it is true then the statement
block will be executed once again. This process of

repeated execution continued until the test condition


becomesfalse.

Program:
nnos_w
.c

Toprintnaturalnumbersfrom1togivennumber

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn,i=1
printf("Enteranumber:")
scanf("%d",&n)
printf("Naturalnumberfrom1to%d\n\n",n)
while(i<=n)
{
printf("\t%d",i)
i++
}
getch()
}

Program:
ev_od_w
.c

Todisplayevenandoddnumbersfor1togivennumber

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn,i
printf("Enteranumber:")
scanf("%d",&n)
printf("\n\nEvennumbersfrom1to%d\n\n",n)
i=1
while(i<=n)
{
if(i%2==0)
printf("\t%d",i)
i++
}
printf("\n\n\nOddnumbersfrom1to%d\n\n",n)
i=1
while(i<=n)
{
if(i%2==1)//if(i%2!=0)
printf("\t%d",i)
i++
}
getch()
}


Program:
nsum_w
.c

Toprintsumofnaturalnumbersfor1togivennumber

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn,i=1,sum=0
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
while(i<=n)
{
sum=sum+i
i++
}
printf("Sumof%dnaturalnumbersis%d",n,sum)
getch()
}

Note:

We can also find the sum of


n digits by the following
formula:
Sum=n*(n+1)/2

Program:
facts_w
.c

Todisplayfactorsofgivennumber

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn,i=1
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
printf("\n\nFactorsofgivennumber:\n\n")
while(i<=n)
{
if(n%i==0)
printf("\t%d",i)
i++
}
getch()
}

Program:
facto_w
.c

Tofindfactorialofgivennumber


#include<stdio.h>
#include<conio.h>
voidmain()
{
intn
unsignedlongfact=1
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
while(n>=1)
{
fact=fact*n
n
}
printf("\n\nFactorialof%dis%lu",n,fact)
getch()
}

Program:
ndig_w
.c

Tofindnumberofdigitsinthegivennumber

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

intcount=0
unsignedlongn
clrscr()
printf("Enteranumber:")
scanf("%lu",&n)
while(n>0)
{
n=n/10
count++
}
printf("\n\nNumber of digits of given number : %d
",count)
getch()
}

Program:
sumdig_w
.c

Tofindsumofdigitsinthegivennumber

#include<stdio.h>
#include<conio.h>
voidmain()
{
intsum=0
unsignedlongn
clrscr()
printf("Enteranumber:")

scanf("%lu",&n)
while(n>0)
{
sum=sum+(n%10)
n=n/10
}
printf("\n\nSumofdigitsofgivennumber:%d",sum)
getch()
}

Program:
rev_w
.c

To find reverse number of a given number using while


loop

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn
unsignedlongrev=0
printf("Enteranumber:")
scanf("%d",&n)

while(n>0)
{
rev=(rev*10)+(n%10)
n=n/10
}
printf("Reversenumberofgivennumber:%lu",rev)
getch()
}

Program:
sum_dig1
.c

Tofindsumofdigitsofgivennumber(finalsum)

#include<stdio.h>
#include<conio.h>
voidmain()
{
unsignedlongn
intsum=0
printf("Enteranumber:")
scanf("%d",&n)
while(n>0)
{
sum=sum+(n%10)
n=n/10

}
printf("Sumofdigits:%d",sum)
getch()
}

Program:
sum_dig2
.c

Tofindsumofdigitsofgivennumber
#include<stdio.h>
#include<conio.h>
voidmain()
{
unsignedlongn
intsum=0
printf("Enteranumber:")
scanf("%lu",&n)
while(n>0)
{
sum=sum+(n%10)
n=n/10
if(n==0&&sum>9)
{
printf("\n%d\n",sum)
n=sum
sum=0
}
}

printf("Sumofdigits:%d",sum)
getch()
}

Note:

Ifanynumberexactlydivideswith9,thensumofdigits=
9, otherwise its remainder value will be sum ofitsdigits.
Theaboveprogramdependsonthistechnique.

Program:
rev1_w
.c

Tofindreversenumberofagivennumber

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn,count=0
unsignedlongrev=0
printf("Enteranumber:")
scanf("%d",&n)
while(n>0)
{
rev=(rev*10)+(n%10)
n=n/10
count++

printf("Reverse number of given number :


%*lu",count,rev)
getch()
}

If n=1000, then we will get the reverse number as 1, i.e.


zeros are not displayed, if we use the above format, the
compiler will format it and gives the output as 0001,this
is because the number of digits in the given number, i.e.
count=4andthevalueofthiscountisassignedto*,and
hencetheoutputhave4digits.i.e.0001incaseofn=1000

Program:
pal_w
.c

To check whether the given number is palindrome or


not

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn,m,rev=0
printf("Enteranumber:")
scanf("%d",&n)
m=n
while(m>0)

{
rev=(rev*10)+(m%10)
m=m/10
}
if(n==rev)
printf("GivennumberisaPalindrome")
else
printf("GivennumberisnotPalindrome")
getch()
}

Program:
prime_w
.c

Tocheckwhetherthegivennumberisprimeornot

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn,i=1,count=0
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
while(i<=n)
{
if(n%i==0)
count++

i++
}
if(count==2)
printf("GivennumberisPrime")
else
printf("GivennumbrisnotPrime")
getch()
}

Program:
fibo_w
.c

Togeneratefibonacciseriesuptonterms

#include<stdio.h>
#include<conio.h>
voidmain()
{
intm,n,a=1,b=0,c=0
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
printf("Fibonacciseries:")
while(n>=1)
{
printf("\t%d",c)
c=a+b
a=b

b=c
n
}
getch()
}

Program:
ev_od1_w
.c

Tocheckwhetherthegivennumberisevenorodd

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn,i=2,k=1
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
while(k<=2)
{
if(i==2)
printf("Evennumbersfrom1to%d",n)
if(i==1)
printf("Oddnumbersfrom1to%d",n)
printf("%d\t",i)

i=i+2
if(i>n)
{
i=1
k++
}
}
}

dowhileloop:(exitcontrolloopstatement)

It is an alternative form of while loop. The only


difference between while and dowhile is the minimum
number of execution of while is zero and the minimum
numberofexecutionofdowhileisone.

Syntax:

do
{
Statements
}
while(testcondition);

In this loop first the statement block will be executed,

aftertheexecutionofstatements,thetestconditionwillbe
evaluated. If it is true, then the statement block will be
executed once again, this process of repeated execution
continuousuntilthetestconditionbecomesfalse.


Program:
nat_dw
.c

Programs to display natural number from 1 to given


numberisusingdowhileloop

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn,i=1
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
printf("\nNaturalnumbersfrom1to%d:",n)
do
{
printf("\t%d",i)
i++
}while(i<=n)

getch()

forloop:

It is the most commonly used loop statement in C


language.Itisconsistingof3expressions.

Syntax:

for(exp1;exp2;exp3)
{
Statements;
}

In this loop first expression is used to initialize the


index, second expression is used to test whether the loop
is to be continued or not (test condition) and the third
expression is used to change the index for further
iteration.

Program:
nat_for
.c

Programs to display natural number from 1 to given


numberisusingforloop

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn,i
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
printf("\nNaturalnumbersfrom1to%d\n\n",n)
for(i=1i<=ni++)
{
printf("\t%d",i)
}
getch()
}

Program:
rev_for
.c

To find reverse number of a given number using for


loop

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

{
intn
unsignedlongrev
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
for(rev=0n>0n=n/10)
{
rev=(rev*10)+(n%10)
}
printf("Reversenumberofgivennumber:%lu",rev)
getch()
}

Program:
perfect
.c

To check whether the given number is perfect number


ornot

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn,i,sum=0
clrscr()
printf("Enteranumber:")

scanf("%d",&n)
for(i=1i<=n/2i++)
{
if(n%i==0)
sum=sum+i
}
if(n==sum)
printf("GivennumberisPerfectnumber")
else
printf("GivennumberisnotPerfectnumber")
getch()
}

Perfectnumber:

If a given number = sum of its divisibles except that


number,iscalledasperfectnumber.

Eg:

6,28,496etc

Program:
armst
.c

To check whether the given number is armstrong


numberofnot

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

voidmain()
{
intn,sum=0,m,r
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
m=n
while(m>0)
{
r=m%10
sum=sum+(r*r*r)
m=m/10
}
if(n==sum)
printf("GivennumberisArmstrongnumber")
else
printf("GivennumberisnotArmstrongnumber")
getch()
}

Program:
table
.c

To display multiplication table of given number from 1


to20

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

voidmain()
{
intn,i
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
for(i=1i<=20i++)
{
printf("\n%d*%d=%d",n,i,n*i)
}
getch()
}

Program:
continue
.c

To display natural numbers from 1 to 100 except 40,50


and60

#include<stdio.h>
#include<conio.h>
voidmain()
{
inti=0
clrscr()
while(i<100)
{
i++

if(i==40||i==50||i==60)
continue
printf("%d\t",i)
}
getch()

Program:
gcd
.c

TofindGCDofgiven2numbers

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta,b,g,i
clrscr()
printf("Enter2numbers:")
scanf("%d%d",&a,&b)
for(i=1i<=a&&i<=bi++)
{
if(a%i==0&&b%i==0)
g=i
}

printf("GCDofgivennumbers:%d",g)
getch()
}

Eg:

GCDof10and20=10
10%10 = 0 and 20%10 = 0 also (10,20)%2 = 0 and
(10,20)%5 = 0, but the greatest of 2, 5 and 10 is 10.
HenceGCD=10.

Program:
lcm
.c

WriteaprogramTofindLCMofgiven2numbers
#include<stdio.h>
#include<conio.h>
voidmain()
{
inta,b,lcm
clrscr()
printf("Enter2numbers:")
scanf("%d%d",&a,&b)
if(a>b)
lcm=a
else
lcm=b

while(1)

{
if(lcm%a==0&&lcm%b==0)
break
lcm++
}
printf("LCDofgivennumbers:%d",l)
getch()
}

Eg:

LCMof10and15is30
30%10=0and30%10=0

2ndMethod

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta,b,lcm
clrscr()
printf("Enteranytwonumbers:")
scanf("%d%d",&a,&b)

if(a>b)
lcm=a
else
lcm=b

while(lcm%a!=0||lcm%b!=0)
{
lcm++
}
printf("Lcmof%dand%dis%d",a,b,lcm)
getch()
}

Nestedloops:

Using a loop statement, within another loop is called as


nestedloop.

Program:
prime_nl
.c

Todisplayprimenumbersfrom1togivennumber

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

{
intn,i,j,count
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
printf("PrimeNumbersfor1to%d\n",n)
for(i=1i<=ni++)
{
count=0
for(j=1j<=ij++)
{
if(i%j==0)
count++
}
if(count==2)
printf("\t%d",i)
}
getch()
}

Program:
prm2_nl
.c

Todisplayprimenumbersbetweengiven2numbers

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

{
intn1,n2,i,j,count
clrscr()
printf("Enterstartingnumber:")
scanf("%d",&n1)
printf("Enterendingnumber:")
scanf("%d",&n2)
for(i=n1i<=n2i++)
{
count=0
for(j=1j<=ij++)
{
if(i%j==0)
count++
}
if(count==2)
printf("\t%d",i)
}
getch()
}

Program:
pal_nl
.c

TodisplayPalindromenumbersfrom1ton

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

voidmain()
{
intn,rev,m,i
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
for(i=1i<=ni++)
{
rev=0
m=i
while(m>0)
{
rev=(rev*10)+(m%10)
m=m/10
}
if(rev==i)
printf("\t%d",i)
}
getch()
}

Program:
perf_nl
.c

Todisplayperfectnumbersfrom1togivennumber

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

voidmain()
{
intn,i,j,sum=0
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
printf("PerfectNumbersbetween1and%d:",n)
for(i=1i<=ni++)
{
sum=0
for(j=1j<=i/2j++)
{
if(i%j==0)
sum=sum+j
}
if(sum==i)
printf("\t%d",i)
}
getch()
}

Program:
armst_nl
.c

TodisplayArmstrongnumbersfrom1togivennumber

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

voidmain()
{
intn,m,r,arm,i
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
printf("Armstrongnumbersfrom1to%d:\n",n)
for(i=1i<=ni++)
{
arm=0
m=i
while(m>0)
{
r=m%10
arm=arm+(r*r*r)
m=m/10
}
if(arm==i)
printf("\t%d",i)
}
getch()
}

Program:
prm_fact
.c

TocalculateanddisplayPrimeFactorsofgivennumber

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn,i
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
printf("PrimeFactorof%d:\n",n)
while(n>1)
{
i=2
while(1)
{
if(n%i==0)
{
printf("\t%d",i)
n=n/i
break
}
else
i++
}
}
getch()
}


Formattingtheoutput:

Integer:

1.intn=100
printf(%d,n)

Output:
100

2.intn=100
printf(%5d,n)

Output:
100

2spaces

3.intn=100
printf(%5d,n)

Output:
100

2spaces

4.intn=5

printf(%.2d,n)

Output:
05

5.intn=5
printf(%.3d,n)

Output:
005

Character:

1.charc=R
printf(%c,c)

Output:
R

2.charc=R
printf(%4c,c)

Output:
R

3spaces

3.charc=R
printf(%4c,c)


Output:
R

3spaces

Float:

1.floatf=14.1718
printf(%f,f)

Output:
14.171800

2.floatf=14.1718
printf(%12f,f)

Output:
14.171800

3spaces

3.floatf=14.1718
printf(%12f,f)

Output:
14.171800

3spaces

4.floatf=14.1718
printf(%.2f,f)

Output:
14.17


5.floatf=14.1718
printf(%7.2f,f)

Output:
14.17


2spaces

In 7.2, 7 indicates total number of digits including


decimalpoint,2representsnumberofdigitsafterdecimal
point.

String:

1.charst[10]=welcome
printf(%s,s)

Output:
welcome

2.charst[10]=welcome
printf(%9s,s)

Output:
welcome

2spaces

3.charst[10]=welcome
printf(%9s,s)

Output:
welcome

2spaces

4.charst[10]=welcome
printf(%.3s,s)

Output:
wel

Otherimportantformats:

1.intn=100,x=5
printf(%xd,x,n)

printf(%5d,n)

Output:
100


2spaces

2.charst[10]=welcome
intx=3
printf(%.*s,x,st)

printf(%.3s,st)

Output:
wel

Program:
patrn1
.c

Togeneratethegivenpattern

w
we
wel
welc
welco
welcom
welcome

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

intx
charst[10]="welcome"
clrscr()
for(x=1x<=7x++)
{
printf("\n%.*s",x,st)
}
getch()
}

textmode():

Itchangesscreenmode(intextmode).

Syntax:
voidtextmode(intnewmode)

ConstantValueTextmode

LASTMODE1Previoustextmode

BW40
0
Black and White
40columns

C40
1
Color
40columns

BW80
2
Black and White
80columns

C80
3
Color
80columns

MONO
7
Monochrome
80columns

C4350
64
EGA (Enhanced
43line
graphicadapter)

VGA (Video
50line
graphicadapter)

Program:
txtmode1
.c

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

textmode(1)//ortextmode(C40)
gotoxy(17,12)
printf("RAJI")
getch()
}

Program:
txtmode2
.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
inti
clrscr()
textmode(64)//ortextmode(C4350)
for(i=1i<=45i++)
{
printf("\nRAJI")
}
getch()
}

textcolor():

Itselectsanewcharactercolorintextmode.

Syntax:
voidtextcolor(intnewcolor)


teextbackground():

Itselectsanewtextbackgroundcolor

Syntax:
voidtextbackground(intnewcolor)
color(textmode):

Constant
Value
Background
Foreground

BLACK
0
Yes
Yes

BLUE
1
Y
Y

GREEN
2
Y
Y

CYAN
3
Y
Y

RED
4
Y
Y


MAGENTA
Y

BROWN
Y

LIGHT GREY
Y

DARK GREY
Y

LIGHT BLUE
Y

LIGHT GREEN
Y

LIGHT CYAN
Y

LIGHT RED
Y

LIGHT MAGENTA
Y

5
6

Y
Y

10

11

12

13


YELLOW
14
N
Y

WHITE
15
N
Y

cprintf():

It is same as printf(). If we want to display colors in text


mode,weusecprintf().

Program:
txtmode3
.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
clrscr()
textmode(1)
textcolor(RED+BLINK)
textbackground(WHITE)
gotoxy(17,12)
cprintf("RAJI")
getch()

Program:
patrn2
.c

Togeneratethefollowingpattern

*****
*****
*****
*****
*****

#include<stdio.h>
#include<conio.h>
voidmain()
{
inti,j,n
clrscr()
printf("Entervalueofn:")
scanf("%d",&n)
for(i=1i<=ni++)
{
for(j=1j<=nj++)
{
printf("%2c",'*')
}
printf("\n")

}
getch()

Program:
patrn3
.c

Togeneratethefollowingpattern

*
**
***
****
*****

#include<stdio.h>
#include<conio.h>
voidmain()
{
inti,j,n
clrscr()
printf("Entervalueofn:")
scanf("%d",&n)
for(i=1i<=ni++)
{
for(j=1j<=ij++)

{
printf("%2c",'*')
}
printf("\n")
}
getch()
}

Program:
patrn4
.c

Togeneratethefollowingpattern

1
22
333
4444
55555

#include<stdio.h>
#include<conio.h>
voidmain()
{
inti,j,n
clrscr()
printf("Entervalueofn:")
scanf("%d",&n)

for(i=1i<=ni++)
{
for(j=1j<=ij++)
{
printf("%3d",i)
}
printf("\n")
}
getch()
}

Program:
patrn5
.c

Togeneratethefollowingpattern

1
12
123
1234
12345

#include<stdio.h>
#include<conio.h>
voidmain()
{
inti,j,n
clrscr()

printf("Enteranumber:")
scanf("%d",&n)
for(i=1i<=ni++)
{
for(j=1j<=ij++)
{
printf("%3d",j)
}
printf("\n")
}
getch()
}

Program:
patrn6
.c

Togeneratethefollowingpattern

*
**
***
****
*****

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

{
inti,j,k,n,s
clrscr()
printf("Entervalueofn:")
scanf("%d",&n)
s=n*2
for(i=1i<=ni++)
{
/*
for(k=1k<=sk++)
{
printf("")
}

or*/

printf("%*c",s,32)
for(j=1j<=ij++)
{
printf("%4c",'*')
}
printf("\n")
s=s2
}
getch()
}

Program:
patrn7
.c

Togeneratethefollowingpattern

1
22
333
4444
55555

#include<stdio.h>
#include<conio.h>
voidmain()
{
inti,j,k,n,s
clrscr()
printf("Entervalueofn:")
scanf("%d",&n)
s=n*2
for(i=1i<=ni++)
{
for(k=1k<=sk++)
{
printf("")
}
for(j=1j<=ij++)

{
printf("%4d",i)
}
printf("\n\n")
s=s2
}
getch()
}

Program:
patrn8
.c

Togeneratethefollowingpattern

*
**
***
****
*****
****
***
**
*

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

{
inti,j,k=1,n,s
clrscr()
printf("Entervalueofn:")
scanf("%d",&n)
s=n*2
for(i=1i<=n*2i++)
{
printf("%*c",s,32)
for(j=1j<=kj++)
{
printf("%4c",'*')
}
if(i<n)
{
s=s2
k++
}
else
{
s=s+2
k
}
printf("\n")
}
getch()
}


Program:
patrn9
.c

Togeneratethefollowingpattern

12345
109876
1112131415
2019181716
2122232425

#include<stdio.h>
#include<conio.h>
voidmain()
{
inti,j,n,k=1
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
for(i=1i<=ni++)
{
for(j=1j<=nj++)
{
printf("%4d",k)
if(j<n)

{
if(i%2==0)
k
else
k++
}
}
printf("\n")
k=k+n
}
getch()
}

Program:
patrn10
.c

Togeneratethefollowingpattern

12345
51234
54123
54312
54321

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

inti,j,k,n,m
clrscr()
printf("Entervalueofn:")
scanf("%d",&n)
m=n
for(i=1i<=ni++)
{
for(j=nj>mj)
{
printf("%3d",j)
}
for(k=1k<=mk++)
{
printf("%3d",k)
}
printf("\n")
m
}
getch()
}

Program:
patrn11
.c

Togeneratethefollowingpattern

ABCDEFGFEDCBA
ABCDEFFEDCBA

ABCDEEDCBA
ABCDDCBA
ABCCBA
ABBA
AA

*/

#include<stdio.h>
#include<conio.h>
voidmain()
{
inti,j,p,x=7,y=7
clrscr()
for(i=1i<=7i++)
{
p=65
for(j=1j<=13j++)
{
if(i>1&&(j>=x&&j<=y))
printf("%2c",32)
else
printf("%2c",p)
if(j<7)
p++
else

p
}
printf("\n")
if(i>1)
{
x
y++
}
}
getch()
}

Program:
patrn12
.c

Togeneratethefollowingpattern

ABCDEFGFEDCBA
ABCDEFFEDCBA
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()
for(i=1i<=7i++)
{
p=65
for(j=1j<=13j++)
{
if(i>1&&(j>=x&&j<=y))
printf("%2c",32)
else
printf("%2c",p)
if(j<7)
p++
else
p
}
printf("\n")

if(i>1)
{
if(i<7)
{
x
y++
}
else
{
x++
y
}
}
}
getch()
}

delay():
<dos.h>

It suspends execution for specified interval (milli


seconds)

Syntax:
voiddelay(unsignedmilliseconds)

kbhit():

Itchecksforcurrentlyavailablekeystrokes.

Syntax:
intkbhit()

_setcursortype():

Itselectscursorappearance.

Syntax:
void_setcursortype(intcur_t)

cur_t:
setthecursortypetooneofthefollowing

1. _NOCURSOR:turnofthecursor
1. _SOLIDCURSOR:solidblockcursor
1. _NORMALCURSOR
: normal underscore
cursor

Program:
rajiram
.c

#include<stdio.h>
#include<conio.h>
#include<dos.h>
voidmain()
{
intc=1,c1=36,r=1
textmode(1)

_setcursortype(_NOCURSOR)
while(!kbhit())
{
textbackground(WHITE)
clrscr()
textcolor(BLUE)
gotoxy(c,12)
cprintf("raji)
textcolor(RED)
gotoxy(c1,12)
cprintf("ram")
textcolor(MAGENTA)
gotoxy(18,r)
cprintf("WEDS")
c++
c1
r++
if(c>36)
{
c=1
c1=36
}
if(r>25)
r=1
delay(150)
}
getch()

FunctionsinC:
Function:
Function is a self contained block of statements and it
performsaparticulartask.Itcanbeusedatseveraltimes
inaprogram,butdefinedonlyonce.

Theyareof2types.
1. Libraryfunctions(or)predefinefunctions
1. Userdefinedfunctions.
Libraryfunctions:

The functions which are Inbuilt with the compiler are


knownasLibraryfunctions(or)Predefinedfunctions.
Eg:
1 printf
1 scanf
2 getch
3 clrscr,etc.

Userdefinedfunctions:

User can define functions to do a task relavant to their


program.
suchfunctionsarecalledasuserdefinedfunctions.

Anyfunction( eitherpredefined(or)userdefined)has3
things.

1. Functiondeclaration
1. Functiondefinition
1. Functioncalling

In case of Library functions(predefined), the function


declaration is in header files, function definition is in C
libraries and function calling is in source program. But
in case of user defined functions all three things are in
sourceprogram.

Functiondeclaration:

Syntax:
returntypefunction_name([arguments_list])

Functiondefinition:

Syntax:

returntypefunction_name([arguments_list])

{
statements
}

Functioncalling:

Syntax:

function_name([parameter_list])

Note:
The arguments which are given at the time of function
declaration or function definition are called as arguments
or formal arguments. The arguments which are given at
the time of function calling are called as parameters or
actualarguments.

Eg:
#include<stdio.h>
#include<conio.h>
voidmain()
{
voidfunc()//declaration
clrscr()
func()//calling

getch()
}

voidfunc()//definition
{
printf(WeclometoCFunctions)
}

RulesforCreatingandaccessingfunctions:

1. Afunctioncanbecalledbyanynumberoftimes
2. Afunctionmayormaynotreceivearguments.
3. Afunctionmayormaynotreturnavalue
1. If a function doesnot return any value, the function
returndatatypewillbespecifiedas
void.
1. If A function returns a value ,only one value it can
bereturned.
1. If a function returnrs a value, the returning value
mustbereturnedwithstatement"return".
1. If a function returns a value ,the execution of the
statementshouldbelast.
1. If we cannot specify any returntype, the function
returnsanintbydefault.
1. A function returns avalue, thereturningvalueshould
matchwiththefunctionreturndatatype.

1.

A function is defined after or before the main


function.

1.

2.

3.

4.

1.

Before calling a function, the function declaration or


definitionismustandshould.
If a function definition is specified before the
function call, then the function declaration is not
necessary.
Afunctionisexecutedwhenthefunctioniscallbyits
name.
If a function returns a value,the return value is
replacedbyfunctioncallingstatement.
Thefunctiondefinitionshouldnotbeterminatedwith
asemicolon()

return(keyword):

Exitsimmediatelyfromthecurrentlyexecutingfunction
tothecallingroutine,optionallyreturningavalue.
Syntax:

return[<expression>]

Example:
ret_max
.c

Tofindmaximumvalueofgiven2numbers

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

{
intmaxval(int,int)
inta,b,m
clrscr()
printf("Enteranytwonumbrs:")
scanf("%d%d",&a,&b)
m=maxval(a,b)
printf("MaximumValue:%d",m)
getch()
}
intmaxval(intx,inty)
{
if(x>y)
returnx
else
returny
}

FunctioncategoriesorFunctionprototypes:

A function ,depending on whether arguments are

presentornot
and whethervalueisreturningornot,maybelongstoone
ofthefollowingcategories.
1. Functionwithnoargumentsandreturnnovalue.
1. Functionwithargumentsandnoreturnvalue.
1. Functionwithargumentsandreturnvalue.
1. Functionwithnoargumentsandreturnvalue.

Functionwithnoargumentsandnoreturnvalue:

In this type the function has no arguments, it doesnot


receive any data from the calling function. Similarly it
doesnot return any value, the calling function doesnot
receive any data from called function. Sothereisnodata
communication between calling function and called
function.

Example:

cat1.c

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

getch()
}
voidsum()
{
inta,b
printf(Enteranytwonumbers:)
scanf("%d%d",&a,&b)
printf(sum=%d,a+b)
}

Functionwithargumentsandnoreturnvalue:

In this type the function has some arguments, it


receives data from the calling function. But it doesnot
return any value, thecallingfunctiondoesnotreceiveany
data from the called function. So there is one way data
communication between calling function and called
function.

Example
:cat2.c

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

inta,b,s
clrscr()
printf(Enteranytwonumbers:)
scanf("%d%d",&a,&b)
sum(a,b)
getch()
}
voidsum(intx,inty)
{
printf(sum=%d,x+y)
}

Functionwithargumentsandreturnvalue:

Inthistypethefunctionhassomearguments,itreceives
datafromthecallingfunction.Similarlyitreturnsavalue,
the calling function receives data from the called
function. So there is two way data communication
betweencallingfunctionandcalledfunction.

Example:
cat3.c

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

inta,b,s
clrscr()
printf(Enteranytwonumbers:)
scanf("%d%d",&a,&b)
s=sum(a,b)
printf(sum=%d,s)
getch()
}
intsum(intx,inty)
{
returnx+y
}

Functionwithnoargumentsandreturnvalue:

In this type the function has no arguments, it doesnot


receiveanydatafromthecallingfunction.Butitreturnsa
value, the calling function receives data from the called
function. So there is one way data communication
betweencallingfunctionandcalledfunction.

Example:
cat4.c

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

voidmain()
{
intsum()
ints
clrscr()
s=sum()
printf("sum=%d",s)
getch()
}
intsum()
{
inta,b
printf(Enteranytwonumbers:)
scanf("%d%d",&a,&b)
returna+b
}

Program:
fn_max
.c

Tofindmaximumvalueofgiven2numbers

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

voidmain()
{
intmaxval(int,int)
inta,b,c,m
clrscr()
printf("Enter3numbrs:")
scanf("%d%d%d",&a,&b,&c)
m=maxval(a,b)
m=maxval(m,c)
printf("MaximumValue:%d",m)
getch()
}
intmaxval(intx,inty)
{
if(x>y)
returnx
else
returny
}

Program:
nnos_fn
.c

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

voiddisp(int)
intn
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
disp(n)
getch()
}
voiddisp(intx)
{
inti
for(i=1i<=xi++)
{
printf("%d\t",i)
}
}

Program:
fact_fn
.c

Tocalculatefactorialofgivennumber

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

unsignedlongf
clrscr()
printf("Entranumber:")
scanf("%d",&n)
f=fact(n)
printf("Factorialof%d:%lu",n,f)
getch()
}
unsignedlongfact(intx)
{
unsignedlongf=1
while(x>=1)
{
f=f*x
x
}
returnf
}

Program:
rev_fn
.c

Todisplayreversenumberofgivennumber

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

unsignedlongrev(int)
intn
unsignedlongr
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
r=rev(n)
printf("Reversenumberof%d:%lu",n,r)
getch()
}
unsignedlongrev(intx)
{
unsignedlongr=0
while(x>0)
{
r=r*10+(x%10)
x=x/10
}
returnr
}

Program:
fibo_fn
.c

Togeneratefibonacciseries

#include<stdio.h>

#include<conio.h>
voidmain()
{
voidfibo(int)
intn
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
printf("Fibonacciseries\n")
fibo(n)
getch()
}
voidfibo(intx)
{
inti,a=0,b=1,c
printf("%d\t%d",a,b)
for(i=1i<=x2i++)
{
c=a+b
printf("\t%d",c)
a=b
b=c
}
}

Program:
lcm_gcd
.c

TofindLCMandGCDofgivennumbers

#include<stdio.h>
#include<conio.h>
voidmain()
{
intlcm(int,int)
intgcd(int,int)
intl,g,a,b
clrscr()
printf("Enter2numbers:")
scanf("%d%d",&a,&b)
l=lcm(a,b)
g=gcd(a,b)
printf("LCMof%dand%d:%d\n",a,b,l)
printf("GCDof%dand%d:%d",a,b,g)
getch()
}
intlcm(intx,inty)
{
intlm
if(x>y)
lm=x
else
lm=y
while(1)
{

if(lm%x==0&&lm%y==0)
break
lm++
}
returnlm
}
intgcd(intx,inty)
{
intgd,i
for(i=1i<=x&&i<=yi++)
{
if(x%i==0&&y%i==0)
gd=i
}
returngd
}

1
(n=0,r=0)
nvalues
11
(n=1,r=0)(n=1,r=1)

121
(n=2,r=0)(n=2,r=1)(n=2,r=2)

1
3
3

(n=3,r=0)
(n=3,r=1)
(n=3,r=2)
(n=3,r=3)

1
4
6
4
1
(n=4,r=0)
(n=4,r=1)
(n=4,r=2)
(n=4,r=3)
(n=4,r=4)

rvalues

Storageclasses:

By the declaration statement the memory is allocated


temporarily for all the variables. The size of memory
varies with respect to the type of the variable. The
availability of the variables for access depends on its
declarationtype.

The storage class specifiers are used to specify the


life and scopeof the variableswithinblocks,functions
andtheentireprogram.

There are 4 types of storage classes supported by C


language
Namely

1)
1)
1)
1)

automaticvariables

staticvariables

externalorglobalvariables
registervariables

automaticvariables:

Thesevariablesaredeclaredinsideafunctionblock.
Ifthereisnostorageclassspecifierbeforethedeclaration
ofanyvariableinsideafunctionblock,bydefaultittakes
autostorageclass.

Storage:
mainmemory
Defaultvalue:
garbagevalue
Scope:
Localtotheblockinwhichitisdefined
Life
:T
illthecontrolremainswithintheblock
in
whichitisdefined
Keyword:
auto

Program:
auto1
.c

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

{
autointa,b
clrscr()
printf("\na=%d",a)
printf("\nb=%d",b)
getch()
}

Note
: The declaration of auto variables as global
variablesinnotallowed

staticvariables:

Thememoryofstaticvariablesremainsunchangeduntil
theendoftheprogram.

Storage:
mainmemory

Defaultvalue:
zero

Scope:
localtotheblockinwhichitisdefined

Life
: T
he value of static variable persists
betweendifferent

function calls ( itcannotreinitializes


between

differentfunctioncalls)

Keyword:
static

Program:
static1
.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
staticinta,b
clrscr()
printf("\na=%d",a)
printf("\nb=%d",b)
getch()
}

Program:
static2
.c

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

inti
clrscr()
for(i=1i<=10i++)
{
disp()
}
getch()
}
voiddisp()
{
staticintn=1
printf("%d\t",n)
n++
}
Output
12345678910

Here n is static, it cannot reinitializes between function


calls, once ifitdeclared,itwillreinitializes oncetheloop
terminates.

Alsoifwedeclarenasautomaticvariable,wewillget

1111111111

externalorglobalvariables:


Thevariablesthatarebothaliveandactivethroughoutthe
entireprogramareknownasglobalvariables.

Storage:
mainmemory
Defaultvalue:
zero
Scope:
global
Life
:A
slongastheprogramexecutiondoesnot
come
toend
Keyword:
extern

Program:
extern1
.c

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

clrscr()
printf("\na=%d",a)
printf("\nb=%d",b)
getch()
}


Program:
extern2
.c

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

printf("a=%d",a)
getch()
}
inta=100

Note:

Without the keyword


extern in main() block,we willget
garbage values of
a
. This is because
a becomes local to
main().

Registervariables:

We can use register variables for frequently used


variables to improve the faster execution of program.
Thesevariablesarealsodeclaredinsideafunctionblock.


Storage:
CPUregister
Defaultvalue:
Garbagevalue
Scope:
Localtotheblockinwhichitisdefined
Life
:T
illthecontrolwithintheblockinwhich
itis
defined
Keyword:
register

Note:

Itsupportsonlyintegraldatatype(intandchar)

Program:
register
.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
registerinta,b
clrscr()
printf("\na=%d",a)
printf("\nb=%d",b)
getch()
}


RecursiveFunction:

Calling afunctionwithinthesamefunctiondefinitionis
calledasrecursivefunction.
If we want to work with recursive function, we must
followthefollowing2aspects.
1) Callingbyitself
1) Terminationcondition

Program:
nnos_rfn
.c

To display natural numbers from 1 tonusingrecursive


function

#include<stdio.h>
#include<conio.h>
voidmain()
{
voiddisp(int)
intn
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
printf("Naturalnumbersfrom1to%d:\n\n",n)
disp(n)

getch()
}
voiddisp(intx)
{
if(x>1)
disp(x1)
printf("%d\t",x)
}

Note:

If we want to display number from 100 to 1, write the


printf(%d\t,x) statement as the first statement in
recursivemethod.

Program:
fact_rfn
.c

To find factorial of given number using recursive


function

#include<stdio.h>
#include<conio.h>
voidmain()
{
unsignedlongfact(int)
intn
unsignedlongf

clrscr()
printf("Enteranumber:")
scanf("%d",&n)
f=fact(n)
printf("Factorialof%dis%lu",n,f)
getch()
}
unsignedlongfact(intx)
{
if(x<=1)
return1
else
returnx*fact(x1)
}

Program:
ncr_rfn
.c

Tofindncrvalueusingrecursivefunction

#include<stdio.h>
#include<conio.h>
voidmain()
{
unsignedlongfact(int)
intn,r,ncr
printf("Enternandrvalues:")
scanf("%d%d",&n,&r)

ncr=fact(n)/(fact(nr)*fact(r))
printf("ncrvalue:%d",ncr)
getch()

nsignedlongfact(intx)
{
if(x<=1)
return1
else
returnx*fact(x1)
}

Calculatingncrvalues:

4c2=6

(4*5)/(1*2)

8c3=56

(8*7*6)/(1*2*3)

Program:
pascal
.c

TodisplayPascalTriangle

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

inti,j,k,n,ncr,s
printf("Enternvalue:")
scanf("%d",&n)
s=n*2
for(i=0i<=ni++)
{
/*for(k=1k<=sk++)
{
printf("")
}*/
printf("%*c",s,32)
for(j=0j<=ij++)
{
ncr=fact(i)/(fact(ij)*fact(j))
printf("%d",ncr)
}
printf("\n\n")
s=s2
}
getch()
}
unsignedlongfact(intx)
{
if(x<=1)
return1
else
returnx*fact(x1)

Program:
rev_rfn
.c

Tofindreverse numberofgivennumberusingrecursive
function

#include<stdio.h>
#include<conio.h>
voidmain()
{
unsignedlongrev(int)
unsignedlongr
intn
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
r=rev(n)
printf("Reversenumber:%lu",r)
getch()
}
unsignedlongrev(intx)
{
staticunsignedlongr=0
r=(r*10)+(x%10)

x=x/10
if(x>0)
rev(x)
returnr
}
Note:

Ifwedeclare
rasautomaticvariable,we willgetonlythe
last digit of the resultant number as output. Because for
each function call
r is initializedtozeroandonlythelast
iteration value is stored in
r
, hence we will get the last
digit of the number as output. So we should declare
r as
static.

Progra
m:
fibo_rfn
.c

Togeneratefibonacciseriesusingrecursivefunction

#include<stdio.h>
#include<conio.h>
voidmain()
{
voidfibo(int)
intn
printf("Enteranumber:")
scanf("%d",&n)

fibo(n)
getch()
}
voidfibo(intx)
{
staticinta=1,b=0,c=0
if(x>=1)
{
printf("\t%d",c)
c=a+b
a=b
b=c
fibo(x1)
}
}
Program:
mn_mn
.c

To display natural numbers using


function(mainwithinanothermain)

#include<stdio.h>
#include<conio.h>
voidmain()
{
staticinti=1,n
if(i==1)
{

recursive

printf("Enteranumber:")
scanf("%d",&n)
}
printf("%d\t",i)
i++
if(i<=n)
main()
getch()
exit(0)
}

Note:

Here we are using main() within main(), and main()


returns void data type, we have to press the enter key
n
times(if n=5, 5 times) to come out from the program, to
avoid this we will use exit(0). Check this without giving
exit(0).

Math.hFunctions:

sqrt:

Calculatesthesquarerootofagivennumber.

Syntax:
doublesqrt(doublex)

Program:
sqrt
.c

Tofindsquarerootofgivennumber

#include<stdio.h>
#include<conio.h>
#include<math.h>
voidmain()
{
intn
doubles
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
s=sqrt(n)
printf("Squarerootof%d=%.3lf",n,s)
getch()
}

Pow
:
Calculates exponential value of given base and
power

Syntax:
doublepow(doublex,doubley)
Herexisbaseandyispower.

Program:
power
.c

Tofindexponentialvalueofgivenbaseandpower

#include<stdio.h>
#include<conio.h>
#include<math.h>
voidmain()
{
intb,p
doublee
printf("Enterbaseandpowervalues:")
scanf("%d%d",&b,&p)
e=pow(b,p)
printf("Exponentialvalue=%.3lf",e)
getch()
}
floor:
Itroundsdownthegivenvalue

Syntax:
doublefloor(doublex)

ceil:
Itroundsupthegivenvalue.

Syntax:
doubleceil(doublex)

Program:
flor_ceil
.c

Tofindfloorandceilvaluesofagivennumber

#include<stdio.h>
#include<conio.h>
#include<math.h>
voidmain()
{
doublen,f,c
clrscr()
printf("Enteranumber:")
scanf("%lf",&n)
f=floor(n)
c=ceil(n)
printf("FloorValue=%.2lf",f)
printf("\nCeilValue=%.2lf",c)
getch()
}

abs :
It is a macro that gets the absolute value of an

integer

Syntax:
intabs(intx)

Program:
abs
.c

Todisplayabsolutevalueofgivennumber

#include<stdio.h>
#include<conio.h>
voidmain()
{
intn,a
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
a=abs(n)
printf("Givenvalue:%d",n)
printf("\nAbsolutevalue:%d",a)
getch()
}

Program:
triangle
.c

Tofindareaofgiventrianglewith3sides

#include<stdio.h>
#include<conio.h>
#include<math.h>
voidmain()
{
floata,b,c,s,area
printf("Entersidesofatriangle:")
scanf("%f%f%f",&a,&b,&c)
if(a+b<=c||a+c<=b||b+c<=a)
{
printf("unabletoformatriangle")
getch()
exit(0)
}
s=(a+b+c)/2
area=sqrt(s*(sa)*(sb)*(sc))
printf("Areaoftriangle=%.2fsqunits",area)
getch()
}

Program:
compound
.c

To enter principal amount, rate of interest and time,


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

voidmain()
{
inty,m,n
floatp,r,i,tot
clrscr()
printf("EnterPrincipalAmount:")
scanf("%f",&p)
printf("EnterRateofInterest:")
scanf("%f",&r)
printf("Entertime(yearsandmonths):")
scanf("%d%d",&y,&m)
n=y*12+m
tot=p*pow(1+(r/100),n)
i=totp
printf("Interest:%.2f",i)
printf("\nTotalAmount:%.2f",tot)
getch()
}

Program:
sim
_ser.c

Evaluatethefollowingsimpleseries
1+1/2+1/3+1/4+.............

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

{
inti,n
floatsum=0
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
for(i=1i<=ni++)
{
sum=sum+(float)1/i
}
printf("Sum=%.2f",sum)
getch()
}

Program:
exp
_ser.c

Evaluatethefollowingexponentialseries
1 + x + (x power 2 )/fact(2) + (x power 3)/fact(3) +
...............+
(xpowern)/fact(n)

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

inti,x,n
floatsum=0
clrscr()
printf("Enteravalueofxandn:")
scanf("%d%d",&x,&n)
for(i=1i<=ni++)
{
sum=sum+pow(x,i)/fact(i)
}
printf("Sum=%.2f",sum)
getch()
}
unsignedlongfact(intx)
{
if(x<=1)
return1
else
returnx*fact(x1)
}

Program:
sin
_ser.c

Evaluatethefollowingsinxseries
x(xpower3)/fact(3)+(xpower5)/fact(5)(xpower
7)/fact(7)+......
#include<stdio.h>
#include<conio.h>

#include<math.h>
voidmain()
{
unsignedlongfact(int)
inti,n,x,p=1
floatsum=0
clrscr()
printf("Entervalueofxandn:")
scanf("%d%d",&x,&n)
for(i=1i<=ni++)
{
if(i%2==0)
sum=sumpow(x,p)/fact(p)
else
sum=sum+pow(x,p)/fact(p)
p=p+2
}
printf("Sum=%.2f",sum)
getch()
}
unsignedlongfact(intx)
{
if(x<=1)
return1
else
returnx*fact(x1)
}


Program:
cos
_ser.c

Evaluatethefollowingcosxseries
1(xpower2)/fact(2)+(xpower4)/fact(4)(xpower
6)/fact(6)+......

#include<stdio.h>
#include<conio.h>
#include<math.h>
voidmain()
{
unsignedlongfact(int)
inti,n,x,p=0
floatsum=0
clrscr()
printf("Entervalueofxandn:")
scanf("%d%d",&x,&n)
for(i=1i<=ni++)
{
if(i%2==0)
sum=sumpow(x,p)/fact(p)
else
sum=sum+pow(x,p)/fact(p)
p=p+2
}
printf("Sum=%.2f",sum)

getch()
}
unsignedlongfact(intx)
{
if(x<=1)
return1
else
returnx*fact(x1)
}

inta,b,c,d,e,f

Arrays

Array is a collection of data items ( variables) of


same datatype, stored in a continuous memory locations
anditcanbereferredas
a common name. A particular value in the array is
indicated by using a number called index or subscript in
squarebracesafterthearrayname.

Typesofarrays:
Csupportsthreetypesofarrays,theyare

One/singledimensionalarrays
1) Two/doubledimensionalarrays
1) Multidimensionalarrays

One/singledimensionalarray:

Agroupofdataitemscanbegivenonevariablename,
using only one index, such a variable is called as single
dimensional array. In single dimensional array the
elements are represented one after the other in edges of
memorybytes.

Declaration:

datatypearr_name[size]

Eg:
inta[5]

Elementsare:

a[0],a[1],a[2],a[3],a[4]
Note:

Inanyarray,thearrayindexisfrom0tosize1

Initialization:

1)

optional
datatypearr_name[size]={val1,val2,..valn}

Eg:
inta[5]={1,2,3,4,5}
(Or)
inta[]={1,2,3,4,5,6,7}

Program:
arr1.c

Toinitialize1Darrayandtodisplayelements

#include<stdio.h>
#include<conio.h>
voidmain()
{
inti,a[5]={1,2,3,4,5}
clrscr()
for(i=0i<5i++)
{
printf("\na[%d]=%d",i,a[i])
}
getch()
}

Program:
arr2.c

Toacceptarrayelementsandtodisplaytheelements

#include<stdio.h>
#include<conio.h>
voidmain()
{
inti,n,a[20]
clrscr()
printf("Enternumberofelements:")
scanf("%d",&n)
if(n>20)
{
printf("Invalidsize")
getch()
exit(0)
}
printf("\nEnterElements:")
for(i=0i<ni++)
{
scanf("%d",&a[i])
}
printf("\nGivenElements:")
for(i=0i<ni++)
{
printf("\na[%d]=%d",i,a[i])
}
getch()
}

Program:
arr3.c

To accept 1D array and to display maximum and


minimumelements

#include<stdio.h>
#include<conio.h>
voidmain()
{
inti,n,a[20],max,min
clrscr()
printf("EnternumberofElements:")
scanf("%d",&n)
printf("\nEnterElements:")
for(i=0i<ni++)
{
scanf("%d",&a[i])
}
max=min=a[0]
for(i=1i<ni++)
{
if(a[i]>max)
max=a[i]
if(a[i]<min)
min=a[i]
}
printf("\nMaximumElement:%d",max)

printf("\nMinimumElement:%d",min)
getch()
}

Program:
arr4.c

To accept 1D array and to search specified element in


thegivenarray

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta[20],n,i,se,ck=0
clrscr()
printf("EnternumberofElements:")
scanf("%d",&n)
printf("\nEnterElements\n\n")
for(i=0i<ni++)
{
printf("Enterelementina[%d]:",i)
scanf("%d",&a[i])
}
printf("\n\nEnterElementtoSearch:")
scanf("%d",&se)
for(i=0i<ni++)
{

if(a[i]==se)
{
ck=1
printf("\n%disfoundata[%d]",se,i)
}
}
if(ck==0)
printf("%disnotfound",se)
getch()
}

Program:
arr5.c

To accept 1D array and to sort the given elements in


ascendingorder/

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta[20],n,i,j,t
clrscr()
printf("EnternumberofElements:")
scanf("%d",&n)
printf("\nEnterElements:\n")
for(i=0i<ni++)
{

scanf("%d",&a[i])
}
printf("\n\nElementsBeforeSorting:")
for(i=0i<ni++)
{
printf("\na[%d]=%d",i,a[i])
}
//sorting//
for(i=0i<ni++)
{
for(j=i+1j<nj++)
{
if(a[i]>a[j])
{
t=a[i]
a[i]=a[j]
a[j]=t
}
}
}
printf("\n\nElementsAfterSorting:")
for(i=0i<ni++)
{
printf("\na[%d]=%d",i,a[i])
}
getch()
}

Program:
arr6.c

Toacceptanddisplay1Darrayusingfunctions

#include<stdio.h>
#include<conio.h>
voidmain()
{
voidaccept(int[],int)
voiddisp(int[],int)
inta[20],n
clrscr()
printf("Enternumberofelements:")
scanf("%d",&n)
printf("EnterElements:")
accept(a,n)
printf("GivenElements:")
disp(a,n)
getch()
}
voidaccept(intx[],ints)
{
inti
for(i=0i<si++)
{
scanf("%d",&x[i])
}

}
voiddisp(intx[],ints)
{
inti
for(i=0i<si++)
{
printf("\t%d",x[i])
}
}

Program:
arr7.c

To accept 1D array and display elements in ascending


orderusingfunctions

#include<stdio.h>
#include<conio.h>
voidmain()
{
voidaccept(int[],int)
voiddisp(int[],int)
voidsort(int[],int)
inta[20],n
printf("Enternumberofelements:")

scanf("%d",&n)
printf("Enterelements:")
accept(a,n)
printf("\nElementsBeforeSorting:")
disp(a,n)
sort(a,n)
printf("\nElementsAfterSorting:")
disp(a,n)
getch()
}

voidaccept(inta[],intn)
{
inti
for(i=0i<ni++)
{
scanf("%d",&a[i])
}
}
voiddisp(inta[],intn)
{
inti
for(i=0i<ni++)
{
printf("\t%d",a[i])
}
}

voidsort(inta[],intn)
{
inti,j,t
for(i=0i<n1i++)
{
for(j=i+1j<nj++)
{
if(a[i]>a[j])
{
t=a[i]
a[i]=a[j]
a[j]=t
}
}
}
}

Program:
arr8.c

To accept 1D array and search specified element using


functions

#include<stdio.h>
#include<conio.h>
voidmain()
{
voidaccept(int[],int)

voiddisp(int[],int)
intsearch(int[],int,int)
inta[20],n,se,p
printf("Enternumberofelements:")
scanf("%d",&n)
printf("Enterelements:")
accept(a,n)
printf("\nGivenElements:")
disp(a,n)
printf("\nEnterelementtosearch:")
scanf("%d",&se)
p=search(a,n,se)
if(p==1)
printf("%disnotfound",se)
else
printf("%disfoundatposition%d",se,p)
getch()
}
voidaccept(inta[],intn)
{
inti
for(i=0i<ni++)
{
scanf("%d",&a[i])
}
}
voiddisp(inta[],intn)

{
inti
for(i=0i<ni++)
{
printf("\t%d",a[i])
}
}
intsearch(inta[],intn,intse)
{
inti
for(i=0i<ni++)
{
if(a[i]==se)
returni
}
return1
}

Twodimensionalarrays:
A
Twodimensionalarraycanstoreatableofvalues
which contains rows and columns. In this array we use 2
indexvalues.Thefirstindexisforrowsandsecondisfor
columns.

Thegeneralformof
Twodimensional
arrayis:


datatypearr_name[rowsize][columnsize]

Eg:
inta[3][3]

Elementsare:
a[0][0]a[0][1]a[0][2]
a[1][0]a[1][1]a[1][2]
a[2][0]a[2][1]a[2][2]

Initialization:

Form:1

optional

datatype
{val_1,val_2,,val_n}

arr_name[row size][column size] =

Eg:

1) inta[2][2]={1,2,3,4}
1) inta[2][2]={1,2,3,4,5}notpossible

1) inta[][2]={1,2,3,4,5}ispossible
Here the rows are allocated according to the given
elements and it will assign zeros for remaining
values.

12
34
50

Form:2
optional
data type
arr_name[row size][column size]= {
{val_1,val_2,,val_n},

{val_1,val_2,,val_n},
......................

{val_1,val_2,,val_n}}

Eg:

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

123
456
789

5)inta[3][3]={{1},{4,6},{8,9}}

100
460

890

If the values are missing it will assign zeros in that


elementplace.

Program:
arr11.c

Toinitialize2Darrayanddisplayelements

#include<stdio.h>
#include<conio.h>
voidmain()
{
//inta[3][3]={1,2,3,4,5,6,7,8,9}(or)
inta[3][3]={{1,2,3},
{4,5,6},
{7,8,9}}
inti,j
clrscr()
for(i=0i<3i++)
{
for(j=0j<3j++)
{

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

Program:
arr12.c

Toaccept2Darrayanddisplayelements

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta[10][10],r,c,i,j
clrscr()
printf("Enternumberofrowsandcolumns:")
scanf("%d%d",&r,&c)
if(r>10||c>10)
{
printf("InvalidSize")
getch()
exit(0)
}
printf("\nEnterElements:")
for(i=0i<ri++)
{

for(j=0j<cj++)
{
scanf("%d",&a[i][j])
}
}
printf("\nGivenElements:\n")
for(i=0i<ri++)
{
for(j=0j<cj++)
{
printf("%3d",a[i][j])
}
printf("\n")
}
getch()
}

Program:
arr13.c

To accept 2 dimensional array and display elements


usingfunctions

#include<stdio.h>
#include<conio.h>
voidmain()
{
voidaccept(int[][10],int,int)

voiddisp(int[][10],int,int)
inta[10][10],r,c
clrscr()
printf("Enternumberofrowsandcolumns:")
scanf("%d%d",&r,&c)
printf("\nEnterElements:")
accept(a,r,c)
printf("\nGivenElements:")
disp(a,r,c)
getch()
}
voidaccept(inta[][10],intr,intc)
{
inti,j
for(i=0i<ri++)
{
for(j=0j<cj++)
{
scanf("%d",&a[i][j])
}
}
}
voiddisp(inta[][10],intr,intc)
{
inti,j
for(i=0i<ri++)
{

for(j=0j<cj++)
{
printf("%3d",a[i][j])
}
printf("\n")
}
}

Program:
arr14.c

AdditionoftwoMatricesusingarraysandfunctions

#include<stdio.h>
#include<conio.h>
voidmain()
{
voidaccept(int[][10],int,int)
voiddisp(int[][10],int,int)
voidaddt(int[][10],int[][10],int[][10],int,int)
inta[10][10],b[10][10],add[10][10],r,c
clrscr()
printf("Enternumberofrowsandcolumns:")
scanf("%d%d",&r,&c)
printf("\nEnterFirstMatrixElements:")
accept(a,r,c)
printf("\nEnterSecondMatrixElements:")
accept(b,r,c)

printf("\nElementsofGivenFirstMatrix:\n")
disp(a,r,c)
printf("\nElementsofGivenSecondMatrix:\n")
disp(b,r,c)
addt(a,b,add,r,c)
printf("\nAdditionofgiven2Matrices:\n")
disp(add,r,c)
getch()
}
voidaccept(inta[][10],intr,intc)
{
inti,j
for(i=0i<ri++)
{
for(j=0j<cj++)
{
scanf("%d",&a[i][j])
}
}
}
voiddisp(inta[][10],intr,intc)
{
inti,j
for(i=0i<ri++)
{
for(j=0j<cj++)
{

printf("%3d",a[i][j])
}
printf("\n")
}
}
voidaddt(inta[][10],intb[][10],intadd[][10],intr,intc)
{
inti,j
for(i=0i<ri++)
{
for(j=0j<cj++)
{
add[i][j]=a[i][j]+b[i][j]
}
}
}

pogram:
arr15.c

Multiplicaton of two Matrices using arrays and


functions

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

{
voidaccept(int[][10],int,int)
voiddisp(int[][10],int,int)
voidmul(int[][10],int[][10],int[][10],int,int,int)
inta[10][10],b[10][10],c[10][10],m,n,p,q
clrscr()
printf("Enter number of rows and columns of First
Matrix:")
scanf("%d%d",&m,&n)
printf("Enter number of rows and columns of Second
Matrix:")
scanf("%d%d",&p,&q)
if(n!=p)
{
printf("\nMatrixMultiplicationisnotPossible")
getch()
exit(0)
}
printf("\nEnterFirstMatrixElements:")
accept(a,m,n)
printf("\nEnterSecondMatrixElements:")
accept(b,p,q)
printf("\nElementsofGivenFirstMatrix:\n")
disp(a,m,n)
printf("\nElementsofGivenSecondMatrix:\n")
disp(b,p,q)
mul(a,b,c,m,n,q)

printf("\nMultiplicationofgivenMatrices:\n")
disp(c,m,q)
getch()
}
voidaccept(inta[][10],intr,intc)
{
inti,j
for(i=0i<ri++)
{
for(j=0j<cj++)
{
scanf("%d",&a[i][j])
}
}
}
voiddisp(inta[][10],intr,intc)
{
inti,j
for(i=0i<ri++)
{
for(j=0j<cj++)
{
printf("%3d",a[i][j])
}
printf("\n")
}
}

void mul(int a[][10],int b[][10],int c[][10],int m,int n,int


q)
{
inti,j,k
for(i=0i<mi++)
{

for(j=0j<qj++)
{

c[i][j]=0
for(k=0k<nk++)
{

c[i][j]=c[i][j]+(a[i][k]*b[k][j])
}
}
}
}

Program:
arr16.c

To check whether the given matrix is identity matrix or


not

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

voidaccept(int[][10],int,int)
voiddisp(int[][10],int,int)
intcheckmat(int[][10],int,int)
inta[10][10],r,c,k
printf("Enternumberofrowsandcolumns:")
scanf("%d%d",&r,&c)
printf("\nEnterElements:")
accept(a,r,c)
printf("\nGivenElements:")
disp(a,r,c)
k=checkmat(a,r,c)
if(k==1)
printf("GivenMatrixisIndentityMatrix")
else
printf("GivenMatrixisnotIndentityMatrix")
getch()
}
voidaccept(inta[][10],intr,intc)
{
inti,j
for(i=0i<ri++)
{
for(j=0j<cj++)
{
scanf("%d",&a[i][j])
}
}

}
voiddisp(inta[][10],intr,intc)
{
inti,j
for(i=0i<ri++)
{
for(j=0j<cj++)
{
printf("%3d",a[i][j])
}
printf("\n")
}
}
intcheckmat(inta[][10],intr,intc)
{
inti,j
for(i=0i<ri++)
{
for(j=0j<cj++)
{
if(i==j)
{
if(a[i][j]!=1)
return0
}
else
{

if(a[i][j]!=0)
return0
}
}
}
return1
}

Program:
arr17.c

TofindTransposeofthegivenmatrix

#include<stdio.h>
#include<conio.h>
voidmain()
{
voidaccept(int[][10],int,int)
voiddisp(int[][10],int,int)
voidtrans(int[][10],int[][10],int,int)
inta[10][10],at[10][10],r,c
clrscr()
printf("Enternumberofrowsandcolumns:")
scanf("%d%d",&r,&c)
printf("\nEnterElements:")
accept(a,r,c)
printf("\nGivenElements:\n")
disp(a,r,c)

trans(a,at,r,c)
printf("TransposeMatrix:\n")
disp(at,c,r)
getch()
}
voidaccept(inta[][10],intr,intc)
{
inti,j
for(i=0i<ri++)
{
for(j=0j<cj++)
{
scanf("%d",&a[i][j])
}
}
}
voiddisp(inta[][10],intr,intc)
{
inti,j
for(i=0i<ri++)
{
for(j=0j<cj++)
{
printf("%3d",a[i][j])
}
printf("\n")
}

}
voidtrans(inta[][10],intat[][10],intr,intc)
{
inti,j
/*for(i=0i<ri++)
{
for(j=0j<cj++)
{
at[j][i]=a[i][j]
}
}
*/
for(i=0i<ci++)
{
for(j=0j<rj++)
{
at[i][j]=a[j][i]
}
}
}

Multidimensionalarray:

C supports arrays of 3 or more dimensions. In Multi


dimensionalarrayweusemorethan2indexvalues

Syntax:

Datatypearr_name[s1][s2][sn]

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]

Program:
arr18.c

Todisplaymultidimensionalarray

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta[2][2][3],i,j,k
for(i=0i<2i++)
{
for(j=0j<2j++)

{
for(k=0k<3k++)
{
printf("EnterValueintoa[%d][%d][%d]:",i,j,k)
scanf("%d",&a[i][j][k])
}
}
}
for(i=0i<2i++)
{
for(j=0j<2j++)
{
for(k=0k<3k++)
{

printf("\nGiven Value in a[%d][%d][%d] =


%d",i,j,k,a[i][j][k])
}
}
}
getch()
}

Strings

A group of characters defined between double


quotationmarks isastring.Itisaconstantstring,Butin
C language, a string variable is nothing but an array of
charactersandterminatedbyanullcharacter(\0).
Declaration:

charidentifier[size]

Eg:
charst[20]

Initialization:

Atthetimeofdeclaringastringvariablewecanstorea
constantstringintothevariableiscalledasinitialization
ofastring.

optional

Syntax:
charidentifier[size]=string

Eg:
charst[10]=WELCOME

charstr[]=ABCD

Note:

1. The compiler assigns a constant string to a string


variable, it automatically supplies a null character at
theendofastring.Thereforethesizeshouldbeequal
tonumberofcharactersinthestringplus1.
1. In C language, string initialization is possible, but
stringassigningisnotpossible.

Program:
str1.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
chars1[10]="welcome"
chars2[]="goodmorning"
clrscr()
printf("string1=%s",s1)
printf("\nstring2=%s",s2)
getch()
}


gets:

Itgetsastringfromstdin.

Syntax:

char*gets(char*s)

Eg:

1)gets(st)
2)gets(welcome)

notpossible

puts:

It outputs a string to stdout and appends a new line
character.

Syntax:

char*puts(constchar*s)

Eg:

1)puts(st)
2)puts(welcome)

possible

Program:
str2.c

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

voidmain()
{
charst[20]
clrscr()
puts("EnteraString:")
gets(st)
puts("GivenString:")
puts(st)
getch()
}

getch:

It gets a character from the console but doesnot echo to


thescreen.

Syntax:

intgetch()

getche:

It gets a character from the console and echoes to the


screen.

Syntax:

intgetche()

Program:
str3.c

#include<stdio.h>

#include<conio.h>
voidmain()
{
charch
charche
clrscr()
printf("Enterfirstcharacter:")
ch=getch()
printf("Entersecondcharacter:")
che=getche()
printf("Firstcharacter:%c"ch)
printf("Secondcharacter:%c"che)
getch()
}

Note:

No need to press enter key after entering a character


because this function itself supplies a new line character
attheendofthecharacter.

getchar:

Itisamacrothatgetsacharacterfromstdin.

Syntax:

intgetchar()

putchar:

Itisamacrothatoutputsacharacteronstdout.

Syntax:

intputchar(intc)

Program:
str4.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
charch
clrscr()
printf("Enteracharacter:")
ch=getchar()
printf("Givencharacter:")
putchar(ch)
getch()
}

Stringhandlingfunctions:

Theseareincludedintheheaderfile
<string.h>

strlen:
Itcalculateslengthofgivenstring.

Syntax:
size_tstrlen(constchar*s)

Program:
str5.c

#include<stdio.h>
#include<conio.h>
#include<string.h>
voidmain()
{
intlen
chars[20]
clrscr()
printf("Enterastring:")
gets(s)
len=strlen(s)
printf("Lengthofgivenstring:%d",len)
getch()
}

strcpy:
Itcopiesonestringtoanotherstring.

Syntax:
char*strcpy(char*dest,constchar*src)

Program:
str6.c


#include<stdio.h>
#include<conio.h>
#include<string.h>
voidmain()
{
intlen
chars1[20],s2[20]
clrscr()
printf("Enterastring:")
gets(s1)
strcpy(s2,s1)
printf("\nGivenstring:%s",s1)
printf("\nCopiedString:%s",s2)
getch()
}

strrev
:

It reverses all characters in the given string except for


theterminatingnull.

Syntax:
char*strrev(char*s)

Program:
str7.c

#include<stdio.h>
#include<conio.h>
#include<string.h>
voidmain()
{
chars[80]
clrscr()
printf("Enterastring:")
gets(s)
printf("Givenstring:%s",s)
strrev(s)
printf("\nReversestring:%s",s)
getch()
}

strcat
:
Itappendsonestringtoanother.

Syntax:
char*strcat(char*dest,constchar*src)

Note:
strcatappendsacopyofsrctotheendofdest.Thelength
ofresultingstringis:
strlen(dest)+strlen(src)

Program:
str8.c

#include<stdio.h>
#include<conio.h>
#include<string.h>
voidmain()
{
chars1[80],s2[80]
clrscr()
printf("Enterfirststring:")
gets(s1)
printf("Entersecondstring:")
gets(s2)
strcat(s1,s2)
printf("\nConcatenationof2strings:%s",s1)
getch()
}

strupr
:
It converts lower case letters inthegivenstringtoupper
case.

Syntax:
char*strupr(char*s)

strlwr
:

It converts upper case letters in the given string to


lowercase.

Syntax
:char*strlwr(char*s)

Program:
str9.c

#include<stdio.h>
#include<conio.h>
#include<string.h>
voidmain()
{
chars[80]
clrscr()
printf("Enterastring:")
gets(s)
printf("Givenstring:%s",s)
strlwr(s)
printf("\nGivenstringinlowercase:%s",s)
strupr(s)
printf("\nGivenstringinuppercase:%s",s)
getch()
}

strcmp
:Itcompares2stringwithcasesensitivity.

Syntax:
intsrtcmp(constchar*s1,constchar*s2)

stricmp
:Itcompares2stringwithoutcasesensitivity.


Syntax
:intsrticmp(constchar*s1,constchar*s2)

strcmpi : It is a macro which compares 2stringwithout


casesensitivity.

Syntax
:intsrtcmpi(constchar*s1,constchar*s2)

Returnvalue:

Theseroutinesreturnsanintvalue
<0

s1<s2
=0

s1=s2
>0

s1>s2

Program:
str10.c

#include<stdio.h>
#include<conio.h>
#include<string.h>
voidmain()
{
chars1[80],s2[80]
intn
clrscr()
printf("Enterfirststring:")
gets(s1)

printf("Entersecondstring:")
gets(s2)
//n=strcmp(s1,s2)
n=stricmp(s1,s2)
//n=strcmpi(s1,s2)
if(n==0)
printf("\n2stringsareequal")
if(n<0)
printf("\nFirststringislessthanSecondstring")
if(n>0)
printf("\nFirststringisgreaterthanSecondstring")
getch()
}

Program:
str11.c
TocheckweatherthegivenstringisPlindromeorNot

#include<stdio.h>
#include<conio.h>
#include<string.h>
voidmain()
{
chars1[80],s2[80]
intn
clrscr()
printf("Enterastring:")
gets(s1)

strcpy(s2,s1)
strrev(s2)
n=strcmp(s1,s2)
if(n==0)
printf("\nGivenstringisaPalindrome")
else
printf("\nGivenstringisnotaPalindrome")
getch()
}

Program:
str12.c

TofindcharacterfrequencyofgivenString

#include<stdio.h>
#include<conio.h>
voidmain()
{
staticinta[256],i
charst[80]
clrscr()
printf("EnteraString:")
gets(st)
for(i=0i<strlen(st)i++)
{
a[st[i]]=a[st[i]]+1
}

printf("\nCharacterFrequency")
printf("\n\n")
for(i=0i<256i++)
{
if(a[i]!=0)
printf("\n%c%d",i,a[i])
}
getch()
}

Program:
str13.c

Toenteranypasswordanddisplaythepasswordstring

#include<stdio.h>
#include<conio.h>
voidmain()
{
charst[20],ch
inti=0
clrscr()
gotoxy(20,15)
printf("EnterPassword:")
while(1)
{
ch=getch()

if(ch==13)
break
if(ch==8)
{
if(i>0)
{
printf("\b%c\b",32)
i
}
}
else
{
st[i]=ch
i++
printf("*")
}
}
st[i]='\0'
gotoxy(20,30)
printf("GivenString:%s",st)
getch()
}

Program:
str14.c

To enter any String and drop characters from top to


bottom

#include<stdio.h>
#include<conio.h>
voidmain()
{
charst[40]
inti,j,c
clrscr()
printf("EnteraString:")
gets(st)
_setcursortype(_NOCURSOR)
while(1)
{
c=(80strlen(st))/2
clrscr()
gotoxy(c,1)
printf("%s",st)
for(i=0i<strlen(st)i++)
{
if(st[i]!=0)
{

for(j=2j<=25j++)
{
if(kbhit())
exit(0)
gotoxy(c,j)
printf("%c",st[i])
gotoxy(c,j1)
printf("%c",32)
delay(20)
}
}
c++
}
}
}

Program:
str15.c

To enter any String and drop characters from top to


bottomandagainbottomtotop

#include<stdio.h>
#include<conio.h>
voidmain()
{
charst[40]
intc,i,j

clrscr()
printf("Enterastring:")
gets(st)
_setcursortype(_NOCURSOR)
while(!kbhit())//while(1)
{
c=(80strlen(st))/2
clrscr()
gotoxy(c,1)
printf("%s",st)
for(i=0i<strlen(st)i++)
{
if(st[i]!=32)
{
for(j=2j<=25j++)
{
//if(kbhit())
//exit(0)
gotoxy(c,j)
printf("%c",st[i])
gotoxy(c,j1)
printf("%c",32)
delay(20)
}
}
c++
}

for(i=strlen(st)1i>=0i)
{
c
if(st[i]!=32)
{
for(j=24j>=1j)
{
//if(kbhit())
//exit(0)
gotoxy(c,j)
printf("%c",st[i])
gotoxy(c,j+1)
printf("%c",32)
delay(20)
}
}
}
}
}

Program:
str16.c

Scrollingthegivenstringonscreencenter

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

{
charst[40],ch
intc,i
clrscr()
printf("Enterastring:")
gets(st)
strcat(st,"")
strupr(st)
clrscr()
textmode(1)
_setcursortype(_NOCURSOR)
textbackground(WHITE)
textcolor(RED)
c=(40strlen(st))/2
gotoxy(c,12)
cprintf("%s",st)
while(!kbhit())
{
ch=st[0]
for(i=0i<strlen(st)i++)
{
st[i]=st[i+1]
}
st[i1]=ch
st[i]='\0'
gotoxy(c,12)
cprintf("%s",st)

delay(100)
}
getch()
}

Twodimensionalcharacterarrays(Stringarray):

Alistofstringscanbetreatedasatableofstringsanda
two dimensional character array can be used to store the
entirelist.
Forexample:
charst[20][20]maybeusedtostorealistof20strings,
eachoflengthnotmorethan20characters.

Program:
strarr1.c

Toentergroupofstringsandtodisplaythem

#include<stdio.h>
#include<conio.h>
voidmain()
{
charst[20][20]
intn,i

clrscr()
printf("Enternumberofstrings:")
scanf("%d",&n)
printf("Enter%dstrings:",n)
fflush(stdin)
for(i=0i<ni++)
{
gets(st[i])
}
printf("\nGivenstrings:")
for(i=0i<ni++)
{
puts(st[i])
}
getch()
}

Program:
strarr2.c

To enter group of strings and to display them in


alphabeticalorder

#include<stdio.h>
#include<conio.h>
voidmain()
{
charst[20][20],t[20]

intn,i,j,k
clrscr()
printf("Enternumberofstrings:")
scanf("%d",&n)
printf("Enter%dstrings:\n",n)
fflush(stdin)
for(i=0i<ni++)
{
gets(st[i])
}
printf("\nGivenstrings:\n")
for(i=0i<ni++)
{
puts(st[i])
}
//soring//
for(i=0i<n1i++)
{
for(j=i+1j<nj++)
{
k=strcmp(st[i],st[j])
if(k>0)
{
strcpy(t,st[i])
strcpy(st[i],st[j])
strcpy(st[j],t)
}

}
}
printf("\nGivenstringsinAlphabeticalorder:\n")
for(i=0i<ni++)
{
puts(st[i])
}
getch()
}

PreprocessorstatementsorPreprocessordirectives:

The processor is a program that process thesource


code before it passes through the compiler. The
commands used to control the processor are known as
preprocessordirectives.

Thesedirectivesaredividedinto3categories.

1. Fileinclusiondirectives
2. Macrosubstitutiondirectives

3. Compilercontroldirectives

Fileinclusiondirectives:

#include:

It is a pre processor file inclusion directive and is


usedtoincludeheaderfiles.Itprovidesinstructionstothe
compilertolinkthefunctionsfromthesystemlibrary.

Syntax:

#include"filename"
(or)
#include<filename>

Whenthefilenameisincludedwithin,the
search for the file is made first the current directory and
then the standard directories. Otherwise the file name is
includedwithin<>,thefileis
sarchedonlyinthestandarddirectories.

Macrosubstitutiondirectives:
Macro is a process where an identifier in a program is
replacedbyapredefinedstringorvalue.


#define:

It is a preprocessor statement and is used to define


macros.

Syntax:

Form1:(simplemacro)

#define
<identifier>
<predefined_string or
value>

eg:
#definepfprintf
#definesfscanf
#definePI3.14
#defineg9.8

Program:
sim_mac.c

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

#definepfprintf
#definesfscanf
#definevmvoidmain()
#defineclsclrscr
#definegtgetch
#defineval100
vm()
{
intn
cls()
pf("Enteranumber:")
sf("%d",&n)
pf("GivenNumber="%d",n)
p("\nval=%d",val)
gt()
}

Form2:(complexmacroormacrowitharguments)

Syntax:

#define
identifier(arg1,arg2,.argn)
definition

Eg:


#definesquare(x)x*x

Program:
comx_mac.c

#include<stdio.h>
#include<conio.h>
#definesquare(x)x*x
voidmain()
{
intn,s
clrscr()
printf("Enteranumber:")
scanf("%d",&n)
s=square(n)
printf("Squareofgivennumber=%d",s)
getch()
}

Differencebetweenfunctionandmacro:


Function

Macro

1)It is a self contained block of statements.


1)It is a
preprocessorstatement.

2)Itreplacesitsreturnvalue

2)It replaces its


definition.

3)Wecanuseonlyspecifieddatatypes.
3)Data types are
generic.

4)Executionspeedisless.

4)Execution speed
ismore

Program:
macr_def.c

#include<stdio.h>
#include<conio.h>
//#definesquare(x)x*x
//#definesquare(x)(x*x)

voidmain()
{
intn
n=100/square(5)

printf("n=%d",n)
getch()
}

Intheaboveexample,ifwegives

n=100/square(5), we should get 100(according to


macros). Because it is a precpcessor statement and it
replacesitsdefinition.i.e.accordingtomacrodefinition,
100/square(5)means100/5*5=20*5=100.
Accordingtofunctiondefinition,
100/square(5)means100/25=4
Hence the difference between macro and a function is in
macros, the method name is replaced with its definition.
i.e. square(a) is replaced with 5*5. whereas in functions,
the method is replaced with its value. i.e. square(5) is
replacedwiththevalue25.

Ifwewanttogettheresultof4,weshouldgive
n=100/(square(5))
or
in the macro definition we should give #define square(a)
(a*a)
then,res=100/(25)
=4

Program:
macr_max.c

#include<stdio.h>
#include<conio.h>
#definemaxval(a,b)a>b?a:b
voidmain()
{
inta,b,max
clrscr()
printf("Enteranytwovalues:")
scanf("%d%d",&a,&b)
max=maxval(a,b)
printf("Maximumvalue=%d",max)
getch()
}

Note:

The are predefined macros namely max and min, hence


donotusethesenamesfordefiningmacros.

Compilercontroldirectives:

Thesedirectivesareusedtocontrolthecompiler.The
followingcompilercontroldirectivesareusedinC.
1 #if
1 #else
1 #elif
1 #endifetc.


Program:
comp_dir.c

#include<stdio.h>
#include<conio.h>
#definen10
#ifn<=10
#defineval100
#else
#defineval200
#endif
voidmain()
{
clrscr()
printf("Val=%d",val)
getch()
}

Pointers

C provides the important feature of data


manipulationswiththeaddressofthevariables.Hencethe
execution time is very much reduced. Such concept is
possiblewiththespecialdatatypecalledpointers.


Definition:

A pointer is a variable which stores the address of


anothervariable.

Declaration:

Pointerdeclarationissimilartonormalvariablebut
preceded
by*symbol.

syntax:
datatype*identifier
eg:
int*p
char*ch1,*ch2
intx,y,*p,z

Initialization:

Atthetimeofdeclaringapointer,wecanstoresome
addressintothatpointercalledasinitializationofpointer.

Syntax:
datatype*identifier=address

Example:

inta
int*p=&a

AssigningAddresstoapointer:

datatype*identifier
identifier=Address

eg:
int*p
inta
p=&a

void*:

Itisagenericpointer,itreferstheaddressofanytypeof
variableandalsoitwillconverttoanytypeofpointer.

eg:
void*p

NULL:


Nullpointervalue(emptyaddress)

Note:

Anytypeofpointer,itallocatesonly2bytesofmemory
,Because it stores the address of memory location. In C
language the memory address is in unsigned integer. (2
bytesforunsignedint,intherangeof0to65535)

Program:
ptr1.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
int*p1
char*p2
float*p3
double*p4
clrscr()
printf("sizeofintpointer=%dbytes",sizeof(p1))
printf("\nsizeofcharpointer=%dbytes",sizeof(p2))
printf("\nsizeoffloatpointer=%dbytes",sizeof(p3))
printf("\nsizeofdoublepointer=%dbytes",sizeof(p4))
getch()

Accessingpointers:

inta=100inta=100
int*p=&a(or)int*p
p=&a

a100*p100
&a5000p5000
a=200*p=200

Program:
ptr2.c

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

inta=100
int*p=&n
clrscr()
printf("valueofa=%d",a)
printf("\naddressofa=%lu",&a)
printf("\nvalueofausingp=%d",*p)
printf("\naddressofausingp=%lu",p)
n=200
printf("\n*p=%d",*p)
*p=300
printf("\na=%d",a)
getch()
}

PointersandFunctions:

Calling mechanism of argument function or Parameter passing


techniques

1)
1)

CallbyvalueorPassbyvalue
CallbyreferenceorPassbyreference.

Callbyvalue:

The process of passing the value to the function call is


knownascallbyvalue.

Program:
fn1.c

Passingconstantvalue

#include<stdio.h>
#include<conio.h>
voidmain()
{
voidfun(int)
clrscr()
fun(100)
getch()
}
voidfun(intx)
{
printf("%d",x)
}

Program:
fn2.c

Passingavariable

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

{
voidfun(int)
intn
clrscr()
printf("Enteranyvalue:")
scanf("%d",&n)
fun(n)
getch()
}
voidfun(intx)
{
printf("Givenvalue=%d",x)
}

Program:
fn3.c

Passinganexpression

#include<stdio.h>
#include<conio.h>
voidmain()
{
voidfun(int)
inta,b
clrscr()
printf("Enteranytwonumbers:")
scanf("%d%d",&a,&b)

fun(a+b)
getch()
}
voidfun(intx)
{
printf("Sum=%d",x)
}

Callbyreference:

The process of calling a function using pointers to pass


theaddressofthevariablesiscalledascallbyreference.

Program:
ptrfn1.c

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

voidsetdata(int*)
intn
clrscr()
setdata(&n)
printf("n=%d",n)
getch()
}

voidsetdata(int*p)
{
*p=100
}

Program:
ptrfn2.c

Toacceptavalueanddisplayitusingcallbyreference

#include<stdio.h>
#include<conio.h>
voidmain()
{
voidaccept(int*)
intn
clrscr()
accept(&n)
printf("Givenvalue=%d",n)
getch()
}
voidaccept(int*p)
{
printf("Enteravalue:")
scanf("%d",p)
}

Program:
ptrfn3.c

Swapingof2valuesusingcallbyreference

#include<stdio.h>
#include<conio.h>
voidmain()
{
voidswap(int*,int*)
inta,b
clrscr()
printf("Enter2values:")
scanf("%d%d",&a,&b)
printf("\nGivenvaluesbeforeswaping:")
printf("\na=%d",a)
printf("\nb=%d",b)
printf("\n\nGivenvaluesafterswaping:")
swap(&a,&b)
printf("\na=%d",a)
printf("\nb=%d",b)
getch()
}
voidswap(int*x,int*y)
{
intt
t=*x
*x=*y

*y=t
}

PointersandArrays:

When an array is declared, the compiler allocates a


base address and sufficient amount of storage to contain
alltheelementsofarrayin
continuous memory locations. The base address is the
locationofthefirstelement(index =0)ofthearray.The
compileralsodefinesthearraynameasaconstantpointer
tothefirstelement.

Program:
ptrarr1.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta[5]
clrscr()
printf("Baseaddress:%u",&a[0])
printf("\nBaseaddress:%u",a)
getch()

Supposewedeclareanarray
a
asfollows:
inta[5]={1,2,3,4,5}
Suppose the base address of a=1000 and each integer
requires 2 bytes of memory,the 5 elements will be stored
asfollows:

The name 'a' is defined as aconstantpointerpointing


to the first element a[0] and therefore the value of a is
1000,thelocationwherea[0]isstored.
Hencea=&a[0]=1000

Ifwedeclare
pasanintegerpointer,thenwecanmake
the pointer p to point to the array
a by the following
assignment.
int*p
p=a(or)p=&a[0]

Now we can access every element of


a using p++ or
p+0, p+1, .. to move one element to another. The
relationshipbetween
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

When handling arrays instead of using array index we


can use pointers to access array elements. Note that
*(p+k)givesthevalueofa[k].

Togetthevaluesofarrayelements:

*(p+0)=a[0]=1
*(p+1)=a[1]=2
*(p+2)=a[2]=3
*(p+3)=a[3]=4
*(p+4)=a[4]=5


Note:

The pointer accessing method is much faster than array


indexing.

Program:
ptrarr2.c

To accept Single dimension array and display array


elementsusingpointeraccessingmethod

#include<stdio.h>
#include<conio.h>
voidmain()
{
inta[20],n,i,*p
p=a//p=&a[0]
clrscr()
printf("Enternumberofelements:")
scanf("%d",&n)
printf("Enterarrayelements:")
for(i=0i<ni++)
{
scanf("%d",(p+i))

//directlywecangive(a+i)withoutdeclaring*p,but
itisnotefficient
}

printf("\nGivenarrayelements:")
for(i=0i<ni++)
{
printf("%d\t",*(p+i))
//herealsowecangive*(a+i),insteadof*(p+i)
}
getch()
}

PointersandStrings

Apointercanalsopointtoastring.
Program:
ptrstr1.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
char*st
clrscr()
printf("EnteraString:")
gets(st)
printf("GivenString:%s",st)
getch()
}
We need not specify the size of String, the

compiler

automaticallyallocatessufficient
amountofmemory

StringcopyingusingPointers:

Program:
ptrstr2.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
char*st1,*st2
clrscr()
printf("EnteraString:")
gets(st1)
st2=st1
printf("GivenString:%s",st1)
printf("\nCopiedString:%s",st2)
getch()
}

DynamicMemoryAllocation(DMA):

Clanguagerequiresthenumberofelementsinanarray

tobespecifiedatcompiletime.Butwemaynotbeableto
do so always. Our initial judgementofsize,ifitiswrong
may cause failure of program or wastage of memory
space.AtthissituationwecanuseDMA.

Definition:

Theprocessofallocatingmemoryatruntimeisknownas
DynamicMemoryAllocation(DMA).

malloc:
<alloc.h>

Itisusedtoallocatememoryatruntime.

Syntax:
void*malloc(size_tsize)

size_t : It is the type used for memory object sizes and


repeatcounts,alsoitisanothernameforunsignedinteger.

void*malloc(size_tsize)

pointer=(typecast)maclloc(memorysize)

Eg:

int*p

p=(int*)malloc(sizeof(int))//1location

p=(int*)malloc(5*sizeof(int))//5locations

It allocates specified number of locations in the


heap(mainmemory)andinitializedtogarbagevalues.

calloc:
<alloc.h>

Itisusedtoallocatememoryatruntime.

Syntax:
void*calloc(size_tnitems,size_tsize)

pointer = (typecast) calloc


(number of locations, size of each
location)

Eg:

int*p
p=(int*)calloc(1,sizeof(int))//1location
p=(int*)calloc(5,sizeof(int))//5locations

It allocates specified number of locations in the


heap(mainmemory)andinitializedtozeroes.

free:
<alloc.h>


Itfreestheallocatedblocks.

Syntax:
voidfree(void*block)

Program:
dma1.c

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
voidmain()
{
int*p1,*p2,i
p1=(int*)malloc(5*sizeof(int))
p2=(int*)calloc(5,sizeof(int))
clrscr()
printf("MALLOC:")
for(i=0i<5i++)
{
printf("%d\t",*(p1+i))
}
printf("\nCALLOC:")
for(i=0i<5i++)
{
printf("%d\t",*(p2+i))
}

free(p1)
free(p2)
getch()
}

Program:
dma2.c

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
voidmain()
{
int*p,n,i
clrscr()
printf("Enternumberofelements:")
scanf("%d",&n)
p=(int*)malloc(n*sizeof(int))
//p=(int*)calloc(n,sizeof(int))
printf("Enterelements:")
for(i=0i<ni++)
{
scanf("%d",(p+i))
}
printf("\nGivenelements:")
for(i=0i<ni++)
{
printf("%d\t",*(p+i))

}
free(p)
getch()
}

realloc:

Itisincludedintheheaderfile<alloc.h>
Itreallocatesmainmemoryatruntime.

Syntax:
void*realloc(void*block,size_tsize)

reallocadjuststhesizeofallocatedblocktosize,
copyingthecontentstoanewlocation.

Program:
realloc1.c

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<string.h>
voidmain()
{
char*str
clrscr()
str=(char*)malloc(10)

strcpy(str,"Hellow")
printf("GivenString:%s",str)
str=(char*)realloc(str,25)
strcat(str,"WelcometoSEASAW")
printf("\nNewString:%s",str)
free(str)
getch()
}

Program:
realloc2.c

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
voidmain()
{
int*p,id=0,i,s
charch
clrscr()
s=sizeof(int)
p=(int*)malloc(s)
while(1)
{
printf("Enterelement:")
scanf("%d",(p+id))
id++
printf("Douwanttoaddanotherelement(y/n):")

fflush(stdin)
scanf("%c",&ch)
if(ch=='y'||ch=='Y')
{
s=s+sizeof(int)
p=(int*)realloc(p,s)
}
else
break
}
printf("\nGivenelements:")
for(i=0i<idi++)
{
printf("%d\t",*(p+i))
}
free(p)
getch()
}

Structures

Wehaveseenthatarrayscanbeusedtorepresenta
group of data items that belongs to same datatype.Ifwe
want to represent a collection of data items of different

data types using a single name, then we cannot use an


array. C supports a constructed data type known as
Structure, which isamethodforpackingdataofdifferent
datatypes.

A structure is a convenienttoolforhandlingagroup
oflogically relateddataitems.Structureshelptoorganize
complex data in a more meaningful way. It is apowerful
concept that we may often need to use in our program
design.

Definition:

A group of data items that belongs to different data


typesisknownasStructure.

struct :
It is a keyword and is used to declare a
Structure.

Declaration:
Form:1

Declarationofstructure:

structstruct_name
{
dataitem1;
dataitem2;


dataitemn;
};

Eg:
structemp
{
inteno
charename[20]
floatsal
}

Declarationofstructurevariable:

structstruct_nameidentifier
(or)
struct
dentifier1,identifier2,.......,identifiern

Eg:

structempe
(or)
structempe1,e2,e3

Form:2

struct_name


Declaration of structure and structure variable in a single
statement:

structstruct_name
{
dataitem1
dataitem2

dataitemn
}var_list

Eg:
structemp
{
inteno
charename[20]
floatsal
}e
(or)

structemp
{
inteno
charename[20]
floatsal

}e1,e2,e3

.(Accessoperator):

It is used to access the data items of a structure with


thehelpofstructurevariable.

Syntax:

struct_variable
.
dataitem
Eg:
e.eno
e.ename
e.sal

Initialization:

Form:1

structstruct_name
{
dataitem1
dataitem2

dataitemn

structstruct_nameidentifier={value1,value2,..,valuen}

Eg:

structemp
{
inteno
charename[20]
floatsal
}

structempe={100,HHHH,20000.00}

Form:2

structstruct_name
{
dataitem1
dataitem2

dataitemn
}identifier={value1,value2,valuen}

Eg:


structemp
{
inteno
charename[20]
floatsal
}e={100,HHHH,20000.00}

Program:
struct1.c

Toinitializeastructureanddisplayitsdata

#include<stdio.h>
#include<conio.h>
structemp
{
inteno
charename[20]
floatsal
}
//}e={1,"HHHH",90000.00}

voidmain()
{
structempe={1,"HHHH",90000}

clrscr()
printf("\nEmpnumber:%d",e.eno)
printf("\nEmpname:%s",e.ename)
printf("\nSalary:%.2f",e.sal)
getch()
}

Program:
struct2.c

Toacceptastructureanddisplaythedata

#include<stdio.h>
#include<conio.h>
structemp
{
inteno
charename[20]
floatsal
}
voidmain()
{
structempe
clrscr()
printf("Enterempnumber:")
scanf("%d",&e.eno)
printf("Enterempname:")
fflush(stdin)

gets(e.ename)
printf("Entersalary:")
scanf("%f",&e.sal)
printf("\n\nGivenEmploydata")
printf("\n")
printf("\nEmpnumber:%d",e.eno)
printf("\nEmpname:%s",e.ename)
printf("\nSalary:%.2f",e.sal)
getch()
}

Program:
struct3.c

To accept student details and to calculate and display


result

#include<stdio.h>
#include<conio.h>
#include<string.h>
structstudent
{
intsno,c,cpp,java,tot
floatavg
charsname[20],res[10],div[12]
}s
voidmain()
{

clrscr()
printf("EnterStudentnumber:")
scanf("%d",&s.sno)
printf("EnterStudentname:")
fflush(stdin)
gets(s.sname)
printf("EntermarksinC:")
scanf("%d",&s.c)
printf("EntermarksinCPP:")
scanf("%d",&s.cpp)
printf("EntermarksinJAVA:")
scanf("%d",&s.java)
s.tot=s.c+s.cpp+s.java
s.avg=(float)s.tot/3
if(s.c>=50&&s.cpp>=50&&s.java>=50)
{
strcpy(s.res,"PASS")
if(s.avg>=60)
strcpy(s.div,"FIRST")
else
strcpy(s.div,"SECOND")
}
else
{
strcpy(s.res,"FAIL")
strcpy(s.div,"NODIVISION")
}

clrscr()
printf("StudentDetails")
printf("\n")
printf("\nStudentnumber:%d",s.sno)
printf("\nStudentname:%s",s.sname)
printf("\nMarksinC:%d",s.c)
printf("\nMarksinCPP:%d",s.cpp)
printf("\nMarksinJAVA:%d",s.java)
printf("\nTotalMarks:%d",s.tot)
printf("\nAverageMarks:%.2f",s.avg)
printf("\nResult:%s",s.res)
printf("\nDivision:%s",s.div)
getch()
}

ArrayofStructures:

Likeanyotherdatatype,structurearrayscanbedefined,
sothateacharrayelementcanbeofstructuredatatype.

ForExample,
structstudents[100]

which defines an array called


s, that contains 100
elements, each element is defined to be of type
struct
student
.


Program:
struct_ar1.c

#include<stdio.h>
#include<conio.h>
structitem
{
intcode
charname[20]
floatcost
}
voidmain()
{
structitemit[100]
intn,i
float*f,f1
clrscr()
f=&f1
*f=f1
printf("Enternumerofrecords:")
scanf("%d",&n)
for(i=0i<ni++)
{
printf("\n\nEnterRecord:%d",i+1)
printf("\n\nEnterItemcode:")
scanf("%d",&it[i].code)
printf("EnterItemName:")

fflush(stdin)
gets(it[i].name)
printf("EnterItemcost:")
scanf("%f",&it[i].cost)
}
clrscr()
printf("%10s%15s%s","CODE","NAME","COST")
printf("\n")
for(i=0i<ni++)
{

printf("\n%10d%15s%.2f",it[i].code,it[i].name,it[i].cost)

}
getch()
}

The allocation of variables in heap contains 2 parts. One


isforintegraldatatypes(intandchar),andtheotherisfor
floattype.

Heap(mainmemory)

Butitisdifferentincasewhenwedeclareastructure.

Whenwedefineastructurewith3datatypes,oneisof
integer, other is of character and another is of float type,
the memory for all the 3 types are allocated in integral
part. When we compile this type of programs we did not
get any error but when we execute the program, the
program terminates abnormally. This is because the link
failswhenconnectingfloatingvaluestothestructure.

To solve this problem, we have to declare2float


values,oneisofpointertypeandtheotherisnormalfloat
value. The memory for float pointer is allocated in the
integral part (because pointer has 2 bytes of unsigned int
memory) and the memory for other float variable is
allocated in the float part. This normal variable points to
the float pointer (which resides in integral part), andthus
we will established a link between integral part and float
partofheap.Thustheprogramsexecutesnormally.

HeapforStructurevariables

Program:
struct_ar2.c

To accept student details and to calculate and display


resultusingarrays


#include<stdio.h>
#include<conio.h>
#include<string.h>
structstudent
{
intsno,c,cpp,java,tot
floatavg
charsname[20],res[10],div[12]
}
voidmain()
{
structstudents[100]
intid=0,i
clrscr()
while(1)
{
printf("\nEnterStudentnumber:")
scanf("%d",&s[id].sno)
printf("EnterStudentname:")
fflush(stdin)
gets(s[id].sname)
printf("EntermarksinC:")
scanf("%d",&s[id].c)
printf("EntermarksinCPP:")
scanf("%d",&s[id].cpp)
printf("EntermarksinJAVA:")

scanf("%d",&s[id].java)
s[id].tot=s[id].c+s[id].cpp+s[id].java
s[id].avg=(float)s[id].tot/3
if(s[id].c>=50&&s[id].cpp>=50&&s[id].java>=50)
{
strcpy(s[id].res,"PASS")
if(s[id].avg>=60)
strcpy(s[id].div,"FIRST")
else
strcpy(s[id].div,"SECOND")
}
else
{
strcpy(s[id].res,"FAIL")
strcpy(s[id].div,"NODIVISION")
}
id++
printf("\nDouwanttoaddanotherRecord(y/n):")
fflush(stdin)
scanf("%c",&ch)
if(ch=='n'||ch=='N')
break
}
for(i=0i<idi++)
{
clrscr()
printf("StudentDetails")

printf("\n")
printf("\nStudentnumber:%d",s[i].sno)
printf("\nStudentname:%s",s[i].sname)
printf("\nMarksinC:%d",s[i].c)
printf("\nMarksinCPP:%d",s[i].cpp)
printf("\nMarksinJAVA:%d",s[i].java)
printf("\nTotalMarks:%d",s[i].tot)
printf("\nAverageMarks:%.2f",s[i].avg)
printf("\nResult:%s",s[i].res)
printf("\nDivision:%s",s[i].div)
printf("\n\nPressanykeytocontinue........")
}
}

Passingstructureasfunctionargument:

Likeanyotherdatatypeastructuremayalsobeusedas
functionargument.

Returningstructure
:

A function can not only receive a structure as its


arguments,butalsocanreturnthem.


Program:
s_pasret.c

#include<stdio.h>
#include<conio.h>
structstudent
{
intsno
charsname[20],course[20]
floatfee
}

structstudentaccept()
{
structstudents
printf("EnterStudentNumber:")
scanf("%d",&s.sno)
printf("EnterStudentName:")
fflush(stdin)
gets(s.sname)
printf("EnterCourse:")
gets(s.course)
printf("EnterFee:")
scanf("%f",&s.fee)
returns
}

voiddisp(structstudents)
{
printf("\n\nSTUDENTDETAILS")
printf("\n\n")
printf("\nStudentNumber:%d",s.sno)
printf("\nStudentName:%s",s.sname)
printf("\nCourse:%s",s.course)
printf("\nFees:%.2f",s.fee)
}
voidmain()
{
structstudentst
clrscr()
st=accept()//returningstructure
disp(st)//passingstructure
getch()
}

PointersandStructures:

Apointercanalsopointtoastructure.

Forexample:

structstudent
{


intsno
charsname[20],course[20]
floatfee

s
tructstudents

s
tructstudent*p

Here p is defined to be a pointer, pointing to student


structure,wecanwrite
p=&s

After making such an assignment we can access every


dataitemofstudentstructurethrough
p.

(Arrow)

>isthecombinationoffollowedby>.

It is used to access the dataitemsofa structurewith


thehelpof
structurepointer.

syntax:

Struct_pointer>dataitem

Eg:
p

sno
p

sname
p

course
p

fee

Program:
stru_ptr.c

#include<stdio.h>
#include<conio.h>
structstudent
{
intsno
charsname[20],course[20]
floatfee
}
voidmain()
{
structstudents
structstudent*p
float*f,f1
f=&f1
*f=f1
p=&s
clrscr()

/*Indirectmethod
printf("EnterStudentNumber:")
scanf("%d",&(*p).sno)
printf("EnterStudentName:")
fflush(stdin)
gets((*p).sname)
printf("EnterCourse:")
gets((*p).course)
printf("EnterFee:")
scanf("%f",&(*p).fee)
printf("\n\nSTUDENTDETAILS")
printf("\n\n")
printf("\nStudentNumber:%d",(*p).sno)
printf("\nStudentName:%s",(*p).sname)
printf("\nCourse:%s",(*p).course)
printf("\nFees:%.2f",(*p).fee)*/

/*Directmethod
printf("EnterStudentNumber:")
scanf("%d",&p>sno)
printf("EnterStudentName:")
fflush(stdin)
gets(p>sname)
printf("EnterCourse:")
gets(p>course)
printf("EnterFee:")
scanf("%f",&p>fee)

printf("\n\nSTUDENTDETAILS")
printf("\n\n")
printf("\nStudentNumber:%d",p>sno)
printf("\nStudentName:%s",p>sname)
printf("\nCourse:%s",p>course)
printf("\nFees:%.2f",p>fee)*/
getch()
}

Predefinedstructures:

1.

structDate:

It used to get current system date. It is included in the


headerfile<DOS.H>

Syntax:

structdate
{
intda_year//currentyear
charda_day//dayofmonth
charda_mon//month(Jan=1)
}


getdate():

Itgetsthecurrentsystemdate.

Syntax:
voidgetdate(structdate*d)

Program:
sysdate.c

Togetcurrentsystemdate
#include<stdio.h>
#include<conio.h>
#include<dos.h>
voidmain()
{
structdated
clrscr()
getdate(&d)
printf("CurrentSystemDate:
%.2d%.2d%d",d.da_day,d.da_mon,d.da_year)
}

2.
structTime:

It used to get current system time. It is included in the


headerfile<DOS.H>

Syntax:

structtime
{
unsignedcharti_min//minutes
unsignedcharti_hour//hours
unsignedcharti_sec//seconds
}

gettime():

Itgetsthecurrentsystemtime.

Syntax:
voidgettime(structtime*t)

Program:
systime.c

Togetcurrentsystemtime

#include<stdio.h>
#include<conio.h>
#include<dos.h>
voidmain()
{
structtimet
gettime(&t)
printf("CurrentSystemTime:

%.2d:%.2d:%.2d",t.ti_hour,t.ti_min,t.ti_sec)
}

structffblk:

Using this structure we can getinformationofafileora


directory.
Itisincludedintheheaderfile<dir.h>

Syntax:

structffblk
{
charff_reserved[21]//reservedbyDOS
charff_attrib//attributefound
charff_ftime//filetime
charff_fdate//filedate

charff_fsize//filesize
charff_name//foundfilename
}

findfirst():

Itsearchesadiskdirectoryforfile.

Syntax : int findfirst(const char *pathname,struct ffblk


*f,intattrib)

Listofattributes:

Theseattributesareincludedintheheaderfile<dos.h>

CONSTANT
DESCRIPTION

FA_RDONLY
Read
only
attribute

FA_HIDDEN
Hiddenfiles

FA_SYSTEM
Systemfiles

FA_LABEL
Volumelabel

FA_DIREC
Directory

FA_ARCH
Archivefile(ie.allfilesexcept

systemfiles
andvolumelebel)


ReturnValue:

0onsuccess(matchfound),elsereturnsnonzerovalue.
findnext():

Itcontinuesthesearch.

Syntax:
intfindnext(structffblk*f)

ReturnValue:

0onsuccess(matchfound),elsereturnsnonzerovalue.

Program:
ffblk.c

#include<stdio.h>
#include<conio.h>
#include<dir.h>
#include<dos.h>
voidmain()
{
structffblkf
intd,count=0
charst[50]
clrscr()
printf("EnterPath:")

gets(st)
d=findfirst(st,&f,FA_ARCH)
while(!d)
{
printf("\n%s",f.ff_name)
count++
if(count%20==0)
{
printf("\n\nPressanykeytoContinue......")
getch()
clrscr()
}
d=findnext(&f)
}
printf("\n\tTotalnumberofFiles:%d",count)
getch()
}
Output

1)Enterpath:
*.*
Itwilldisplayallfileinthecurrentworkingdirectory.

2)Enterpath:
*.c
It will display all .C programs in the current working
directory.

Bitfields:

Cpermitsustousesmallbitfieldstoholddata.We
have been using integer field of size 16 bit to store data.
The dataitemrequiresmuchlessthan16bitsofspace,in
such case we waste memory space. In this situation we
usesmallbitfieldsinstructures.

Thebitfieldsdatatypeiseitherintorunsignedint.
the maximum value that can store in unsigned intfiledis
: (2 powern)1 andinintfiledis:2power(n1).
Herenisthebitlength.

Note:

scanf() statement cannot read data into bit fields because


scanf() statement, scans on format data into 2 bytes
addressofthefiled.

Syntax:

structstruct_name
{
unsigned(or)intidentifier1:bit_length
unsigned(or)intidentifier2:bit_length

.
.
unsigned(or)intidentifierN:bit_length
}
Program:
bit_stru.c

#include<stdio.h>
#include<conio.h>
structemp
{
unsignedeno:7
charename[20]
unsignedage:6
floatsal
unsignedms:1
}
voidmain()
{
structempe
intn
clrscr()
printf("Entereno:")
scanf("%d",&n)
e.eno=n
printf("Enterename:")
fflush(stdin)
gets(e.ename)

printf("Enterage:")
scanf("%d",&n)
e.age=n
printf("Entersalary:")
scanf("%f",&e.sal)
printf("EnterMaritalStatus:")
scanf("%d",&n)
e.ms=n
clrscr()
printf("Employnumber:%d",e.eno)
printf("\nEmployname:%s",e.ename)
printf("\nEmployage:%d",e.age)
printf("\nEmploysalary:%.2f",e.sal)
printf("\nMaritalstatus:%d",e.ms)
getch()
}

Unions:

A union is similar to struct, except it allows us to define


variablesthatsharestoragespace.

Syntax:

unionunion_name
{

dataitem1
dataitem2

dataitemN
}[var_list]

Eg:

uniontest
{
intn
charc
floatsal
}t

Program:
un_stru.c

#include<stdio.h>
#include<conio.h>
structtest1
{
intn
charc
floatf
}t1
uniontest2
{

intn
charc
floatf
}t2

voidmain()
{
clrscr()
printf("Memorysizeofstruct:%dbytes",sizeof(t1))
printf("\nMemorysizeofunion:%dbytes",sizeof(t2))
getch()
}

Output

1)
Memorysizeofstruct:7bytes
Memorysizeofunion:4bytes

STRUCT
UNION
Agroupofdataitemsthat Itisalsosameasstruct,
belongstodifferentdata buttheonlymajor
types
differenceismemory
allocation.
Allocatesmemoryofall Allocatesmemoryof

declareddataitemsinit
Wecanaccessalldata
itemsatatime
Eachandeverydataitems
hasitsownstoragespace

biggestdataitemsinit
Wecanaccessonlyone
dataitemsatatime
Alltheitemsshared
commonstoragespace.

Program:
union.c

#include<stdio.h>
#include<conio.h>
unionemp
{
inteno
charename[20]
floatsal
}
voidmain()
{
unionempe
printf("Enterempno:")
scanf("%d",&e.eno)
printf("Empnumber:%d",e.eno)
printf("\n\nEnterempname:")
fflush(stdin)
gets(e.ename)
printf("Empname:%s",e.ename)

printf("\n\nEnterempsal:")
scanf("%f",&e.sal)
printf("Salary:%.2f",e.sal)
}

<dir.h>functions:

1.
getcwd:

Itgetsthecurrentworkingdirectory

Syntax:
char*getcwd(char*buf,intbuflen)

Program:
getcwd.c

#include<stdio.h>
#include<conio.h>
#include<dir.h>
voidmain()
{
charst[80]
clrscr()
getcwd(st,80)
printf("CurrentWorkingDirectory:%s",st)

getch()
}

2.
chdir:

Itchangesthecurrentworkingdirectory

Syntax:
intchdir(constchar*path)

ReturnValue:

Itreturns0ifsuccess,elsenonzero.

Program:
chdir.c

#include<stdio.h>
#include<conio.h>
#include<dir.h>
voidmain()
{
charst[80]
intn
clrscr()
printf("Enterpath:")
gets(st)
n=chdir(st)
if(n==0)

printf("DirectoryChanged")
else
printf("DirectorynotChanged")
getch()
}

Output

Enterpath:
E:\raji\cpp\programs
WewillgetthemessageDirectoryChanged
To check whether we have changed to that specific
directory or not, run the getcwd.c program in that
directory, then it will display the current working
directoryas:E:\raji\cpp\programs.

3.
mkdir:

Itcreatesadirectory

Syntax:
intmkdir(constchar*path)

ReturnValue:

Itreturns0ifsuccess,elsenonzero.

Program:
mkdir.c


#include<stdio.h>
#include<conio.h>
#include<dir.h>
voidmain()
{
charst[80]
intn
clrscr()
printf("EnterPath:")
gets(st)
n=mkdir(st)
if(n==0)
printf("DirectoryCreated")
else
printf("UnabletoCreateaDirectory")
}

Output

Enterpath:
rr
Directoryiscreatedinourcurrentdirectory.
Ifwegivesthesamepathonceagain,wewillget
Unabletocreateadir
Gotocommandpromptandtype
dir,
thendirectory
rr
is
displayedatthelast


4.
rmdir:

Itremovesadosfiledirectory.

Syntax:
intrmdir(constchar*path)

ReturnValue:

Itreturns0ifsuccess,elsenonzero.

rmdir deletes the directory whose path is given by the


path.Thedirectorynamedbythepath,
1 mustbeempty
1 mustnotbecurrentworkingdirectory
1 mustnotbetherootdirectory.

Program:
rmdir.c

#include<stdio.h>
#include<conio.h>
#include<dir.h>
voidmain()
{
charst[50]
intn
clrscr()

printf("EnterPath:")
gets(st)
n=rmdir(st)
if(n==0)
printf("Directoryisdeleted")
else
printf("UnabletodeleteaDirectory")
getch()
}

Output

GotoDOSshell
E:\raji\c\programs>mdraji
E:\raji\c\programs>cdraji
Directorycreated
E:\raji\c\programs\raji>copyconaa.txt
Goodmorning
Welcome
Ctrl+z
(1)fileiscopied

E:\raji\c\programs>typeaa
Thentheabovedataisdisplayed
E:\raji\c\programs>cdram
Directorycreated
Now our current working directory has 2 sub directories,

calledrajiandram.
Wecandeletethesubdirectoryrambyusingrmdir(),but
we cannot deleted the directory raji, because raji contain
one text file aa.txt, but ram is empty, hence we can
removeit.

Ifwewanttodeletedthedirectoryraji,thenagaingoto
DOSshell
E:\raji\c\programs\raji>delaa.txt
(1) filedeleted.

Nowwecandeletethefolderrajiwiththehelpofrmdir().

Files:

C language permits the usage of limited input and


output functions to read and write data. These functions
are used for only smaller volume of data and it becomes
difficult to handle longer data volumes. Also the entire
dataislostwhentheprogramover.
To overcome these difficulties a flexible method was
developed by employing the concept of files to store, to
read and write data and to return them even when the
programover.

Definition:

A file is one,whichenabletheusertostore,toread

andwriteagroupofrelateddata.
(or)
1)

2)
A file is a collection of records stored in a
particularareaonthedisk.

C supports a number of functions to have the ability to


performthebasicfileoperations,whichinclude:
namingafile
openingafile
readingdatafromfile
writingdatatofile
closingafile

Typesoffiles:
Filesaretwotypes,Namely
1. Textfiles(or)Sequentialfiles
1. Binaryfiles

Textfiles:

Used for reading and writing data in the form of


characters. The memory size of each and every character
is1byte.


Binaryfiles:

Used for reading and writing data in the form of data


blocks. The memory size of each and every data block
dependsonitsdatatype.

FILE:

It isapredefinedstructureandisusedtodeclareafile
pointer. Using this pointer, we can perform all file
operations.

DeclarationofFILEpointer:

Syntax
:
FILE*identifier.

Eg:

FILE*fp

Filehandlingfunctions:

fopen
:
Itopensafilestream.

Syntax:

FILE* fopen(const char*filename, constchar


*mode);

filename
:filethatthefunctionopens

modestring:

Therearevariousmodesandaredescribedinthe
following
table

String

Description

.
Openforreadingonly.

Createforwriting.
If afilebythatnamealreadyexists,itwillbe
overwritten

Append:
open for writing at end of file, or create for
writingifthefiledoesnotexist.

Open an existingfile forupdate(readingand


writing)

r+


w+

a+

Create a new file for update (reading and


writing).
If a file by that name already exists, it will
beoverwritten.

Openforappend:
open for update at the end of the file, or
createifthefiledoesnotexist.

Tospecifythatagivenfileisbeingopenedorcreatedintextmode,
append"t"tothestring(rt,w+t,etc.).

1 Tospecifybinarymode,append"b"tothestring(wb,a+b,etc.).

fclose:
Itclosesthefilestream.

Syntax:
intfclose(FILE*stream)

fcloseall:

Itclosesallopenfilestream.

Syntax:

intfcloseall()

Program:
file1.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
FILE*fp
clrscr()
fp=fopen("a.txt","w")
if(fp==NULL)
printf("Unabletoopenafile")
else
printf("Fileisopened")
getch()
}

If we specify the mode a, we will get the same output


(i.e. File is opened), if we specify the mode r, we will
gettheoutputasUnabletoopenafile.

Textfiles

getc :
It is a macro that gets one character from a file
stream.


Syntax:
intgetc(FILE*stream)

putc : It is a macro that outputs a character to a file


stream.

Syntax:
intputc(intc,FILE*stream)

fgetc:Itisafunctionthatgetsonecharacterfromafile
stream.

Syntax:
intfgetc(FILE*stream)

fputc : It is a function that outputs a character to a file


stream.

Syntax:
intfputc(intc,FILE*stream)

EOF:

It is a constant indicating that end of file has been


reached on a File. To get this character from keyboard
pressCtrl+Z(or)F6

Program:
file2.c


To create a text file and to store data into that file
throughkeyboard

#include<stdio.h>
#include<conio.h>
voidmain()
{
charch
FILE*fp
clrscr()
fp=fopen("a.txt","wt")
printf("Enterdata(Ctrl+Ztostop):")
ch=getchar()
while(ch!=EOF)
{
putc(ch,fp)
ch=getchar()
}
fclose(fp)
printf("Datastoredsuccessfully")
getch()
}

Program:
file3.c

Toopenafileandtoreaddatafromthefileanddisplay

onthemonitor
#include<stdio.h>
#include<conio.h>
voidmain()
{
FILE*fp
charch
clrscr()
fp=fopen("a.txt","rt")
printf("Readingdatafromthefile\n\n")
ch=getc(fp)
while(ch!=EOF)
{
printf("%c",ch)
ch=getc(fp)
}
fclose(fp)
getch()
}

Program:
file4.c

Toenterafileanddisplayitscontentsonthemonitor

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

{
FILE*fp
charch,st[20]
clrscr()
printf("EnterFilename:")
gets(st)
fp=fopen(st,"rt")
if(fp==NULL)
{
printf("\nFilenotfound")
getch()
exit(0)
}
printf("\n\nReadingdatafromthefile\n\n")
ch=getc(fp)
while(ch!=EOF)
{
printf("%c",ch)
ch=getc(fp)
delay(10)
}
fclose(fp)
getch()
}

Program:
file5.c

To enter a file and number of lines, words and


charactersinthefile

#include<stdio.h>
#include<conio.h>
voidmain()
{
FILE*fp
charch,ch1,st[20]
intnc=0,nw=0,nl=0
clrscr()
printf("EnterFilename:")
gets(st)
fp=fopen(st,"rt")
if(fp==NULL)
{
printf("\nFilenotfound")
getch()
exit(0)
}
ch=getc(fp)
while(ch!=EOF)
{
if(ch==32||ch=='\n')
{
nw++
if(ch=='\n')

nl++
}
else
nc++
ch1=ch

ch=getc(fp)
if(ch==32&&ch1==ch)
nw
}
printf("\nNumberofcharacters:%d",nc)
printf("\nNumberofwords:%d",nw)
printf("\nNumberoflines:%d",nl)
fclose(fp)
getch()
}

If more than one space is there between 2 words, the


compiler will treats the additional space as a word. To
avoidthisusetheabovetechnique.

rewind():

Itrepositionsfilepointertofilestreamsbeginning

Syntax:
voidrewind(FILE*stream)


Program:
file6.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
FILE*fp
charch
clrscr()
fp=fopen("a.txt","a+t")
printf("Enterdata(Ctrl+Ztostop):")
ch=getchar()
while(ch!=EOF)
{
putc(ch,fp)
ch=getchar()
}
printf("\nDatastoredsuccessfully")
rewind(fp)
printf("\n\nReadingdatafromthefile\n\n")
ch=getc(fp)
while(ch!=EOF)
{
printf("%c",ch)
ch=getc(fp)
}

fclose(fp)
getch()
}

fgets():

Itgetsastringfromfilestream.

Syntax:
char*fgets(char*s,intn,FILE*stream)

fgets reads characters from stream into the string s. it


stops when it reads either n1 characters of a new line
characterwhichevercomesfirst.

fputs():

Itoutputsastringtoafilestream.

Syntax:
char*fputs(char*s,FILE*stream)

fgets copies the null terminated string s to the given


outputstream.Itdoesnotappendanewlinecharacterand
theterminatingnullcharacterisnotcopied.

foef:

Itisamacro thattestsifendoffilehasbeenreachedona

filestream.

Syntax:
intfeof(FILE*stream)

Returnvalue:

1 Returns non zero if an end of file indicator was


detected on the last input operation on the named
stream.
1 Returns0ifendoffilehasnotbeenreached.

Program:
file7.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
FILE*fp
charst[80]
clrscr()
fp=fopen("str.txt","a+t")
printf("Enterstringdata('end'tostop):")
gets(st)
while(strcmp(st,"end")!=0)
{
fputs(st,fp)

fputs("\n",fp)
gets(st)
}
rewind(fp)
printf("\nReadingdatafromthefile:\n")
fgets(st,80,fp)
while(!feof(fp))
{
printf("%s",st)
fgets(st,80,fp)
}
getch()
fclose(fp)
}

Output

Enterdata:
Raji
Ram
Ramraji
Rajiram
Bunny
end

fprintf():

Itsendsformattedoutputtoafilestream.

Syntax:
intfprintf(FILE*stream,constchar*format[,argument,...])

fscanf():

Itscansandformatsinputfromafilestream.

Syntax : int fscanf(FILE *stream,const char *format


[,address,...])

Note:

Infprintfandfscanf,betweenformatsatleastonespaceis
necessary.

Program:
file8.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
inteno
charename[20]
floatsal
FILE*fp
clrscr()

fp=fopen("emp.txt","wt")
printf("Enterempno:")
scanf("%d",&eno)
printf("Enterename:")
fflush(stdin)
gets(ename)
printf("Entersal:")
scanf("%f",&sal)
fprintf(fp,"%d%s%.2f",eno,ename,sal)
fclose(fp)
printf("\nRecordsavedsuccessfully")
getch()
}
Program:
file9.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
inteno
charename[20]
floatsal
FILE*fp
clrscr()
fp=fopen("emp.txt","rt")
fscanf(fp,"%d%s%f",&eno,ename,&sal)
fclose(fp)

printf("\nReadingdatafromfile")
printf("\n\nEnterempno:%d",eno)
printf("\nEnterename:%s",ename)
printf("\nEntersal:%.2f",sal)
getch()
}

Program:
file10.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
inteno
charename[20],ch
floatsal
FILE*fp
clrscr()
fp=fopen("emp1.txt","a+t")
do
{
printf("Enterempno:")
scanf("%d",&eno)
printf("Enterename:")
fflush(stdin)
gets(ename)
printf("Entersal:")

scanf("%f",&sal)
fprintf(fp,"%d%s%.2f\n",eno,ename,sal)
printf("\n\nRecordsavedsuccessfully")
printf("\n\nDouwanttoaddanotherrecord(y/n):")
fflush(stdin)
scanf("%c",&ch)
}while(ch!='n')
rewind(fp)
printf("\nReadingdatafromfile\n\n")
printf("%10s%15s%s","ENO","ENAME","SAL")
printf("\n")
while(!feof(fp))
{
fscanf(fp,"%d%s%f\n",&eno,ename,&sal)
printf("\n%10d%15s%.2f",eno,ename,sal)
}
fclose(fp)
getch()
}

ftell:

Itreturnsthecurrentfilepointer

Syntax
:longftell(FILE*stream)

fseek:


Itrepositionsthefilepointerofafilestream

Syntax:
intfseek(FILE*stream,longoffset,int
whence)

stream:

Whosefilepointerfseeksets

offset:

Differenceinbytesbetweenwhenceandnew
position.

whence:

OneofthreeSEEK_xxxfilepointerlocations(0,
1,or2)

ConstantValueFilelocation

SEEK_SET0Seeksfrombeginningof
file
SEEK_CUR1Seeksfromcurrent
position
SEEK_END2Seeksfromendoffile

Program:
file11.c

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

voidmain()
{
FILE*fp
charch
clrscr()
fp=fopen("z.txt","w")
printf("Currentfilepointerposition:%lu",ftell(fp))
printf("\n\nEnterdata(Ctrl+Ztostop):")
ch=getchar()
while(ch!=EOF)
{
putc(ch,fp)
ch=getchar()
}
printf("Presentfilepointerposition:%lu",ftell(fp))
fseek(fp,10,1)//fseek(fp,10,SEEK_CUR)
printf("\nNewfilepointerposition:%lu",ftell(fp))
fclose(fp)
getch()
}

Binaryfiles:

getw:

Itgetsanintegerfromafilestream.


Syntax:
intgetw(FILE*stream)

putw:

Itoutputsanintegeronafilestream.

Syntax:
intputw(intw,FILE*stream)

Program:
file12.c

#include<stdio.h>
#include<conio.h>
voidmain()
{
FILE*fp
intn
clrscr()
fp=fopen("a.dat","a+b")//appendinbinaryformat
printf("Enterdata(0tostop):\n\n")
scanf("%d",&n)
while(n!=0)
{
putw(n,fp)
scanf("%d",&n)
}

fseek(fp,0,0)//rewind(fp)
printf("\n\nReadingdatafromfile:\n\n")
n=getw(fp)
while(!feof(fp))
{
printf("%d\n",n)
n=getw(fp)
}
fclose(fp)
getch()
}

fwrite:

Itappendsaspecifiednumberofequalsizeddataitemstoanoutputfile.

Syntax:
size_tfwrite(void*ptr,size_tsize,size_tn,FILE
*stream)

fread:

Itreadsspecifiednumberofequalsizeddataitemsfromaninputfileinto
ablock.

Syntax:
size_tfread(void*ptr,size_tsize,size_tn,FILE*stream)

argumnet
description


ptr pointertoablockintowhichthedataisread/write

sizelengthofeachitemread/writeinbytes

nnumberofitemsread/write

streampointstooutput/inputstream

Program:
file13.c

#include<stdio.h>
#include<conio.h>
structstudent
{
intsno
charsname[20],course[10]
floatfee
}
voidmain()
{
structstudents
FILE*fp
clrscr()
fp=fopen("student.dat","wb")
printf("Enterstudentnumber:")
scanf("%d",&s.sno)
printf("Enterstudentname:")
fflush(stdin)
gets(s.sname)

printf("Entercourse:")
gets(s.course)
printf("Enterfee:")
scanf("%f",&s.fee)
fwrite(&s,sizeof(s),1,fp)
fclose(fp)
printf("\n\nRecordsavesucessfully")
getch()
}

Program:
file14.c

#include<stdio.h>
#include<conio.h>
structstudent
{
intsno
charsname[20],course[10]
floatfee
}
voidmain()
{
structstudents
FILE*fp
clrscr()
fp=fopen("student.dat","rb")
fread(&s,sizeof(s),1,fp)
printf("Readingdatafromfile\n\n")
printf("Studentnumber:%d",s.sno)
printf("\nStudentname:%s",s.sname)
printf("\nCourse:%s",s.course)
printf("\nFee:%.2f",s.fee)
fclose(fp)

getch()
}

Program:
file15.c

#include<stdio.h>
#include<conio.h>
structstudent
{
intsno
charsname[20],course[5]
floatfee
}
voidmain()
{
FILE*fp
charch
structstudents
clrscr()
fp=fopen("student.dat","a+b")
do
{
printf("Enterstudentnumber:")
scanf("%d",&s.sno)
printf("Enterstudentname:")
fflush(stdin)
gets(s.sname)
printf("Entercourse:")
fflush(stdin)
gets(s.course)
printf("Enterfee:")
scanf("%f",&s.fee)
fwrite(&s,sizeof(s),1,fp)

printf("\nRecordsavedsuccessfully")
printf("\n\nDoyouwanttoaddanotherrecord(y/n):")
fflush(stdin)
scanf("%c",&ch)
}
while(ch!='n')
fseek(fp,0,0)
fread(&s,sizeof(s),1,fp)
while(!feof(fp))
{
clrscr()
printf("\nStudentnumber:%d",s.sno)
printf("\nStudentname:%s",s.sname)
printf("\ncourse:%s",s.course)
printf("\nFee:%.2f",s.fee)
printf("\n\nPressanykeetocontune.........")
getch()
fread(&s,sizeof(s),1,fp)
}
fclose(fp)
getch()
}

enum,typedef

Commandlinearguments:

Thesearetheparameterssuppliedtoaprogram,whenthe
programisinvoked.Thisparametermayrepresentafile

namethattheprogramshouldprocess.Commandline
argumentsaretypedbytheuser.Thefirstargumentis
alwaysthefilename.
Weknowthat,everyCprogramshouldhaveonemain
functionanditcantakeargumentslikeotherfunctions.If
wewanttoworkwithcommandlinearguments,themain
functioncantake2argumentscalledargcandargvand
theinformationcontainedinthecommandlineis
processedontotheprogramthroughthesecommandline
arguments.
Thevariableargcisanargumentcounterthatcounts
Noofargumentsonthecommandline.Theargument
argvisanargumentvectorthatrepresentsanarrayof
characterpointersthatpointstothecommandline
arguments.Thesizeofthisarrayisequaltothevalueof
argc.

Program:
cla1.c

#include<stdio.h>
#include<conio.h>
voidmain(intargc,char*argv[])
{
inti

clrscr()
printf("Numberofargument:%d",argc)
for(i=0i<argci++)
{
printf("\nargument[%d]:%s",i,argv[i])
}
getch()
}

Program:
cla2.c

#include<stdio.h>
#include<conio.h>
voidmain(intargc,char*argv[])
{
FILE*fp
charch
clrscr()
if(argc!=2)
{
printf("Invalidarguments")
exit(0)
}
fp=fopen(argv[1],"w")
ch=getchar()
while(ch!=EOF)
{

putc(ch,fp)
ch=getchar()
}
fclose(fp)
printf("Filecreated")
getch()
}

Program:
cla3.c

#include<stdio.h>
#include<conio.h>
voidmain(intargc,char*argv[])
{
FILE*fp
charch
clrscr()
if(argc!=2)
{
printf("Invalidarguments")
exit(0)
}
fp=fopen(argv[1],"r")
if(fp==NULL)
{
printf("Filenotfound")
exit(0)

}
ch=getc(fp)
while(ch!=EOF)
{
printf("%c",ch)
ch=getc(fp)
}
fclose(fp)
getch()
}

Program:
cla4.c

#include<stdio.h>
#include<conio.h>
voidmain(intargc,char*argv[])
{
FILE*fp1,*fp2
charch
if(argc!=3)
{
printf("Invalidarguments")
exit(0)
}
fp1=fopen(argv[1],"r")
if(fp1==NULL)
{

printf("Filenotfound")
exit(0)
}
fp2=fopen(argv[2],"r")
if(fp2!=NULL)
{
printf("Filealreadyexists:%s",argv[2])
printf("\nDoyouwanttooverride(y/n):")
scanf("%c",&ch)
if(ch=='n'||ch=='N')
{
printf("Unabletocopyafile")
fcloseall()
exit(0)
}
fclose(fp2)
fp2=fopen(argv[2],"w")
ch=getc(fp1)
while(ch!=EOF)
{
putc(ch,fp2)
ch=getc(fp1)
}
fcloseall()
}
printf("Filecopiedsuccessfully")
}

Program:
design.h

#include<stdio.h>
#include<conio.h>
voidhline(intr,intsc,intec)
{
inti
for(i=sci<=eci++)
{
gotoxy(i,r)
printf("%c",196)
}
}
voidvline(intc,intsr,inter)
{
inti
for(i=sri<=eri++)
{
gotoxy(c,i)
printf("%c",179)
}
}

voidbox(intsc,intsr,intec,inter)
{
gotoxy(sc,sr)
printf("%c",218)
gotoxy(ec,sr)
printf("%c",191)
gotoxy(sc,er)
printf("%c",192)
gotoxy(ec,er)
printf("%c",217)
hline(sr,sc+1,ec1)
hline(er,sc+1,ec1)
vline(sc,sr+1,er1)
vline(ec,sr+1,er1)
}

Program:
shuffle.c

#include<process.h>
#include<stdlib.h>
#include"design.h"
voidmain()
{

voidgenerate(int[][4])
inta[4][4]
inti,j,r,c,count=0
charch
_setcursortype(_NOCURSOR)
generate(a)
while(1)
{
clrscr()
gotoxy(35,2)
printf("SHUFFLEGAME")
box(22,3,58,19)
hline(7,23,57)
hline(11,23,57)
hline(15,23,57)
vline(30,4,18)
vline(40,4,18)
vline(50,4,18)
gotoxy(32,21)
printf("Numberofkeystrokes:%d",count)
gotoxy(35,23)
printf("Esctoexit")
gotoxy(35,25)
printf("Alt+Stoshuffle")
for(i=0i<4i++)
{
for(j=0j<4j++)

{
gotoxy(25+j*10,5+i*4)
if(a[i][j]!=0)
printf("%d",a[i][j])
else
{
r=i
c=j
}
}
}
ch=getch()
if(ch==0)
ch=getch()
count++
if(count>200)
{
clrscr()
textcolor(15+128)
gotoxy(35,12)
printf("GAMEOVER")
getch()
exit(0)
}
switch(ch)
{
case80:

if(r>0)
{
a[r][c]=a[r1][c]
a[r1][c]=0
}
break
case72:
if(r<3)
{
a[r][c]=a[r+1][c]
a[r+1][c]=0
}
break
case77:
if(c>0)
{
a[r][c]=a[r][c1]
a[r][c1]=0
}
break
case75:
if(r<3)
{
a[r][c]=a[r][c+1]
a[r][c+1]=0
}
break

case31:
generate(a)
count=0
break
case27:
exit(0)
}
if(a[0][0]==1&&a[0][1]==2&&a[0][2]==3&&
a[0][3]==4&&
a[1][0]==5&&a[1][1]==6&&a[1][2]==7&&
a[1][3]==8&&
a[2][0]==9&&a[2][1]==10&&a[2][2]==11&&
a[2][3]==12&&
a[3][0]==13&&a[3][1]==14&&a[3][2]==15&&
a[3][3]==0)
{
clrscr()
textcolor(15+128)
gotoxy(35,12)
cprintf("GAMESUCCESS")
gotoxy(32,15)
printf("Numberofkeystrokes:%d",count)
getch()
exit(0)
}
}
}

voidgenerate(inta[][4])
{
intx[16],n,id=0,i,j
charck
randomize()
while(id<16)
{
n=random(16)
ck=0
for(i=0i<idi++)
{
if(x[i]==n)
{
ck=1
break
}
}
if(ck==0)
{
x[id]=n
id++
}
}
id=0
for(i=0i<4i++)
{
for(j=0j<4j++)

{
a[i][j]=x[id]
id++
}
}
}

Conversionfunctions:

atoi:
Itisamacrothatconvertsstringtoint.

Syntax:
intatoi(const

Vous aimerez peut-être aussi