C Language Basic Question
C Language Basic Question
Syllabus
S
for 1st midsem exa
am
Draw th
he block diag
gram of com
mputer architecture and
d explain ea
ach block.
Computerr is made up of
o mainly fourr components,,
1)
C
Central
proces
ssing unit (CPU
U)
2)
Input section
3)
O
Output
section
n
4)
S
Storage
device
es
OUTPUT SE
ECTION
(Mouse
e, Keyboard, ettc...)
(
(Monitor,
Printe
er, etc)
PR
RIMARY MEM
MORY
(
(RAM,
ROM, ettc)
SEC
CONDARY MEMORY
(Hard
d disk, Pen driv
ve, etc)
1) Central
C
Proce
essing Unit (CPU):(
It contains
s electronics circuitry
c
that p
processes the data based on instructions
s.
It also con
ntrols the flow
w of data in the
e system.
It is also known
k
as brain of the comp
puter.
CPU consis
sts of,
1
1.1)
Arithm
metic Logic Un
nit (ALU)
9
Itt can perform add, subtractt, multiply, compare, count,, shift and oth
her logical activities.
Itt calculates ve
ery fast.
1
1.2)
1
1.3)
Contro
ol Unit (CU)
9
Primary Memory:9
Th
he processor or
o the CPU dirrectly stores and
a
retrieves iinformation frrom it.
1
Darshan Insttitute of En
ngineering & Technology
Syllabus
S
for 1st midsem exa
am
Generally curren
ntly executing programs and data are sto
ored in primarry memory
RO
OM is Read Only Memory an
nd it can hold data permane
ently.
PRO
OM is Program
mmable Read Only Memory
y and it can h
hold data perm
manently. Pro
ogrammer
can
n store inform
mation only once. Modificatio
on is not allow
wed.
EPR
ROM is Erasa
able Program
mmable Read Only Memorry. It can ho
old data perm
manently.
Pro
ogrammer can
n delete and w
write on it again and again.
2) Input
I
Section
n:
The device
es used to entter data in to computer sys
stem are called
d input device
es.
It converts
s human unde
erstandable in
nput to compu
uter controllab
ble data.
CPU accep
pts information
n from user th
hrough input devices.
d
3) Output
O
Sectio
on:
The device
es used to send the inform
mation to the outside world from the com
mputer is called output
devices.
It converts
s data stored in 1s and 0s iin computer to human unde
erstandable in
nformation
4) Storage
S
devic
ces (Secondary memory
y):-
Secondary
y memory is also
a
called Aux
xiliary memory
y or External memory.
It can be modified
m
easily.
Describe
e advantage
es and limita
ations of co
omputer. Or Explain cha
aracteristics
s of compute
er.
Advantages
S
Speed:
It can calculate millions of expre
essions within a fraction of second. The micro
m
second and nano
s
second
units are
a used to measure
m
the sp
peed of computers. There are
a some problems which cannot
c
be
s
solved
within specified
s
time limit without computer.
S
Storage:
It ca
an store data in large quan
ntity using varrious storage devices. Millio
ons of paper files data
c
can
be stored in single sma
all pen drive. M
Moreover, it reproduces
r
da
ata whenever we need and whatever
fo
ormat we nee
ed. Now a day
ys, Gigabytes a
and Terabytes
s are units of data storage devises.
A
Accuracy:
Co
omputer perfforms the computations at
a very high speed witho
out any mista
akes. For
e
example,
multtiplication of two very larrge number takes more time for huma
an and there are high
p
probabilities
of mistakes. Computer
C
does it in parts of
o the second
d with accurac
cy level we want.
w
Very
h
high
level of accuracy
a
is must in financia
al transaction, medical surrgery, nuclearr plant, etc which
w
can
b satisfied by
be
y computer on
nly.
R
Reliability:
Itt is very relia
able device. T
The informatio
on stored in c
computer is available
a
afterr years in
2
Darshan Insttitute of En
ngineering & Technology
Syllabus
S
for 1st midsem exa
am
s
same
form. It works 24 hou
urs without an
ny problem as it does not fe
eel tiredness.
A
Automation:
Once the one task is crea
ated in a com
mputer, it can
n be repeatedly performed again by
s
single
click wh
henever we want. For exam
mple, once the
e software forr banking application is insttalled in a
c
computer,
it co
omputes the interest
i
by sending one com
mmand.
Limitatio
ons
L
Lake
of intellligence: It ca
annot think wh
hile doing worrk. It does nott have natural intelligence. It cannot
think about prroperness or effect
e
of work
k it is doing. It
I can only ex
xecute the ins
structions but it cannot
think about the correctness of these instrructions.
U
Unable
to Co
orrect Mistak
kes: It cannott correct the mistakes by itself. So if we
e have provid
ded wrong
o incorrect da
or
ata then it pro
oduces wrong results or perrforms wrong calculations.
Describe
e various ty
ypes of comp
puter langua
ages and mention its advantages and
a
disadva
antages.
Computerr languages may
m
be classified in three ca
ategories,
1)
Machine lev
vel language
e or Low leve
el language:-
ADVANTA
AGES:
1.
It is very
v
fast in ex
xecution
2.
3.
Trans
slation is not required.
4.
Suita
able for low vo
olume applicattions.
DISADVA
ANTAGES:
1.
2.
Debu
ugging is very difficult task..
3.
It is not portable.
4.
2) Assembly la
anguage:
Every ma
achine langua
age instruction
n is assigned to English word
w
MNEMON
NIC such that it should
describe function of ins
struction.
System cannot
c
unders
stand this language directly
y so we requiire translator that convert assembly
language
e to machine la
anguage. This
s translator is called assembler.
ADVANTA
AGES:
1.
2.
3.
DISADVA
ANTAGES:
1.
It is not portable.
2.
3.
It req
quires assemb
bler as a trans
slator.
We can write
w
programs in English lik
ke manner an
nd it is more convenient to use.
Programm
mer can perfo
orm complex ttask by using high level languages with le
ess efforts.
3
Darshan Insttitute of En
ngineering & Technology
ADVANTA
AGES:
1)
Easie
er to learn.
2)
Requ
uires less time
e to write.
3)
Proviides better do
ocumentation.
4)
Easie
er to maintain.
5)
It is portable.
Syllabus
S
for 1st midsem exa
am
DISADVA
ANTAGES:
1)
It req
quires compile
er or interpretter to convert higher level language to machine
m
language.
2)
Progrrammers need
d to learn stru
ucture of high level languag
ge.
3)
Why C is
s called mid
ddle level lan
nguage?
C is called
d middle levell language bec
cause
S
Syntax
and ke
eywords of C are
a just like hiigher level lan
nguage (Englis
sh).
It gives access
s to the low le
evel memory tthrough Pointe
ers.
M
Moreover
it do
oes support th
he Low Level p
programming i.e., Assembly
y Language.
It is not hardw
ware or system
m dependent. Hence portab
ble programs c
can be written
n with C comp
piler.
O
Operating
systtem: It contro
ols hardware as well as interacts with us
sers, and prov
vides different services
to user. It is a bridge betwe
een computer hardware and
d user. Ex: Wiindows XP, Lin
nux, UNIX, etc
2)
S
System
suppo
ort software: It
I makes worrking of hardw
ware more effficiently. For example
e
drive
ers of the
I//O devices or routine for so
ocket program
mming, etc
3)
S
System
develo
opment softw
ware: It provid
des programm
ming developm
ment environm
ment to programmers.
E Editor, pre
Ex:
e-processor, compiler, interrpreter, loaderr, etc..
Application software
e
Applicatio
on software is designed to help
h
the user to perform ge
eneral tasks (word processiing, web brow
wser ) or
some spe
ecific task (ac
ccounting, tick
ket booking ).
Example: Enterprise so
oftware, Accou
unting softwa
are, Office
suites, Grraphics softwa
are and media
a players.
Applicatio
on software is classified into
o two categories.
1)
G
General
purpo
ose software:: It is used widely by many
m
people ffor some com
mmon task, like word
p
processing,
we
eb browser, ex
xcel, etc It is designed on
n vast conceptt so many peo
ople can use itt.
4
Darshan Insttitute of En
ngineering & Technology
2)
Syllabus
S
for 1st midsem exa
am
S
Special
purpos
se software: It
I is used by limited people
e for some sp
pecific task lik
ke accounting software,
tax calculation
n software, tic
cket booking software, ban
nking softwarre etc It is designed
d
as per
p
users
s
special
require
ement.
Define the
t
following
g terms:
1.
P
Program
A set of instruc
ction in a logical order to perform a mea
aningful task is
s called progrram.
2.
S
Software
A set of instrruction in a lo
ogical order to
t perform a meaningful task is called
d program, and set of
p
program
is called software.
3.
H
Hardware
P
Physical
parts of computer is
i known as H
Hardware. Use
er can see and
d touch the ha
ardware compo
onents.
4.
O
Operating
sy
ystem
O
Operating
systtem is system
m software whiich works as an
a interface be
etween hardw
ware and user and
p
provides
intera
active platform
m to user.
5.
A
Assembler
A
Assembler
is system
s
software which conv
verts program
ms of assembly
y language to machine lang
guage.
6.
C
Compiler
It translates programs
p
of higher level language to ma
achine langua
age. It converrts whole prog
gram at a
time.
7.
I
Interpreter
It translates programs of higher level language to mac
chine language. It converts program line by line.
Darsh
han Institu
ute of Engin
neering & T
Technology
y
Co
omputer Pro
ogramming and Utilizattion (CPU) 110003
B) Flowch
hart & Algor
rithm
What is Algorithm?
A
W
What
is Flow
wchart? Write down the
e advantage
es and disad
dvantages. Compare
C
them.
Flowchartt
Flowch
hart is a pictorial or graphic
cal representa
ation of a pro
ocess. Each sttep in the pro
ocess is represented by a
different symbol an
nd contains a short description of the process step
p. The flow chart
c
symbols
s are linked
togethe
er with arrow
ws showing th
he process flo
ow direction. This pictorial representatio
on can give step-by-step
s
solution of the given
n problem.
ntages
Advan
Easy to draw.
Disadv
vantages
Tim
me consuming
g.
Diffficult to modiify.
Ve
ery difficult to draw flowchart for big or complex proble
ems.
Algorithm
m
An Algorithm is a fin
nite sequence of well define
ed steps for so
olving a problem in system
matic manner. It is written
in the natural langua
ages like English.
Advan
ntages
Easy to write.
Hu
uman readable
e techniques to
t understand logic.
Alg
gorithms for big
b problems can
c
be written
n with modera
ate efforts.
Disadv
vantages
Diffficult to debu
ug.
Diffficult to show
w branching an
nd looping.
Jum
mping (goto) makes it hard
d to trace som
me problems.
Compariso
on:
Flowcharrt
Algorithm
It is step wise
w
analysis of
o the work to be done.
It is somew
what difficult to understand.
Easy to sh
how branching
g and looping.
Algorithm can
c
be written
n for any problem
Darsh
han Institu
ute of Engin
neering & T
Technology
y
Start / Stop
Input / Output
(Read / Print)
Process
Decisio
on making
Subrou
utine
s
Arrows
rite an algo
orithm and
d Draw a flo
owchart
Wr
3
To find wh
hether given
n number is even
e
or odd.
Algorithm
m:Step 1 :
Input no.
Step 2 :
Step 3 :
Print given
n no is odd, go
oto 5.
Step 4 :
Print given
n no is even.
Step 5 :
Stop.
start
Flowchartt:-
Read
R
No
Yes
Is No
o mod 2=0?
No
Print no is Odd
Print no is Even
sttop
Darsh
han Institu
ute of Engin
neering & T
Technology
y
To enter number
n
still user wants and
a
at the en
nd it should display coun
nt of total nu
umber of pos
sitive,
negative and
a
zero enttered.
Algorithm
m:Step 1 :
Initialize po
os0,neg0,,zero0
Step 2 :
Read no
Step 3 :
If no>0, go
oto 6
Step 4 :
If no<0, go
oto 7
Step 5 :
Increment zero by 1, ze
ero=zero+1.go
o to 8
Step 6 :
Step 7 :
Step 8 :
Print Do you
y
want to en
nter more num
mber?
Step 9 :
Read ans
Step 10 :
If ans = y
y, goto 2
Step 11 :
Step 12:
Stop.
Flowchartt:-
start
pos0,neg
g0,zero0
Read no
Yes
s
pospos+1
1
No
Is no>0?
n
Yes
Is no<0?
neg
neg+1
Yes
No
zeroz
zero+1
Do you wa
ant to
enter morre no?
No
Print pos, ne
eg, zero
stop
Darsh
han Institu
ute of Engin
neering & T
Technology
y
m
number from a given 3 num
mbers.
To print maximum
Algorithm
m:Step 1 :
Read a ,b, c
Step 2 :
If a>b, goto 5
Step 3 :
If b>c, gotto 8
Step 4 :
Print c is maximum
m
goto
o9
Step 5 :
If a>c, gotto 7.
Step 6 :
Print c is maximum,
m
gotto 9
Step 7 :
Print a is maximum,
m
gotto 9
Step 8 :
Print b is maximum
m
Step 9 :
Stop.
Flowchartt:-
start
Read a, b, c
Yes
s
Yes
Print max = a
Is
a>c?
No
Is
a > b?
Yes
No
Print
P
max = c
Is
b>c?
Print max = b
stop
No
Print ma
ax= c
Darsh
han Institu
ute of Engin
neering & T
Technology
y
Initialize count1,fact
1
Step 2 :
Read no
Step 3 :
Calculate factfact
f
* co
ount.
Step 4 :
Step 5 :
If count<=
=no, goto 3.
Step 6 :
Print fact.
Step 7 :
Stop.
Flowchartt:-
start
Read no
co
ount1,fact
1
cou
unt count + 1
Ye
es
Is
count<=no?
?
No
Print fact
stop
Darsh
han Institu
ute of Engin
neering & T
Technology
y
To solve series
s
1!+2!+
+3!+4!+
.+n!
Algorithm
m:
Step 1 :
=1, sum=0
Initialize count=1, fact=
Step 2 :
Read no
Step 3 :
nt
f
Calculate fact=fact*cou
Step 4:
Calculate sum=sum
s
+ fact.
f
Step 5:
Step 6:
If count<=
=no, goto 3.
Step 7:
Print sum.
Step 8:
Stop.
Flowchartt:
start
Read no
o
cou
unt1,fact1
1,sum0
fa
actfact * co
ount
s
sumsum + fact
c
countcount
+1
Yes
Y
Is
count<=n
no?
N
No
Print sum
m
stop
Darshan Insttitute of En
ngineering & Technology
Syllabus
S
for 1st midsem exa
am
Explain
n basic structure of C program.
Basic Structure off C Program is as below,
Exam
mple of C Prog
gram is as below,
Docum
mentation Section
// This
s program is to
t find area off circle
Link Section
#inclu
ude<stdio.h>
Definittion Section
#defin
ne PI 3.14
int i;
float areaofcircle(flo
a
oat);
main())
void main()
m
{
Declaration
n Part
//Declaratio
on Part
float r,area
a;
Executable Part
//Executable Part
scanf(%f,&r);
area=areao
ofcircle(r);
printf(Area
a of Circle is :- %f,area);
}
Subpro
ogram Section
n (User Define
ed Section)
float areaofcircle(flo
a
oat r)
Function1()
Function2()
return PI * r * r;
}
Explain
n printf() and
d scanf() fun
nction with s
syntax.
The stdio.h header fiile provides built in functions for reading
g (scanf) data
a from input devices
d
(keybo
oard) and
writing (printf) forma
atted data to output
o
devices
s (monitor).
scanf()
):
Syntax:
int scan
nf(const ch
har *format,
, ...)
Example:
scanf(%
%d, &i);
First argume
ent is the spec
cification of format and othe
er arguments are pointer variables
v
to sto
ore data.
scanf() stop
ps when it ex
xhausts its fo
ormat string or when som
me input fails to match th
he control
specification.
printf():
printf() is a library
l
functio
on that prints formatted
f
datta to standard
d output, gene
erally monitor.
Syntax:
int prin
ntf(char * format, arg
g1, arg2, )
Exampe:
printf(
Your marks
s are %d, mark);
m
Syllabus
S
for 1st midsem exa
am
Darshan Insttitute of En
ngineering & Technology
The string fo
ormat consists
s of two types
s of items - characters
c
tha
at will be printted on the screen, and
format comm
mands that de
efine how the other argume
ents to printf()) are displayed.
Explain
n different da
ata types av
vailable in C.
A data type
t
is a class
sification of va
arious types o
of data, as floating-point, in
nteger, or striing. C is rich in
i its data
types to
o allow progra
ammer to sele
ect appropriate
e type of data
a type.
Data T
Type in C
Priimary data ty
ype
Secondary data type
(int,
(
float, charr)
D
Derived data type
User defined
d
data ttype
(array, pointter)
1) Primary data ty
ypes
Prim
mary data typ
pes are built in
n data types. T
They are direc
ctly supported
d by machine. They are also
o known
as fundamental
f
data
d
types.
a.
int
nteger which is whole num
mber without fraction partt. Its range is machine dependent
d
int is in
values. C has 3 class
ses of integerr storage nam
mely short int, int and long
g int. All of th
hese data
types ha
ave signed and
d unsigned forms.
sig
gned
Size
u
unsigned
Range
S
Size
(bits)
b.
Range
(bits)
short int
-128 to 127
0 to 255
int
16
-32768 to 32
2767
16
0 to 65535
long in
nt
32
-2,14,74,83,,648 to 2,14,7
74,83,647
3
32
0 to 4,29,49
9,67,295
char
char datta type can sto
ore single cha
aracter of alph
habet or digit or special sym
mbol. Each ch
haracter is
assigned
d some intege
er value which is known as ASCII
A
values.
siigned
charr
c.
Uns
signed
Size
S
(bits)
Range
Size (b
bits)
Range
-128 to 127
0 to 255
float
float datta type can store
s
floating point numbe
er which represents a reall number with
h decimal
point and fractional part.
p
When the
e accuracy off the floating point numberr is insufficien
nt, we can
Syllabus
S
for 1st midsem exa
am
Darshan Insttitute of En
ngineering & Technology
d.
Size (bits)
Precision Digits
D
Rang
ge
float
32
3.4E
E-38 to 3.4E+3
38
double
64
14
1.7E
E-308 to 1.7E+
+308
long float
80
3.4E
E-4932 to 1.1E
E+4932
void
The void
d type has no value therefo
ore we cannott declare it as
s variable as we
w did in case
e of int or
float or char.
c
The void
d data type is used to indica
ate that function is not retu
urning anythin
ng.
2) Sec
condary data
a types
Sec
condary data types
t
are not directly suppo
orted by the machine.
m
It is combination of primary data types
to handle
h
real life
e data in more
e convenient way. It can be
e further divid
ded in two cattegories,
a.
Derived
d data type
Derived data type is extension
e
of primary
p
data ty
ype. It is builtt-in system an
nd its structurre cannot
be chang
ged. Examples: Array, Poin
nter, etc
b.
i.
ii.
User de
efined data ty
ypes
User deffined data type can be created by progra
ammer using c
combination of
o primary datta type
and/or derived
d
data ty
ype. Use can design it as per special requirements
i.
structure: Strructure is a co
ollection of log
gically related data items off different datta types
grouped toge
ether and know
wn by a single
e name.
ii.
iii.
Explain
n types of co
onstant in de
etail.
Constan
nt is somethin
ng whose value does not ch
hange through
hout the progrram.
Consta
ants
Nu
umeric constant
Integer consta
ant
Real constant
Non
n numeric constant
Single character co
onstant
String co
onstant
Darshan Insttitute of En
ngineering & Technology
Syllabus
S
for 1st midsem exa
am
Integer constant:
Integer cons
stant is a number without decimal point and
a
fractional part
Decim
mal integer
Decim
mal integer con
nsist of a set of
o digits, 0 to 9 having optiional or + sign. No other
characters are allow
wed like space
e, commas, an
nd non-digit c
charcters.
Ex: 12
23, -321, 0, +78
+
Octal integer
Octal integer consis
sts of any com
mbination of digits from the
e set 0 to 7. Octal
O
numbers are
alway
ys preceded by
y 0.
Ex: 03
37, 0, 0551
Hexad
decimal intege
er
Hexad
decimal intege
er consists of any combinattion of digits from the set 0 to 9 and A to
oF
alphab
bets. It alway
ys starts with 0
0x or 0X. A re
epresents 10, B represents 11 F represents 15.
Ex: 0X
X2A, 0x95, 0x
xA47C.
Real co
onstant:
A real numb
ber may also be
b expressed in exponentia
al notation.
Single character co
onstant:
Ex: 5, A, ;,
String constant:-
A string cons
stant is a sequ
uence of chara
acters enclose
ed within a do
ouble inverted comma.
The characte
ers may be lettter, number, special character, blank sp
pace, etc
?A.B
B,!, 5+3, etc
What is
s variable? Give
G
the rule
es to define v
variable nam
me.
A variab
ble is a data name
n
that is used
u
to store a data value. A variable ma
ay take differe
ent values at different
d
times during executio
on of the prog
gram.
Rules to
o define variab
ble name:
1.
It must cons
sists of only alphabets (a to
o z & A to Z), digits
d
(0 to 9)) & underscore
e (_).
2.
3.
4.
uage is known
n as token.
Smallest unit of any langu
Darshan Insttitute of En
ngineering & Technology
Syllabus
S
for 1st midsem exa
am
Identiffier:
An identifier is a sequence
e of letters and digits.
Keyword:
Keywords arre reserved wo
ords whose meaning
m
is fixed and they arre used for som
me special pu
urpose by
the compilerr.
void - data
d
type:
void is a prim
mary data type. void means
s nothing, no value.
Explain
n operators available
a
in C
An operrator is a symbol that tells the
t
compiler to
t perform certain mathematical or logical operation. C has
rich set of operators as below,
1.
Arithmetic Ope
erators
Aritthmetic operators are used for mathematical calculatio
on. C supports following arithmetic opera
ators
+
a b (subtrraction), -8 (u
unary minus)
Multiplic
cation
a*b
Division
a/b
Modulo division
d
a % b (this
s operator can
n be used with
h only integer
data type)
2.
Rellational Operrators
Rela
ational operattors are used to compare tw
wo numbers and
a
taking dec
cisions based on their relatiion.
Rela
ational expres
ssions are use
ed in decision statements su
uch as if, for, while, etc
3.
<
less th
han
<=
=
less th
han or equal to
o
>
greate
er than
>=
=
greate
er than or equal to
==
=
is equa
al to
!=
=
is not equal to
Log
gical Operato
ors
Log
gical operators
s are used to test
t
more than one conditio
on and make decisions
4.
&&
&
||
Ass
signment Op
perators
Ass
signment operrators are used to assign th
he result of an
n expression to
o a variable. C also supportts
sho
orthand assign
nment operato
ors which simp
plify operation
n with assignm
ment
Darshan Insttitute of En
ngineering & Technology
5.
Assign
ns value of rig
ght side to leftt side
+=
a += 1 is same as a = a + 1
-=
=
a -= 1 is same as a = a - 1
*=
=
a *= 1 is same as a = a * 1
/=
=
a /= 1 is same as a = a / 1
%=
%
a %= 1 is same as
sa=a%1
Syllabus
S
for 1st midsem exa
am
Inc
crement and Decrement Operators
The
ese are special operators in C which are g
generally not found in othe
er languages.
++
Increm
ments value by 1.
a++ is
s postfix, the expression is evaluated firs
st and then th
he value is inc
cremented.
Ex. a=
=10; b=a++; after this stattement, a= 11, b = 10.
++a is
s prefix, the value
v
is increm
mented first an
nd then the ex
xpression is evaluated.
e
Ex. a=
=10; b=++a; after this stattement, a= 11, b = 11.
--
Decrements value by
b 1.
a-- is postfix, the ex
xpression is e
evaluated first and then the
e value is decrremented.
Ex. a=
=10; b=a--; after
a
this state
ement, a= 9, b = 10.
--a is prefix, the value is decremented first and then the ex
xpression is ev
valuated.
=10; b=--a; after
a
this state
ement, a= 9, b = 9.
Ex. a=
6.
Con
nditional Ope
erator
A te
ernary operator is known as Conditional Operator.
exp
p1?exp2:exp3 if exp1 is true then executte exp2 otherw
wise exp3
Ex: x = (a>b)?a:b; which is same as
if(a>b)
x=a;
else
e
x=b;
7.
Bitw
wise Operators
Bitw
wise operators
s are used to perform opera
ation bit by biit. Bitwise ope
erators may not be applied to float
or double.
d
8.
&
bitwise
e AND
bitwise
e OR
bitwise
e exclusive OR
R
<<
<
shift le
eft ( shift left means
m
multiply by 2)
>>
>
Spe
ecial Operato
ors
&
Addre
ess operator, it is used to de
etermine addrress of the variable.
Pointe
er operator, it is used to declare pointer variable
v
and tto get value frrom it.
Comm
ma operator. It is used to lin
nk the related
d expressions together.
sizeof
It retu
urns the numb
ber of bytes th
he operand oc
ccupies.
memb
ber selection operator,
o
used
d in structure..
->
>
memb
ber selection operator,
o
used
d in pointer to
o structure.
Explain
n conditionall operator (tternary opera
ator) with ex
xample.
C provides
p
specia
al conditional operator ( ? : ) to evaluate
e conditional e
expression in single line.
Syllabus
S
for 1st midsem exa
am
Darshan Insttitute of En
ngineering & Technology
It is
s also known as ternary op
perator becaus
se this is the only operatorr in C which re
equires three operands
or expressions.
e
Syn
ntax: expr1? expr2 : expr3
Firs
st of all expr1
1 is evaluated
d, if it is nonz
zero (true) th
hen the expre
ession expr2 is evaluated otherwise
exp
pr3 is evaluate
ed. Only one of
o expr2 and e
expr3 is evalu
uated.
Exa
ample: c = a>
>b? a : b; // Iff a is greater tthan b then a is assigned to
o c otherwise b.
What is
s type conve
ersion? Expla
ain implicit a
and explicit type
t
convers
sion with exa
ample.
When an operato
or has operands of differentt types, they are
a converted
d to a common
n type, this is known
as type
t
casting or
o type converrsion.
Typ
pecasting is making
m
a variable of one datta type to act like another d
data type such
h as an int to float.
C automatica
ally converts any
a
intermediate values to the proper ty
ype so that the
e expression can
c
be
evaluated wiithout losing any
a
significanc
ce.
Example:
o
If on
ne operand is int and otherr is float then int will be con
nverted to floa
at.
If on
ne operand is float and othe
er is long double then float will be conve
erted to long double.
d
Thus convers
sion happens from low data
a type to high
h data type so that informattion is not lostt. The
conversion hierarchy
h
is sh
hown below.
long
g double
double
e
float
Conversion
Hierarchy
unsigned
d long int
long int
unsigned int
int
shortt
char
Sometimes we
w want to forrce a type con
nversion in a way
w
that is diffferent from automatic
a
conv
version.
The process of such a loca
al conversion or casting is known
k
as expllicit casting.
(type--name) expre
ession.
an expressio
on.
Example:
#include<std
dio.h>
#include<co
onio.h>
Syllabus
S
for 1st midsem exa
am
Darshan Insttitute of En
ngineering & Technology
void main()
{
int sum=47,
s
n=10;
floatt avg;
avg=
=sum / n;
// implicit ty
ype casting
printtf(Result of Implicit
I
Type Casting:
C
%f, avg);
avg=
=(float)sum / (float)n;
// explicit ty
ype casting
printtf(Result of Explicit
E
Type C
Casting: %f, avg);
}
10
Explain
n operator prrecedence and associativ
vity.
Precedence of an
n operator is itts priority in an
a expression for evaluation
n.
Ope
erator precede
ence is why th
he expression 5 + 3 * 2 is calculated
c
as 5 + (3 * 2), giving
g
11, and
d not as
(5 + 3) * 2, givin
ng 16.
We say that the multiplication operator (*) has higher "p
precedence" or "priority" tha
an the additio
on
ope
erator (+), so the multiplica
ation must be performed firrst.
Ass
sociativity is th
he left-to-righ
ht or right-to-left order for grouping
g
operrands to opera
ators that hav
ve the
sam
me precedence
e.
Ope
erator associa
ativity is why the
t
expression
n 8 - 3 - 2 is calculated
c
as ((8 - 3) - 2, giv
ving 3, and an
nd not as
8 - (3 - 2), giving
g 7.
We say that the subtraction op
perator (-) is "left associative", so the left subtraction must be perfformed
firstt. When we ca
an't decide by
y operator pre
ecedence alone
e in which ord
der to calculatte an expression, we
must use associa
ativity.
As
ssociativity
Operattor
Des
scription
Lefft to Right
()
Func
ction Call
[]
Arra
ay Element Re
eference
+, -
++, --
Increment, Decre
ement
Logical Negation
Ones Complemen
nt
Poin
nter Reference
e (Indirection)
&
Address
sizeof
Size
e of an object
(type)
Type
e Cast (Conve
ersion)
Multtiplication
Divis
sion
Modulus
Addition
Subttraction
<<
Left Shift
>>
Righ
ht Shift
<
Less
s than
Rig
ght to Left
Lefft to Right
Lefft to Right
Lefft to Right
Lefft to Right
Darshan Insttitute of En
ngineering & Technology
<=
Less
s than or equa
al to
>
Grea
ater than
>=
Grea
ater than or equal to
==
Equa
ality
Lefft to Right
!=
Ineq
quality
Lefft to Right
&
Bitw
wise AND
Lefft to Right
Bitw
wise XOR
10
Lefft to Right
Bitw
wise OR
11
Lefft to Right
&&
Logical AND
12
Lefft to Right
||
Logical OR
13
Rig
ght to Left
?:
Cond
ditional Expre
ession
14
Rig
ght to Left
ators
Assignment Opera
Syllabus
S
for 1st midsem exa
am
%=, +=
=, -=,
&=, ^=
=, |=,
<<=, >
>>=
15
11
Lefft to Right
Com
mma Operator
Explain
n backslash and
a
trigraph
h characters.
Backsla
ash characte
er:
Back sla
ash constants are a special type of chara
acter constantt which are co
onsists of two characters. Th
his is
known as
a escape seq
quence. Escap
pe sequence sttarts with bac
ckslash \ charracter.
Escape sequence
M
Meaning
\0
\n
\r
\f
Form
m feed- takes
s control to the
e next page.
\t
Horizontal tab
\b
Back space
\\
Prin
nts backslash c
character \
\a
Alerrt provide ed
dible alert.
Trigrap
ph characterr:C introd
duces conceptt of trigraph sequence to provide a way
y to enter certtain characterrs which are not
availablle in some key
yboard of non
n English langu
uage. Each trigraph charactter consists off a three characters.
T
Trigraph
seque
ence
Trranslation
??=
# number
n
sign
??(
[ le
eft bracket
??)
] right bracket
??<
{ left bracket
??<
} right bracket
??!
| vertical
v
bar
??/
\ backslash
Darshan Insttitute of En
ngineering & Technology
Syllabus
S
for 1st midsem exa
am
Expla
ain if with ex
xample and draw
d
flowchart.
Itt evaluates ex
xpression firstt and based on
n its result, th
he control is trransferred to the
t
particular statement.
T
The
general form of simple if
i statement is
s
if (test
t expression
n)
{
tatement-bl
lock
st
}
nt-x
statemen
b
block
will be skipped
s
and the execution will jump to th
he statement
t-x.
Flowc
chart:
Entry
T
Test
Exprression?
False
True
Sttatement-bloc
ck
State
ement-x
Next-s
statement
mple:
Exam
#include<
<stdio.h>
void main
n()
{
nt no;
in
pr
rintf("Enter
r the numbe
er:");
sc
canf("%d", &no);
&
if
f(no%2==0)
f("no is ev
ven");
printf
f(no%2!=0)
if
f("no is od
dd");
printf
}
Syllabus
S
for 1st midsem exa
am
Darshan Insttitute of En
ngineering & Technology
Expla
ain ifelse
with examp
ple and draw
w flowchart.
The general
g
formatt is given belo
ow.
if(test-exp
i
pression)
{
-block stat
tement.
True}
e
else
{
e-block sta
atement
False
}
s
statement-x
x;
Iff test-expre
ession is true
e, then true-b
block state
ement is execu
uted otherwise false-bloc
ck
statement is executed.
E
Every
time, eitther true block
k or false bloc
ck will be exec
cuted.
In
n both the cas
ses, statemen
nt-x will be e
executed immediately after that block.
Flowc
chart:
Entry
y
False
True
Test
sion?
Express
False block
T
True-block
Stateme
ent-x
Next statement
Exam
mple: Check whether the giv
ven number is
s even or odd..
#include<
<stdio.h>
void main
n()
{
nt no;
in
pr
rintf("Enter
r the numbe
er:");
sc
canf("%d", &no);
&
if
f(no%2==0)
f("the number is even"
");
printf
lse
el
f("the number is odd");
printf
}
2
Syllabus
S
for 1st midsem exa
am
Darshan Insttitute of En
ngineering & Technology
Expla
ain ifelse....if ladder witth example a
and draw flo
owchart.
n multipath de
ecisions are involved, we may use ifelse
eif ladder, which
w
takes the
e following ge
eneral form.
When
if
f(condition-1)
statem
ment-1;
el
lse if(cond
dition-2)
statem
ment-2;
el
lse if(cond
dition-N)
statem
ment-N;
el
lse
defaul
ltstatemen
nt;
tatement-x
st
F
First
conditio
on-1 is checke
ed and if it is true, then statement-1 will
w be execute
ed and control goes to
statement-x.
T
This
process is
s repeated unttil either it find
ds one of the conditions is true or all the
e conditions arre false. If all
th
he conditions are false, the
en default-statement willl be executed
d.
E
Else
part is opttional in ifels
seif ladder.
Flowc
chart:
True
Stattement-1
Entry
Test
Conditio
on
1
True
F
False
Test
Condition
2
Stateme
ent-2
True
e
Statement-3
False
T
Test
Con
ndition
3
True
False
Test
Condition
n
N
Fa
alse
State
ement-N
Default
statemen
nt
Statemen
nt-x
Darshan Insttitute of En
ngineering & Technology
Syllabus
S
for 1st midsem exa
am
Exam
mple: Find the class of stude
ent based on a
average mark
ks.
#include<
<stdio.h>
void main
n()
{
nt m1,m2,m3,
,m4,m5;
in
fl
loat avg;
pr
rintf("Enter
r m1,m2,m3,m4,m5:");
sc
canf("%d%d%d
d%d%d", &m1
1, &m2, &m3,
, &m4, &m5);
av
vg=(m1+m2+m3
3+m4+m5)/5;
;
if
f(avg>=70)
f(Distinct);
printf
lse if(avg>=
=60)
el
printf
f("First class");
lse if(avg>=
=50)
el
printf
f("Second class");
lse if(avg>=
=40)
el
printf
f("Pass class");
lse
el
f("fail");
printf
}
4
Expla
ain nested if with examp
ple and draw
w flowchart.
n a series of decisions are in
nvolved, we m
may have to use more than one ifelse statement
s
in nested
n
form
When
as shown below.
if
f(test-cond
dition-1)
{
if(t
test-conditi
ion-2)
{
Statement-1;
}
e
else
{
Statement-2;
}
}
lse
el
{
ment-3;
Statem
}
tatement-x
St
Iff test-conditio
on-1 is true then test-condition-2 is evalu
uated. If it is ttrue then Stattement-1 will be executed,
iff it is false the
en Statement--2 will be exec
cuted.
Iff test-conditio
on-1 is false th
hen Statemen
nt-3 will be executed.
Syllabus
S
for 1st midsem exa
am
Darshan Insttitute of En
ngineering & Technology
Entry
Flowc
chart:
False
Sttatement-3
T
Test
Cond
dition 1?
True
Te
est
Condittion 2?
False
True
Statem
ment-1
Statem
ment-x
Next sta
atement
Exam
mple: Find max
ximum numbe
er from given three numberrs.
#include<
<stdio.h>
void main
n()
{
in
nt a,b,c;
pr
rintf("Enter
r value of a, b, c:");
;
sc
canf("%d%d%d
d", &a, &b, &c);
if
f(a>b)
{
if(a>c
c)
printf("a is max");
else
printf("c is max");
}
el
lse
{
if(b>c
c)
printf("b is max");
else
printf("c is max");
}
}
S
Statement-2
Darshan Insttitute of En
ngineering & Technology
Syllabus
S
for 1st midsem exa
am
Expla
ain switch-ca
ase statement with exam
mple.
T
The
switch stattement is a multi-way
m
decis
sion making.
G
General
form of
o switch-case
e is as below,
switch(ex
xpression)
{
ase const-ex
xpr 1:
ca
sta
atement 1;
bre
eak;
ase const-ex
xpr 2:
ca
sta
atement 2;
bre
eak;
ase const-ex
xpr 3:
ca
sta
atement 3;
bre
eak;
efault:
de
ments
statem
}
e
expression
in switch
s
should be integer or character exp
pression. Float or any otherr data type is not allowed.
E
Each
case is la
abeled by one or more integ
ger-valued con
nstant.
V
Value
of all cas
se expressions must be diffferent.
T
The
break stattement causes
s an immediatte exit from th
he switch.
mple:
Exam
switch (g
grade)
{
ca
ase 1:
printf
f("Fall (F)\n");
break;
;
ca
ase 2:
printf
f("Bad (D)\n");
break;
;
ca
ase 3:
printf
f("Good (C)\n");
break;
;
ca
ase 4:
printf
f("Very Good (B)\n");
break;
;
ca
ase 5:
printf
f("Excellent (A)\n");
break;
;
de
efault:
printf
f("You have inputted false
f
grade\
\n");
break;
;
// break isnt
t necessary here
}
Darshan Insttitute of En
ngineering & Technology
Syllabus
S
for 1st midsem exa
am
Rules
s for switch sta
atement
The switch
h expression must
m
be integrral type. Floatt or other data
a types are no
ot allowed.
switch
h
If statement is used
u
to selectt among two
The
e switch statem
ment is used to
t select among
altternatives.
mulltiple alternatiives.
If implements Linear
L
search.
Swiitch implemen
nts Binary search.
Flo
oat, double, char, int and other data type
es can
be
e used in if con
ndition.
bloc
ck.
Write a C Pr
rogram to.
1
#incl
lude<stdio.h>
void main()
{
int no;
enter no:");
printf("e
scanf("%d
d",&no);
if(no%2==
=0)
pr
rintf("no is
s even");
else
rintf("no is
s odd");
pr
}
2
mbers.
Find maximum number from given 3 num
#incl
lude<stdio.h>
void main()
{
c;
int a,b,c
printf("e
enter a,b,c
c:");
scanf("%d
d%d%d",&a,&
&b,&c);
7
Darshan Insttitute of En
ngineering & Technology
Syllabus
S
for 1st midsem exa
am
if(a>b&&a
a>c)
pr
rintf("a is maximum");
;
else if(b
b>c)
pr
rintf("b is maximum");
;
else
rintf("c is maximum");
;
pr
}
3
n
and prints
p
corres
sponding day
y name using
g switch-cas
se.
which asks day number
#incl
lude<stdio.h>
void main()
{
int day;
enter day number
n
(1-7)
) \n");
printf("e
scanf("%d
d",&day);
switch(da
ay)
{
ase 1:
ca
f("sunday");
printf
break;
;
ase 2:
ca
f("monday");
printf
break;
;
ase 3:
ca
f("tuesday");
printf
break;
;
ase 4:
ca
f("wednesday");
printf
break;
;
ase 5:
ca
f("thursday
y");
printf
break;
;
ase 6:
ca
f("friday");
printf
break;
;
ase 7:
ca
f("saturday
y");
printf
break;
;
efault:
de
f("wrong input");
printf
}
}
During looping, a set of statements are executed until some condition for termination is encountered.
Initialization of a counter
2)
3)
4)
Initialization;
while (test condition)
{
body of the loop ;
increment or decrement;
}
Test condition is evaluated and if the condition is true then the body of the loop is executed.
After the execution of the body, the test condition is once again evaluated and if it is true, the body
is executed once again.
This process is repeated till the test condition is true. When it becomes false, the control is
transferred out of the loop.
On exit, the program continues with the statements immediately after the body of the loop.
While loop is also known as entry control loop because first control-statement is executed and if it is true
then only body of the loop will be executed.
dowhile loop
In contrast to while loop, the body of the dowhile loop is executed first and then the loop condition is
checked.
The body of the loop is executed at least once because dowhile loop tests condition at the bottom of
the loop after executing the body.
dowhile loop is also known as exit control loop because first body statements are executed and then
initialization;
do
{
statement;
increment or decrement;
}
while(test-condition);
Example: To print first 10 positive integer numbers
void main()
{
int i;
i = 1;
\\ initialization of i
do
{
printf(\t%d,i);
\\ statement execution
i++;
\\ increment of control variable
} while(i <= 10);
\\ condition checking
}
for Loop
When the control enters for loop, the variables used in for loop is initialized with the starting value such
Then it is checked with the given test condition. If the given condition is satisfied, the control enters into
After the completion of the execution of the loop, the control is transferred back to the increment part of
If new value of the control variable satisfies the loop condition then the body of the loop is again
For loop is also entry control loop because first control-statement is executed and if it is true then only
executed. This process goes on till the control variable fails to satisfy the condition.
body of the loop will be executed.
//declare variable
// for loop
// add the value of i and store it to sum
We can include multiple expressions in any of the fields of for loop provided that we separate such
expressions by commas. For example: for( i = 0; j = 100; i < 10 && j>50; i++, j=j-10)
for Loop
while Loop
dowhile Loop
i=1;
while(i<=10)
{
sum = sum + i;
i ++;
}
i=1;
do
{
sum = sum + i;
i ++;
} while(i<=10);
State the difference between entry control loop and exit control loop.
For example, consider searching a particular number in a set of 100 numbers, as soon as the search
A break statement provides an early exit from for, while, dowhile and switch constructs.
float sum=0,average;
printf(Input the marks, -1 to end\n);
while(1)
{
scanf(%d,&i);
if(i==-1)
break;
sum+=i;
}
printf(%d, sum);
}
continue;
The continue statement can be used to skip the rest of the body of an iterative loop.
The continue statement tells the compiler, SKIP THE FOLLOWING STATEMENTS AND CONTINUE WITH
THE NEXT ITERATION.
Example: Find sum of 5 positive integers. If a negative number is entered then skip it.
void main()
{
int i=1, num, sum=0;
for (i = 0; i < 5; i++)
{
scanf(%d, &num);
if(num < 0)
continue;
// starts with the beginning of the loop
sum+=num;
}
printf(The sum of positive numbers entered = %d,sum);
}
goto:
The goto statement is a jump statement which jumps from one point to another point within a function.
The goto statement is marked by label statement. Label statement can be used anywhere in the function
above or below the goto statement.
Generally goto should be avoided because its usage results in less efficient code, complicated logic and
difficult to debug.
Dars
shan Instittute of Eng
gineering & Technology
Sy
yllabus for 1st midsem exam
m
Compute
er Programm
ming and Uttilization (CP
PU) 11000
03
F)
) Array and String
What is
s an array? Explain
E
with Example. What
W
are the advantages of using an array?
An array is a fixe
ed-size sequen
nced collection
n of elements
s of the same data type.
The
e individual ele
ement of an array
a
is referre
ed by their ind
dex or subscriipt value.
The
e subscript forr an array alw
ways begins wiith 0.
Syntax :
data
a_type arra
ay_name[size
e];
Example :
int marks[5];
The
e data_type sp
pecifies the ty
ype of the elem
ments that can be stored in
n an array, like
e int, float or char.
The
e size indicate
es the maximu
um number off elements tha
at can be store
ed inside the array.
a
In the
t
example, data type of an
a array is intt and maximum elements th
hat can be sto
ored in an arra
ay are 5.
Advanttages:
You
u can use one name to storre many value
es with different indexes.
Examp
ple:
#include<s
stdio.h>
void main()
{
int a[5] = {5,12,20,54,68
8}, i;
(i=0;i<5;i+
++)
for(
{
printf(
%d, a[i]);
}
}
Types of
o an array:
1)
Single dimension
nal array
2)
Two
o dimensional array
3)
Mullti dimensiona
al array
Sy
yllabus for 1st midsem exam
m
Dars
shan Instittute of Eng
gineering & Technology
Explain
n initializatio
on and workiing of single
e and multi-d
dimensional array
a
with example.
Single Dimensional Array
An array using only one
o
subscript to represent the
t
list of elem
ments is called
d single dimen
nsional array.
Syntax :
data
a_type arra
ay_name[size
e];
Example :
int marks[5];
generally
if
is
de
eclared
to
b
be
an
integ
ger
variable,
then the
s
statement
g=m
marks[i];
We can store value into array element by specifying the array element on the left hand
h
side of th
he equals
sign
n like marks[6
60]=95; The value
v
95 is sto
ored at 60th position in an array.
a
The
e ability to rep
present a colle
ection of relatted data items
s by a single array
a
enables
s us to develop concise
and
d efficient prog
grams.
The
e declaration int values[5]; would re
eserve enough
h space for an
n array called values that could hold
up to 5 integers. Refer to the below given picture
p
to conc
ceptualize the
e reserved storage space.
values[0]]
values[1]]
values[2]]
values[3]]
values[4]]
int
t number[3]=
={1, 5, 2};
will initialize 0th element
e
of an array to 1, 1st element to 5 and 2nd elem
ment to 2.
2.
int
t number[5] = {1, 7};
will initialize 0th element
e
of an array to 1, 1st element to 7 and rest all elements will be initialized to 0.
3.
int
t number[ ] ={1, 5, 6};
first of all array size
s
will be fix
xed to 3 then it will initialize
e 0th element to 1, 1st element to 5 and 2nd
ment to 6
elem
Sy
yllabus for 1st midsem exam
m
Dars
shan Instittute of Eng
gineering & Technology
Two
o dimensional arrays are also called table
e or matrix.
Two
o dimensional arrays have two
t
subscripts
s.
Firs
st subscript de
enotes the num
mber of rows and second subscript deno
otes the number of columns
s.
Syntax :
data
a_type arra
ay_name[row_
_size][colu
umn_size];
Example :
int marks[10][20];
A tw
wo dimensional array mark
ks[4][3] is sho
own below. Th
he first element is given by
y marks[0][0] contains
thro
ough 19). The
e first elementt of the matrix
x is m[0][0] and
a
the last ro
ow last column
n is m[9][19]
35.5 & second ellement is marrks[0][1] and contains 40.5
5 and so on.
marrks [0][0]
marks
s [0][1]
marks [0]][2]
35.5
5
40.5
45.5
marrks [1][0]
marks
s [1][1]
marks [1]][2]
66.5
5
55.5
60.5
marrks [2][0]
marks
s [2][1]
marks [2]][2]
85.5
5
78.5
65.3
marrks [3][0]
marks
s [3][1]
marks [3]][2]
25.6
6
35.2
76.2
int
t table[2][3
3] = {1,2,3
3,4,5,6};
will initialize 1st row
r
1st column
n element to 1,
1 1st row 2nd column to 2, 1st row 3rd collumn to 3, 2ndd row 3rd
umn to 6 and so on.
colu
2.
int
t table[2][3
3] = {{1,2,3},{4,5,6})
);
s
herre, 1st group is
s for 1st row and 2nd group is for 2nd row.. So 1st row 1st
column elem
ment is 1, 2nd row 1st
colu
umn element is 4, 2nd row 3rd column ele
ement is 6 so on.
3.
int
t table[2][3
3] ={{1,2},{4}}
initializes as above but missing elements will be initialize
ed by 0.
Explain
n various str
ring handling
g operations available in C with exa
ample.
C has several inbuilt functions to operate
o
on strring. These fun
nctions are kn
nown as string
g handling fun
nctions.
For Example: char s1
1[]=Their, s2[]=There;
Functtion
strlen((s1)
M
Meaning
Returns len
ngth of the strring.
l = strlen(s
s1); it returns 5
strcmp
p(s1,s2)
Compares two
t
strings.
It returns negative
n
value
e if s1<s2, positive if s1>s2
2 and zero if s1=s2.
s
Dars
shan Instittute of Eng
gineering & Technology
Sy
yllabus for 1st midsem exam
m
printf(%d, strcmp(s1,s
s2));
Output : -9
9
strcpy
y(s1,s2)
strcat((s1,s2)
n
Appends 2nd
string at the
e end of 1st sttring.
strcat(s1,s2
2); a copy off string s2 is appended att the end of string
s
s1. Now
w s1
becomes T
TheirThere
strchr((s1,c)
Returns a pointer
p
to the first occurren
nce of a given character in the
t
string s1.
printf(%s,strchr(s1,i));
Output : ir
strstr((s1,s2)
Returns a pointer
p
to the first occurren
nce of a given string s2 in string
s
s1.
printf(%s,strstr(s1,he
e));
Output : he
eir
strrev(s1)
strlwr((s1)
printf(%s, strlwr(s1));
strupr(s1)
strncp
py(s1,s2,n)
Outp
put : THEIR
strncat(s1,s2,n)
strncm
mp(s1,s2,n)
strrchrr(s1,c)
Returns the
e last occurrence of a given
n character in a string s1.
printf(%s,strrchr(s2,e));
Output : erre
Darshan Insttitute of En
ngineering & Technology
S
Syllabus
for 1st midsem exa
am
Compute
er Programm
ming and Uttilization (CP
PU) 11000
03
G) Functio
ons
Th
he functions which
w
are crea
ated by progra
ammer are called user-defined functions.
Th
he functions which
w
are in-b
built in compile
er are known as system fun
nctions.
Th
he functions which
w
are implemented in header
h
librarie
es are known as
a library func
ctions.
Pa
arameter or argument pass
sing to functio
on is optional.
Function Declaration
Like va
ariables, all th
he functions must
m
be declarred before the
ey are used.
1)
Function ty
ype (return ty
ype).
2)
Function name.
3)
Parameter list.
4)
Terminatin
ng semicolon
Syntax
x:
<retur
rn type> Fun
nctionName (Argument1,
, Argument2,
, Argument3
3);
Exampl
le:
int su
um(int , int
t);
2.
3
3.
Function Definition
Functio
on Definition is
i also called function
f
imple
ementation.
Function body
Function call
c
Functio
on is invoked from main fun
nction or othe
er function tha
at is known as
s function call..
Functio
on can be callled by simply
y using a fun
nction name followed by a list of actual argument
enclose
ed in parenthe
eses.
Darshan Insttitute of En
ngineering & Technology
S
Syllabus
for 1st midsem exa
am
<return type>
t
Functi
ionName (Ar
rgument1, Ar
rgument2, Argument3)
A
)
{
St
tatement1;
St
tatement2;
St
tatement3;
}
An example of func
ction
#include<
<stdio.h>
int sum(i
int, int);
\ Function
\\
n Declaratio
on or Signature
void main
n()
{
in
nt a, b, ans
s;
sc
canf(%d%d,
, &a, &b);
an
ns = sum(a, b);
\ Function
\\
n Calling
pr
rintf(Answe
er = %d, ans);
}
int sum (int
(
x, int y)
\ Function
\\
n Definition
n
{
nt result;
in
re
esult = x + y;
re
eturn (resul
lt);
}
2
Fu
unctions with no arguments
s and no returrn value
\ void printlin
\\
ne(void)
2.
Fu
unctions with no arguments
s and return a value
\ int printline
\\
e(void)
3.
Fu
unctions with arguments an
nd no return value
v
\ void printlin
\\
ne(int a)
4.
Fu
unctions with arguments an
nd one return value
\ int printline
\\
e(int a)
5.
Fu
unctions that return multiple values using pointer
\ void printlin
\\
ne(int a)
1.
Fu
unction with no
n argument and
a
no return value.
When a fun
nction has no argument, it does not rece
eive any data from calling fu
unction.
When it do
oes not return a value, the calling
c
functio
on does not re
eceive any datta from the ca
alled
function.
S
Syllabus
for 1st midsem exa
am
Darshan Insttitute of En
ngineering & Technology
Examp
ple:
#include<
<stdio.h>
void prin
ntline(void)
);
// No argument
t No retur
rn value
void main
n()
{
cl
lrscr();
pr
rintline();
void main()
{
Fun
n1()
pr
rintf("\n GT
TU \n");
}
void prin
ntline(void)
)
{
in
nt i;
fo
or(i=0;i<10;
;i++)
void Fun1
1()
{
No
Input
No
Output
{
printf
f("-");
}
}
2.
Fu
unction with no
n arguments and return a value
When a fun
nction has no argument, it does not rece
eive data from
m calling functiion.
When a fun
nction has return value, the
e calling functtion receives one
o
data from the called fun
nction.
Examp
ple:
#include<
<stdio.h>
int get_n
number(void)
);
// No argument
a
void main
n()
{
nt m;
in
m=
=get_number(
();
pr
rintf("%d",m
m);
}
int get_n
number(void)
)
{
void main
n()
{
a = Fun1
1()
nt number;
in
No
Input
int Fun1()
{
return no;
}
Function
result
pr
rintf("enter
r number:");
sc
canf("%d",&n
number);
re
eturn number
r;
// Retu
urn value
}
3.
Fu
unction with arguments
a
and
d no return va
alues
When a fun
nction has arg
gument, it receives data fro
om calling func
ction.
When it do
oes not return a value, the calling
c
functio
on does not re
eceive any datta from the ca
alled
function.
Ex
xample:
3
S
Syllabus
for 1st midsem exa
am
Darshan Insttitute of En
ngineering & Technology
#include<
<stdio.h>
#include<
<conio.h>
void sum(
(int,int);
// Argument
void main
n()
{
in
nt no1,no2;
pr
rintf("enter
r no1,no2:");
sc
canf("%d%d",
,&no1,&no2);
su
um(no1,no2);
;
}
void sum(
(int no1,int
t no2)
{
void main()
{
Fun1
1(a)
f(no1>no2)
if
Value of
argument
void Fun
n1(int a)
{
No return
n
value
printf
f("\n no1 is
s gretest");
el
lse
printf
f("\n no2 is
s gretest");
}
4.
//
/ No return value
Fu
unction with arguments
a
and
d one return value
v
When a fun
nction has arg
gument, it receives data fro
om calling func
ction.
When a fun
nction has return value, the
e calling functtion receives any
a
data from the called fun
nction.
Example:
#include<
<stdio.h>
#include<
<conio.h>
int sum(i
int);
// Argumen
nt
void main
n()
{
in
nt no,x;
cl
lrscr();
pr
rintf("enter
r no:");
sc
canf("%d",&n
no);
x=
=sum(no);
pr
rintf("sum=%
%d",x);
ge
etch();
}
void main())
{
a)
b = Fun1(a
int no)
int sum(i
{
in
nt add=0,i;
wh
hile(no>0)
{
i=no%1
10;
4
Value of
gument
arg
Fu
unction
r
result
in
nt fun2(f)
{
re
eturn(e)
}
Darshan Insttitute of En
ngineering & Technology
S
Syllabus
for 1st midsem exa
am
add=ad
dd+i;
no=no/
/10;
}
re
eturn add;
// Retu
urn value
}
5.
Fu
unction that returns a multiple value
Function ca
an return either one value or
o zero value. It cannot retturn more than one value
So function
n should be ca
alled with refe
erence not with value
Examp
ple:
#i
include<std
dio.h>
vo
oid mathope
eration(int x, int y, int *s, int
t *d);
vo
oid main()
{
int x=20,
,y=10,s,d;
mathopera
ation(x,y,&s
s,&d);
printf("s
s=%d \nd=%d"
", s,d);
}
vo
oid mathope
eration(int a, int b, int *sum, int
i
*diff)
{
*sum = a + b;
*diff = a - b;
}
3
Expla
ain actual arg
gument and formal argument with example.
Arguments pas
ssed to the fun
nction during function callin
ng are called actual
a
argume
ents or parameters.
Arguments rece
eived in the definition of a function are called
c
formal arguments
a
or parameters.
Examp
ple:
#include<
<stdio.h>
int max(i
int , int )
// Functi
ion Declarat
tion.
void main
n()
{
in
nt a=5,b=3, ans;
an
ns=max(a, b)
);
//a an
nd b are act
tual argumen
nts.
pr
rintf("max=%
%d", ans);
}
int x, int y)
y
int max(i
// x and y are
e formal arg
guments.
{
if
f(x>y)
n x;
return
5
Darshan Insttitute of En
ngineering & Technology
S
Syllabus
for 1st midsem exa
am
el
lse
return
n y;
}
4
Expla
ain call by va
alue (pass by
y value) and call by referrence (pass by
b reference
e) with exam
mple.
The parameters can
n be passed in
n two ways du
uring function calling,
Call by value
Call by referenc
ce
b value
Call by
In
n call by value
e, the values of
o actual parameters are co
opied to their corresponding
g formal param
meters.
So
o the original values of the variables of calling
c
function remain unchanged.
Ev
ven if a functtion tries to change
c
the value
v
of passe
ed parameter, those chang
ges will occurr in formal
pa
arameter, nott in actual parrameter.
Examp
ple:
#incl
lude<stdio.h
h>
void swap(int, int);
i
void main()
{
int x, y;
;
printf("E
Enter the va
alue of X & Y:");
scanf("%d
d%d", &x, &y
y);
swap(x, y);
y
printf(\
\n Values in
nside the main
m
functio
on);
printf(\
\n x=%d, y=%
%d, x, y);
;
getch();
}
void swap(int x,
,int y)
{
int temp;
;
temp=x;
x=y;
y=temp;
printf(\
\n Values in
nside the swap
s
functio
on);
printf("\
\n x=%d y=%d
d", x, y);
}
Outpu
ut:
Enter the value of X & Y: 3 5
Values
s inside the sw
wap function
X=5 y=3
y
Darshan Insttitute of En
ngineering & Technology
S
Syllabus
for 1st midsem exa
am
Values
s inside the main
m
function
X=3 y=5
y
Call by
b Reference
e
In
n call by refe
erence, the address
a
of the
e actual para
ameters is pa
assed as an argument to the called
fu
unction.
So
o the original content of the
e calling functtion can be ch
hanged.
Call by referenc
ce is used whenever we wa
ant to change the value of local variables
s through func
ction.
Example:
#include<
<stdio.h>
void swap
p(int *, int
t *);
void main
n()
{
in
nt x,y;
pr
rintf("Enter
r the value of X & Y:
sc
canf("%d%d",
, &x, &y);
sw
wap(&x, &y);
;
pr
rintf(\n Va
alue inside the main function);
f
pr
rintf("\n x=
=%d y=%d", x, y);
}
void swap
p(int *x, in
nt *y)
{
in
nt temp;
te
emp=*x;
*x
x=*y;
*y
y=temp;
pr
rintf(\n Va
alue inside the swap function);
f
pr
rintf("\n x=
=%d y=%d", x, y);
}
Outpu
ut:
Enter the value of X & Y: 3 5
Value inside the sw
wap function
X=5 y=3
y
Value inside the ma
ain function
X=5 y=3
y
Differe
ence between
n two program
m is marked as
s bold in call by
b reference program
p
4
Darshan Insttitute of En
ngineering & Technology
S
Syllabus
for 1st midsem exa
am
If a functio
on calls itself then it is know
wn as recursio
on.
Suppose we
w want to calculate the fac
ctorial of a giv
ven number th
hen in terms of
o recursion we
w can
write it as n! = n * (n
n-1)!. First we
w have to fin
nd (n-1)! and
d then multiply it by n. the (n-1)! is
computed as (n-1)! = (n-1) * (n
n-2)!. This process end wh
hen finally we need to calcu
ulate
1!.which is
s 1.
Ex: 4! =4*
*3!
=4
4*3*2!
=4
4*3*2*1!
=4
4*3*2*1
Pictorial presentatio
on of recursion.
fact(4)
f=1;
if(..)
..;
f=4*fac
ct(3)
2
return 24;
fact(3)
f=1;
if(..)
..;
f=3*factt(2)
return 6;
6
fact(2)
f=1;
if(..)
..;
f=2*factt(1)
return 2;
fact(1)
f=1;
if(..)
..
return 1;
Tracing of function fa
act() for n=4
Darshan Insttitute of En
ngineering & Technology
S
Syllabus
for 1st midsem exa
am
#include<
<stdio.h>
#include<
<conio.h>
int fact(
(int);
void main
n()
{
in
nt f,n;
pr
rintf("enter
r number:");
sc
canf("%d",&n
n);
f=
=fact(n);
pr
rintf("\n fa
actorial=%d
d",f);
}
int fact(
(int n)
{
in
nt f=1;
if
f(n==1)
{
return
n 1;
}
lse
el
{
f=n*fa
act(n-1);
return
n f;
}
}
ntages
Advan
Disadv
vantages
Recursive code
c
is difficult to understand and debug
g.
Execution speed
s
decreas
ses because of
o function calll and return activity many times.
t
Local varia
ables which arre declared in
nside the body
y of function cannot
c
be acc
cessed outside
e the body
of function.
Darshan Insttitute of En
ngineering & Technology
S
Syllabus
for 1st midsem exa
am
Global varriables which are declared outside any function deffinition can be
b accessible by all the
function in a program.
Lifetim
me
d
the program executio
on until which
h a variable ex
xist in a memo
ory.
Lifetime is a time limit during
It is also re
eferred to the longevity of variable.
v
Visibility
10
2nd Mids
sem Syllabu
us
A pointer is
s a variable that contains address or lo
ocation of ano
other variable
e.
Pointer is a derived data
a type in C.
Pointers co
ontain memo
ory address as their va
alues, so the
ey can also be used to
o access and
d
manipulate
e data stored in memory.
void main()
{
int a=10, *p;
p = &a;
\\ As
ssign memory
y address of a to pointer variable
v
p
prin
ntf(%d %d %d,
%
a, *p, p);
p
}
Output: 10
0 10 5000
& is address of or re
* is ind
direction or de
ereferencing operator which returns va
alue stored at
a that memo
ory address
& opera
ator is the inv
verse of * op
perator ( x = a is same as
s x = *(&a))
Variable
Address
Valu
ue
10
5000
5000
5048
Declaration of po
ointer,
Syntax:
data_type *pt_name
e;
Example:
int *p, float
f
*q, charr *c;
1) The astterisk (*) tellls that the va
ariable pt_nam
me is a pointter variable
2) pt_nam
me needs a memory
m
locatiion to store address
a
of another variablle
3) pt_nam
me points to a variable of type data_ty
ype
Initialization of the pointer,
int a=5, x, *p; // Decla
ares pointer variable
v
p and
d regular varriable a and x
p = &a
// Initializes p with address
a
of a
x = *p;
// p con
ntains address of a and *p
p gives value stored at tha
at address.
2nd Mids
sem Syllabu
us
How pointer
p
is diifferent from
m array?
Array
Pointer
Poin
nter variable can
c
be chang
ged.
It refers
r
directly
y to the elements.
It re
efers address of the variab
ble.
Mem
mory allocation is in sequence.
Mem
mory allocatio
on is random..
Allo
ocates the me
emory space which canno
ot
resize or reassig
gned.
Alloc
cated memorry size can be
e resized.
It is
s a group of elements.
e
Discu
uss relation
nship betw
ween array and pointe
er.
int a[10], *p;
*
Array name
e is constant pointer so a is constant pointer
p
and itt always points to the firstt element of
an array.
a[0] is sam
me as *(a+0), a[2] is same as *(a+2), a[i] is same
e as *(a+i)
So every program writte
en using arra
ay can always
s be written using
u
pointerr.
a:
a[0]
a:
*(a+0)
2000
a[1]
a+1:
*(a+1)
2002
.
.
.
.
.
.
.
.
a[i]
a+i:
2000+i*2
2
.
.
.
.
.
.
a[9]
*(a+i)
a+9:
*(a+9)
2018
sem Syllabu
us
2nd Mids
x :
Syntax
data_type *name[size];;
Examp
ple :
int *ptr[5];;
p
;
\\ Can be re-written as ptr[i]=mat[i];
}
ptr
ptr[0]
ptr[1]
ptr[2]
ptr[3]
ptr[4]
By using dynamic memory
m
alloc
cation, we do
o not require to declare tw
wo-dimensional array, it ca
an be created
d
dynam
mically using array
a
of pointers.
5
Swap value of tw
wo variables using pointter. OR
Swap value of tw
wo variables using call by
b reference
e
#include<stdio.h>
wap(int *,int *);
void sw
void main()
m
{
int a,b;
printf("Ente
er two numbe
ers:");
scanf("%d%
%d", &a, &b));
swap(&a, &b);
&
printf("a=%
%d b=%d", a,
a b);
getch();
}
void sw
wap(int *a, in
nt *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
2nd Mids
sem Syllabu
us
Write a C program
m to calcula
ate sum of 10
1 elements
s of an array
y using pointers
#include<stdio.h>
#include<conio.h>
>
void main()
m
{
int *p, a[10
0], sum=0, i;
p=a;
printf("Ente
er elements:"");
for(i=0; i<10; i++)
{
sca
anf("%d", &a[i]);
}
for(i=0; i<10; i++)
{
sum
m=sum+*p;
p++;
}
printf("sum
m=%d", sum));
getch();
}
What is structure
e? How to de
eclare a Strructure? Exp
plain with Ex
xample
Structure is
i a collection
n of logically related data items of diffe
erent data types grouped together
under a sin
ngle name.
Structure is
i a user defined data type.
Structure helps
h
to orga
anize complex
x data in a more meaningful way.
x of Structure
e:
Syntax
struct struc
cture_name
{
datta_type mem
mber1;
datta_type mem
mber2;
.
};
struct is a keyword.
structure_
_name is a tag name of a structure.
Examp
ple:
stdio.h>
#include<s
#include<c
conio.h>
struct book
k
{
cha
ar title[100];
cha
ar author[50]];
int pages;
floa
at price;
};
void main()
{
stru
uct book boo
ok1;
prin
ntf("enter titlle, author name, pages an
nd price of bo
ook");
sca
anf(%s,book1.title);
sca
anf(%s, boo
ok1.author);
sca
anf("%d",&bo
ook1.pages);
sca
anf("%f",&boo
ok1.price);
prin
ntf("\n detail of the book"");
prin
ntf(%s,boo
ok1.title);
prin
ntf(%s,boo
ok1.author);
prin
ntf("%d",boo
ok1.pages);
prin
ntf("%f",book
k1.price);
gettch();
}
ucture whose
e members arre title, autho
or, pages and
d price.
book is stru
How do
d we declare and acce
ess structure
e variables?
?
Declaration of str
ructure:
A structure variable declaration
n is similar to
o the declarattion of variab
bles of any otther data typ
pe. It includes
s
the folllowing eleme
ents:
1) The keyword struct
2) The structu
ure tag name
e
3) List of varia
able names separated
s
by commas
4) A terminatiing semicolon
n
For ex
xample:
k
struct book
{
cha
ar title[100];
cha
ar author[50]];
int pages;
floa
at price;
} book1;
struct book
k book2;
ble in two way
ys
We can declare structure variab
1) Just after the structure body like boo
ok1
2) With structt keyword and
d structure ta
ag name like book2
ssing structu
ure memberrs:
Acces
The fo
ollowing synta
ax is used to access the member
m
of strructure.
stru
ucture_variab
ble.member_
_name
structure_v
variable is a variable of structure
s
and
d member_na
ame is the na
ame of variab
ble which is a
member off a structure.
for ex:
book1.price
e
represents
s price of boo
ok1
What is Union?
ser defined da
ata type just like structure
e.
Union is us
Examp
ple:
union book
k
{
ar title[100];
cha
cha
ar author[50]];
int pages;
floa
at price;
};
4
Differrence betwe
een Structurre and Union
n
Struc
cture
on
Unio
All members
m
sharre the same storage
s
area.
All members
m
are active
a
at a tim
me.
All members
m
can be initialized..
Requires more me
emory.
Requ
uires less mem
mory.
Exam
mple:
Exam
mple:
struct SS
union
n UU
{
int a;
int a;
float b;
float b;
char c;
char c;
};
};
1 by
yte for c
2 by
ytes for a
4 by
ytes for b
Total bytes = 1 + 2 + 4 = 7 bytes.
A structure
e that contains another structure as a member variable is known as nested
d structure or
structure within
w
a struc
cture.
Structure which
w
is part of other stru
ucture must be
b declared before
b
the strructure in which it is used.
Examp
ple:
#include<stdio.h>
#include<conio.h>
>
struct address
{
char add1[50];
char add2[50];
char city[25];
};
struct employee
{
char name[100];
struct addrress a;
int salary;
};
void main()
m
{
struct employee e;
printf("ente
er name,addrress,city,salary");
scanf(%s,e.name);
scanf(%s,e.a.add1);
scanf(%s,e.a.add2);
scanf(%s,e.a.city);
scanf("%d"",&e.salary);
printf("deta
ail of employa
aee:");
printf("%s,e.name);
printf("%s,e.a.add1);
printf("%s,e.a.add2);
printf("%s,e.a.city);
printf("%d"",e.salary);
getch();
}
As we have
e an array of basic data ty
ypes, same way
w
we can ha
ave an array variable of structure.
s
Follow
wing example shows how an
a array of sttructure can be
b used
#include<stdio.h>
#include<conio.h>
>
struct result
{
char name[100];
int rollno;
float cpi;
};
void main()
m
{
struct result r[66];
int i;
er detail of sttudent :");
printf("ente
for(i=0;i<6
66;i++)
{
prin
ntf("\nenter name,roll
n
no,,cpi");
sca
anf(%s,r[i]..name);
sca
anf("%d%f",&
&r[i].rollno,&r[i].cpi);
}
d
of stude
ent:\n");
printf("\n detail
for(i=0;i<6
66;i++)
{
ntf(%s,r[i]..name);
prin
prin
ntf("\t%d",r[i].rollno);
prin
ntf("\t%f\n",r[i].cpi);
}
getch();
}
Darsh
han Institu
ute of Engin
neering & T
Technology
y
ComputerProgra
amminga
andUtiliza
ation(CP
PU)110003
J)FileHandling
g
FilleManage
ement
Inreallife,wewantttostoredatapermanentlyysothatlaterronwecanreetrieveitandreuseit.
ofbytesstoredonasecond
darystoragedevicelikehaarddisk,pendrive,andtape.
Afileisaacollectiono
Therearretwokindso
offilesthatp
programmersdealwithtexxtfilesandbin
naryfiles.
TextfilearehumanrreadableanditisastreamofplainEngllishcharacterrs.
ble.ItisastreeamofprocesssedcharacteersandAsciissymbols.
Binaryfiilesarenothumanreadab
FilleOpening
gModes
Wewan
nttoopenfile
eforsomepurposelike,reeadfile,createnewfile,ap
ppendfile,reaadandwritefile,
etc
weopenanyffileforprocesssing,atthatttimewehaveetogivefileo
openingmode
e.
Whenw
Wecandolimitedop
perationsonlyybasedonm
modeinwhich
hfileisopened.
e.g.
fp = fope
en(demo.t
txt,r);
//H
Herefileisop
penedinreadonlymode.
Chas6diffeerentfileopen
ningmodesfortextfiles,
1.
2.
3.
4.
5.
6.
r
w
a
r+
w+
a+
openforread
dingonly.
openforwritting(Iffileexiststhenitisoverwritten)
openforapp
pending(Iffile
edoesnotexistthenitcreeatesnewfilee)
openforread
dingandwritting,startatb
beginning
openforread
dingandwritting(overwrittefile)
openforread
dingandwritting,attheen
nd(appendiffileexists)
pportedforbinaryfilesbyjustaddingb
b,e.g. rb, wb,
w
ab, r+b,
r
w+b, a+b
Samemodesarealsosup
WrriteaCprogramtod
displayfilleonscree
en.
#inclu
ude <stdio.h>
void main()
m
{
;
FILE *fp;
char ch ;
//fp isfilepointerr.FILEisasttructuredefin
nedinstdio.h
h
fp = fope
en(prog.c
c, r); //OpenPr
rog.cfileinreadonlymo
ode.
c = getc(
(fp) ;
while (ch
h != EOF)
//EOF=En
ndofFile.Reaadfiletillend
d
{
char(ch);
putc
ch = getc (f
fp);
//Readssinglechaaracterfromfileandadvancesposition
ntonextcharracter
}
p);
fclose(fp
//Closetheefilesothatotherscanacccessit.
}
Darsh
han Institu
ute of Engin
neering & T
Technology
y
WrriteaCprogramtoc
copyafile
e.
#inclu
ude <stdio.h>
void main()
m
{
*q;
FILE *p,*
char ch;
p = fopen
n(Prog.c
,"r");
q = fopen
n(Prognew
w.c,"w");
ch = getc
c(p);
while(ch != EOF)
{
putc
c(ch,q);
ch = getc(p);
}
printf("F
File is co
opied suc
ccessfully
y. ");
fclose(p);
fclose(q);
;
return 0;
}
Ex
xplainfileh
handingfu
unctionsw
withexample.
Cprovidesasetoffunctionstodooperatiionsonfile.TThesefunctionsareknown
nasfilehandllingfunctionss.
Eacchfunctionisusedforsom
meparticularp
purpose.
fop
pen()
(Openfile)
fopenisusedtoopenafileforoperattion.
ofopenfunction,
Twoargumeentsshouldbesuppliedto
Filenameorrfullpathofffiletobeope
ened
Fileopeninggmodewhich
hindicateswh
hichtypeofo
operationsareepermittedo
onfile.
Iffileisopen
nedsuccessfu
ully,itreturnsspointertofiileelseNULL.
Exaample:
fp = fope
en(Prog.c
c,r);
fclo
ose()
(Closefile)
Openedfilessmustbeclosedwhenoperationsareo
over.
Thefunction
nfcloseisuse
edtoclosethefilei.e.indicatethatwearefinishedp
processingth
hisfile.
Tocloseafile,wehaveto
osupplyfilep
pointertofcllosefunction.
edsuccessfullythenitretu
urns0elseEO
OF.
Iffileisclose
Exaample:
p);
fclose(fp
fprrintf()
(Writeform
mattedoutpu
uttofile)
meisprog.canditisopenedforreadiingonly.
//Filenam
Thefprintfffunctionprinttsinformation
ninthefileacccordingtoth
hespecifiedfformat.
fprintf()worrksjustlikeprrintf(),onlydifferenceisw
wehavetopassfilepointertothefuncttion.
Itreturnsthenumberofcharactersou
utputted,oraanegativenu
umberifanerrroroccurs.
Exaample:
fprintf(f
fp
Sum = %d
su
um);
Darsh
han Institu
ute of Engin
neering & T
Technology
y
fscanf()
(Readform
matteddataf
fromfile)
Thefunction
nfscanf()read
dsdatafromthegivenfilee.
Itworksinaamannerexacctlylikescanff(),onlydifferrenceiswehavetopassfiilepointertothefunction.
Ifreadingissucceededth
henitreturnssthenumberofvariablestthatareactuaallyassignedvalues,orEO
OFifany
erroroccurrred.
Exaample:
fscanf(fp
p, %d, &sum);
&
fse
eek()
(Reposition
nfilepositio
onindicatorr)
Setsthepossitionindicato
orassociatedwiththefilepointertoan
newpositiondefinedbyad
ddingoffsetttoa
referencepo
ositionspeciffiedbyorigin..
Youcanusefseek()tomo
ovebeyondaafile,butnotbeforethebeginning.
fseek()clearrstheEOFflaggassociatedwiththatfile.
Wehavetosupplythreearguments,ffilepointer,h
howmanychaaracters,from
mwhichlocation.
erouponsucccess,nonzero
oonfailure.
Itreturnsze
The
eoriginvalueshouldhaaveoneofthe
efollowingvaalues
Nam
me
Explanation
SEE
EK_SET Seekfromth
hestartoftheefile
SEE
EK_CUR Seekfromth
hecurrentlocation
SEE
EK_END Seekfromth
heendofthefile
Exaample:
fseek(fp,
,9,SEEK_SE
ET); //Mo
ovesfilepositiionindicatorto9thpositionfrombegging.
ftelll()
(Getcurren
ntpositionin
nfile)
Itre
eturnsthecurrentvalueo
oftheposition
nindicatoroffthefile.
Forrbinarystream
ms,thevalue
ereturnedcorrespondstothenumberofbytesfrom
mthebeginnin
ngofthefile.
Exa
ample:
rew
wind()
(Setpositio
onindicatortothebegin
nning)
Setsthepossitionindicato
orassociatedwithfiletoth
hebeginningofthefile.
Acalltorew
windisequivalentto:
fseek (fp
p, 0, SEEK
K_SET);
Onfileopen
nforupdate(read+write),acalltorewindallowstoswitchbetweeenreadingandwriting.
Exaample:
rewind (f
fp);
gettc()
(Getcharaccterfromfile
e)
getcfunctionreturnstheenextcharactterfromfileo
orEOFiftheeendoffileisrreached.
Afterreadingacharacterr,itadvancespositioninfilebyonechaaracter.
getcisequivvalenttogetcchar().
fgetcisidenticaltogetc.
Exaample:
ch = getc
c(fp);
puttc()
(Writecharractertofile
e)
putcwritesaacharacterto
othefileandadvancestheepositionind
dicator.
Afterreadingacharacterr,itadvancespositioninfilebyonechaaracter.
Darsh
han Institu
ute of Engin
neering & T
Technology
y
putcisequivvalenttoputcchar().
fgetcisidenticaltoputc.
Exaample:
putc(ch, fp);
f
gettw()
(Getintege
erfromfile)
getwfunctio
onreturnstheenextintfromthefile.IfeerroroccurstthenEOFisreeturned.
Exaample:
i = getw(
(fp);
puttw()
(Writeinteg
gertofile)
putwfunctio
onwritesinte
egertofilean
ndadvancesindicatortonextposition.
Itsucceeded
dthenreturnssameintege
erotherwiseEOFisreturn
ned.
Exaample:
putw(I, fp);
f
Wrriteaprog
gramtoco
ountthenu
umberofl
lines,tabss,characte
ersandwo
ordsinafiile.
#in
nclude <s
stdio.h>
voi
id main()
{
*
FILE *fp;
int li
ines=0, tabs=0, ch
haracters=
=0, words = 0;
char ch,
c
filename[100] ;
printf
f(Enter file name
e: );
gets( filename );
///Youcanalso
ouse scanf
f(%s,fil
lename);
f
filename, r
);
fp = fopen(
if ( fp
f == NULL )
///FileisnotopenedsuccesssfullythenitreturnsNULL.
{
printf(C
Cannot ope
en %s for
r reading \n, file
ename );
exit(1);
/* terminate
t
e program */
}
ch = getc(
g
fp ) ;
while ( ch != EOF )
{
if ( ch == \n )
line
es++ ;
else if ( ch == \t )
tabs
s ++ ;
else if ( ch ==
word
ds ++ ;
else
char
racters++
+;
c = getc ( fp );
}
fclose
e( fp );
printf
f(Lines=%d Tabs=%
%d Wods=%d
d Characters=%d, lines, ta
abs, words,
charac
cters);
}
Darsh
han Institu
ute of Engin
neering & T
Technology
y
ComputerProgra
amminga
andUtiliza
ation(CP
PU)110003
K)D
DynamicM
MemoryA
Allocation
n,StorageClasses
StaticMemoryAllocatio
on
Dynam
micMemo
oryAlloca
ation
If memory is allocated
d to variablees before
nofprogram)thenitiscalleddynamic
execution
staticmemo
oryallocation.
memory.
Itisfastand
dsavesrunnin
ngtime.
Itisbitslo
ow.
Itallocatesm
memoryfrom
mstack.
Itallocateesmemoryfro
omheap
It is preferreedwhen size
e of an array isknown
Itispreferredwhennu
umberofvariablesisnot
knowninadvanceorvverylargeinsize.
utionofprogram.
mostofthetimeofexecu
m
stayss from start to
t end of
Allocated memory
Memoryccanbeallocaatedatanytimeandcan
program.
bereleaseedatanytime.
g
symbo
olic name
The storagee space is given
no name
e and thereefore its value can be
canaccessvvalue.
accessedonlythroughapointer.
e.g.
inti;
floatj;
e.g.
nt));
p=malloc(sizeof(in
Ex
xplainvarriousfuncctionsuse
edinDyna
amicMem
moryAllo
ocation.
ma
alloc()
malloc())isusedtoallocateacertaainamountbyytesofmemo
oryduringtheeexecutiono
ofaprogram.
malloc())allocatessi
ize_in_byt
tesbytesofmemoryfrom
mheap,iftheeallocationsu
ucceeds,apo
ointerto
theblocckofmemoryyisreturnede
elseNULLisreeturned.
malloc())returnsanuninitializedm
memoryforyo
outouse.
Malloc())canbeusedtoallocatespaceforcomplexdatatyp
pessuchasstructures.
ptr_
Syntax:
_var = (c
cast_type *)malloc(
(size_in_
_bytes);
e:
Example
clude<std
dio.h>
#inc
int main()
{
int *p ;
nt *)malloc(sizeof
f(int));
p = (in
*p =25;
;
printf(
(%d,*p);
free(P)
);
}
callloc()
calloc()isusedtoallo
ocateablockofmemoryd
duringtheexeecutionofap
program,e.g.foranarray.
calloc()aallocatesareegionofmemorylargeeno
oughtoholdn
no_of_blo
ocksofsizes
size_of_bl
lock
each,ifttheallocation
nsucceedsth
henapointertotheblocko
ofmemoryissreturnedelsseNULLisreturned.
Darsh
han Institu
ute of Engin
neering & T
Technology
y
Syntax:ptr_var=(c
cast_type
e *)calloc
c(no_of_bl
locks ,si
ize_of_blo
ock);
Example
e:
#inc
clude<std
dio.h>
int main ()
{
n;
int i,n
int *p
p;
printf ("Enter how many numbers:"
");
scanf ("%d",&n)
;
(
p = (in
nt*) calloc (n, si
izeof(int)
));
for (i=
=0; i<n; i++)
{
scanf(%d
,p);
p
p++;
}
}
rea
alloc()
realloc())reallocatesaamemoryblo
ockwithasp
pecificnewsizze.Ifyoucalllrealloc(),theesizeofthe memory
blockpo
ointedtobytthepointerischangedtotthegivensizeeinbytes.Thiiswayyouarreabletoexp
pandand
reducettheamounto
ofmemoryyo
ouwanttouse.
It is posssible that th
he function moves
m
the meemory block to a new loccation; then the function returns
address of new locaation. Old memory
m
blockk is copied to
o new memo
ory and old memory is released
automattically.
Thecontentwillremainunchangeedmeansitisscopiedtoneewlocation.
ointerisNULLLthenthereaalloc()willbehaveexactlylikethemallo
oc().Itwillasssignanewblockofa
Ifthepo
sizeinbytesandwillreturnapoin
ntertoit.
Syntax:
ptr_v
var=*reallo
oc(void*ptrr,size_tsize);;
e:
Example
#inc
clude<std
dio.h>
int main()
{
int *p ;
nt *)malloc(sizeof
f(int));
p = (in
*p =25;
;
p = (in
nt *)realloc(p, 2 * sizeof(
(int));
printf(
(%d,*p);
free(P)
);
}
fre
ee()
Whenth
hememoryissnotneededanymore,youmustreleasseitcallingth
hefunctionfree.
Justpassthepointeroftheallocatedmemorytofreefunctionandmem
moryisreleaseed.
void
d free(vo
oid *point
ter);
Syntax:
Example
e:
free
e(p);
Darsh
han Institu
ute of Engin
neering & T
Technology
y
Sto
orageCla
ass
Storageclassdecidessthescope,liifetimeandm
memoryallocaationofvariable.
Scopeofavariableisstheboundarrywithinwhicchavariablecanbeused.
orageclassesareavailableinC,
Foursto
o Automatic(a
auto)
o Register(reg
gister)
o External(ext
tern)
o Static(static)
auttomatic:
Variable
eswhichared
declaredinfu
unctionareoffautomaticsttorageclass.
Automaticvariablesaareallocatedstorageinth
hemainmemoryofthecomputer.
onandfreed automaticallyuponexitffromthe
Memoryyisallocatedautomaticallyuponentryytoafunctio
function
n.
Thescop
peofautomaaticvariableisslocaltothefunctioninw
whichitisdeclared.
Itisnotrequiredtou
usethekeywo
ordautobecaausebydefau
ultstorageclaasswithinab
blockisauto.
Exaample:
int a;
auto int a;
reg
gister:
extternal:
Automaticandregisttervariablesh
havelimitedsscopeandlim
mitedlifetimesinwhichtheeyaredeclareed.
mesweneedglobalvariab
bleswhichareeaccessibleth
hroughouttheprogram.
Sometim
extern
nkeyworddeefinesaglobaalvariablethaatisvisibletoALLfunction
ns.
extern
nisalsousedwhenourprrogramisstorredinmultipllefilesinsteadofsinglefilee.
Memoryyforsuchvariablesisallo
ocatedwhen theprogram beginsexecu
ution,andremainsallocatteduntil
theproggramterminaates.Memoryyallocatedfo
oranexternallvariableisin
nitializedtozeero.
Declarattionforexterrnalvariableisasfollows: extern int var;
sta
atic:
static
ckeyworddeefinesaglobaalvariablethaatisvisibletoALLfunction
nsinsamefilee.
Memoryyallocatedfo
orstaticvariab
bleisinitializeedtozero.
Staticstorageclasscaanbespecifieedforautomaaticaswellassexternalvarriablessuchaas:
static
c extern in
nt varx; //static ex
xternal
// static a
static
c int var;
automatic
Staticau
utomaticvariablescontinu
uetoexisteveenaftertheffunctionterm
minates.
Thescop
peofstaticau
utomaticvariiablesisidentticaltothato
ofautomaticvvariables.
Darsh
han Institu
ute of Engin
neering & T
Technology
y
Ex
xplainInp
put/Outp
putfunctions.
Clanguaageprovides asetofstan
ndardbuiltin
nfunctionsw
whichwilldottheworkof readingordiisplaying
dataorinformationo
ontheI/Odevicesduringp
programexeccution.
Ofunctionsesstablishanintteractivecom
mmunicationb
betweentheprogramand
duser.
SuchI/O
Fo
ormattedI
nput/Outp
putfunctions
sca
anf()
Itisused
dtoreadallttypesofdata..
Itcanno
otreadwhitespacebetweenstrings.
Itcanreeadmultipled
dataatatimeebymultipleformatspeciffierinonescaanf().
Example
e:
scan
nf(%d%d
, &a, &b)
);
priintf()
Itisused
dtodisplayalltypesofdataandmessaages.
Itcandisplaymultipledataatatim
mebymultip
pleformatspeecifierinoneprintf().
Example
e:
prin
ntf(a=%d
d b=%d, a
a, b);
Un
nformatted
dinputou
utputfuncttions
getts()
Itisused
dtoreadasin
nglestringwiithwhitespacces.
Itisterm
minatedbyen
nterkeyorattendofline.
Example
e:
char str[10];
s
gets(s
str);
gettchar(),getcche(),getch
h()
Itisused
dtoreadsingglecharacteratatime.
getchar(()functionreequiresenterkeytotermin
nateinputwh
hilegetche()andgetch()doesnotrequire.
getch() functiondoe
esnotdisplayytheinputch
haracterwhilegetchar()aandgetche())functiondissplaythe
inputch
haracteronth
hescreen.
Example
e:
char ch;
c
ch = getchar()
g
;
ch = getche();
g
ch = getch();
g
putts()
Itisused
dtodisplayastringatatim
me.
Example
e:
char str[]=He
s
llo;
puts(s
str );
puttchar()
Itisused
dtodisplaysinglecharacteratatime.
Example
e:
Darsh
han Institu
ute of Engin
neering & T
Technology
y
putcha
ar(ch);
Ch
haracterch
heckingfu
unctions.
Chaaractercheckkingfunctionssareavailable
einctype.hheaderfile.
1.
2.
3.
4.
5.
6.
7.
isdigit(in
nt);
isalpha(int);
isalnum(int);
isspace(int);
islower(int);
isupper((int);
ispunct(int);
forcheckingnumber(09)
forcheckingletter(AZoraz)
forcheckingletter(AZoraz)ordigit(09)
forcheckingempttyspace
forcheckingletter(az)
forcheckingletter(AZ)
bols(like:,;,{,},?,.etcc.)
forcheckingpuncctuationsymb
Ex
xample:Wrriteaprog
gramtoch
hecktheen
nteredcha
aracterisdigitorno
ot
#inclu
ude<stdio.h>
#inclu
ude<conio.h>
#inclu
ude<ctype.h>
void main()
m
{
char c;
clrscr();
;
scanf("%c
c",&c);
if(isdigi
it(c))
prin
ntf("True
e");
getch();
}