Sei sulla pagina 1di 64

Darshan Insttitute of En

ngineering & Technology Syllabus


S for 1st midsem exa
am

Computer Programmiing and Utiliization (CPU


U) – 110003
3

A) Co
omputer Fun
ndamentals

1 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

Centtral Processiing Unit

ALU + CU
U

INP
PUT SECTIO
ON 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):-
(
• Central processing unit is a main parrt of the comp
puter system.
• 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 performs all arithmetic callculations and takes logical decision.
9 Itt can perform add, subtractt, multiply, compare, count,, shift and oth
her logical activities.
9 Itt calculates ve
ery fast.
9 Itt takes data from memory
y unit and re
eturns data to
t memory unit,
u generally
y primary
memory.
m
1
1.2) Contro
ol Unit (CU)
9 Itt controls all other
o units in the
t computer system.
9 Itt manages all operations
9 Itt reads instruc
ction and data
a from memorry.
1
1.3) Primary Memory:-
9 Itt is also known
n as main 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

9 Thiis memory is accessed


a by C
CPU, in random
m fashion
9 Generally curren
ntly executing programs and data are sto
ored in primarry memory
9 Its storage capacity is very sm
mall compared
d to secondary
y storage.
9 It is very fast in an operation compared to secondary sto
orage
9 RAM is Random Access Memo
ory and it is vo
olatile in naturre.
9 RO
OM is Read Only Memory an
nd it can hold data permane
ently.
9 PRO mmable Read Only Memory
OM is Program y and it can h
hold data perm
manently. Pro
ogrammer
can
n store inform
mation only once. Modificatio
on is not allow
wed.
9 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:-
• es used to entter data in to computer sys
The device 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
• Examples:: Mouse, Keyb
board, Touch s
screen, Joystick etc…

3) Output
O Sectio
on:-
• The device
es used to send the inform mputer is called output
mation to the outside world from the com
devices.
• It converts
s data stored in 1s and 0s iin computer to human unde
erstandable in
nformation
• Examples:: Monitor, Prin
nter, Plotter, Speakers
S etc…

4) Storage
S devic
ces (Secondary memory
y):-
• Secondary
y memory is also
a called Aux
xiliary memory
y or External memory.
• User can store
s data perrmanently.
• It can be modified
m easily.
• It can storre large data compared
c to primary
p memo
ory. Now days
s, it is availab
ble in Terabyte
es.
• Examples:: Hard disk, Floppy disk, CD
D, DVD, Pen drive,
d etc…

2 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 peed of computers. There are
the sp 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 ons of paper file’s data
ntity using varrious storage devices. Millio
c
can be stored in single sma
all pen drive. M
Moreover, it reproduces
r ata whenever we need and whatever
da
fo
ormat we nee
ed. Now a day
ys, Gigabytes a s are units of data storage devises.
and Terabytes
• A
Accuracy: Co a very high speed witho
omputer perfforms the computations at 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.

3 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:--
• Computer directly und
derstands this language. It is a language
e of 0’s and 1’s
1 (binary). Every
E CPU
has its ow
wn machine la
anguage.
• ADVANTA
AGES:
1. It is very
v fast in ex
xecution
2. It does not require
e any extra sy
ystem or softw
ware to run the program.
3. Trans
slation is not required.
4. Suita
able for low vo
olume applicattions.
• DISADVA
ANTAGES:
1. g and difficult to write and understand
Progrrams are long u for human.
2. ugging is very difficult task..
Debu
3. It is not portable.
4. Progrrammer requires detailed k
knowledge of architecture
a o microproces
of ssor.
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.
• Example : 8086 Instru
uction Set
• ADVANTA
AGES:
1. Progrrams are easy
y to understan t machine level language.
nd compared to
2. Progrrams are sma
aller in size compared to ma
achine level la
anguage.
3. Progrrams can be entered
e quicklly using alpha
anumeric keyb
board.
• DISADVA
ANTAGES:
1. It is not portable.
2. Progrrammer shoulld know structture of assem
mbly language of microproce
essor.
3. It req
quires assemb
bler as a trans
slator.

3) Higher levell language:-


• We can write
w programs in English lik nd it is more convenient to use.
ke manner an
• Programm orm complex ttask by using high level languages with le
mer can perfo ess efforts.

3
Darshan Insttitute of En
ngineering & Technology Syllabus
S for 1st midsem exa
am

• It is simillar to natural language and


d mathematica
al notation.
• Example:: C, C++, Java, etc…
• 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.
• 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) It is bit slow comp evel and medium level language.
pared to low le

4 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 advantages of highe
er level language through function,
f modular programm
ming and brea
akup.
• It gives access
s to the low le
evel memory tthrough Pointe
ers.
• M
Moreover it do
oes support th programming i.e., Assembly
he Low Level p y Language.
• W can develop application specific pro
We ograms in C and at the s
same time we can use fe
eatures of
a
assembly level language to give more speed and efficiency
• It is not hardw
ware or system
m dependent. Hence portab
ble programs c
can be written
n with C comp
piler.

5 Write a short note on


o types of software.
A set of instruction
i in a logical orde
er to perform
m a meaningfu ed program and a set of program is
ul task is calle
called sofftware.
System Software
S
System software is des
signed to operrate the comp
puter hardwarre efficiently. IIt provides an
nd maintains a platform
for runnin
ng application
n software. Siince system s
software runs at the most basic level off computer, itt is called
"low-level" software.
System software can be
b classified in
nto three categ
gories
1) O
Operating ols hardware as well as interacts with us
systtem: It contro vides different services
sers, and prov
to user. It is a bridge betwe
een computer hardware and nux, UNIX, etc…
d user. Ex: Wiindows XP, Lin
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 to programmers.
ment environm
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 … Example: Enterprise so
ket booking …). 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 ose software:: It is used widely by many
purpo m mmon task, like word
people ffor some com
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 Syllabus
S for 1st midsem exa
am

2) 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 user’s
s
special require
ement.

6 Define the
t following
g terms:
1. P
Program
ction in a logical order to perform a mea
A set of instruc aningful task is
s called progrram.
2. S
Software
A set of instrruction in a lo
ogical order to d program, and set of
t perform a meaningful task is called
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.

5
Darsh
han Institu
ute of Engin
neering & T
Technology
y Syllabus for 1st midsem
m exam

Co
omputer Pro
ogramming and Utilizattion (CPU) – 110003

B) Flowch
hart & Algor
rithm

1 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.
• Easy to understand logic.
• Easy to identify mistakes by non
n computerr person.
• Easy to show brranching and looping.
l
Disadv
vantages
• Tim
me consuming
g.
• Diffficult to modiify.
• ery difficult to draw flowchart for big or complex proble
Ve 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 a picttorial representation of a process. It is step wise


w analysis of
o the work to be done.

Solution is shown in graphical forma


at. Solution is shown in non computer lan
nguage like En
nglish.

Easy to understand as compared to algorithm. It is somew


what difficult to understand.

Easy to sh
how branching
g and looping. Difficult to show branching and looping.

Flowchartt for big proble


em is impracttical Algorithm can
c be written
n for any problem
Darsh
han Institu
ute of Engin
neering & T
Technology
y Syllabus for 1st midsem
m exam

2 Explain various symb


bol used in flowchart.
f

Start / Stop

Input / Output
(Read / Print)

Process

Decisio
on making

Subrou
utine

s
Arrows

rite an algo
Wr orithm and
d Draw a flo
owchart
3 To find wh
hether given
n number is even
e or odd.
Algorithm
m:-
Step 1 : Input no.
Step 2 : If no mod 2=0, goto 4.
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 No
Is No
o mod 2=0?

Print no is Even Print no is Odd

sttop
Darsh
han Institu
ute of Engin
neering & T
Technology
y Syllabus for 1st midsem
m exam

4 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
osÅ0,negÅ0,,zeroÅ0
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 : Increment pos by 1, pos
s=pos+1.go to
o8
Step 7 : Increment neg by 1, neg
g=neg+1.
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 : Print pos, neg,
n zero.
Step 12: Stop.

Flowchartt:-
start

posÅ0,neg
gÅ0,zeroÅ0

Read no

Yes
s No
Is no>0?
n

Yes Is no<0? No
posÅpos+1
1

negÅ
Åneg+1 zeroÅz
zero+1

Yes Do you waant to


enter morre no?

No

Print pos, ne
eg, zero

stop
Darsh
han Institu
ute of Engin
neering & T
Technology
y Syllabus for 1st midsem
m exam

5 To print maximum
m number from a given 3 num
mbers.
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 No
Is
a > b?

Yes No Yes No
Is Is
a>c? b>c?

Print “max =” a Print


P “max =”” c Print “max =” b Print “ma
ax=” c

stop
Darsh
han Institu
ute of Engin
neering & T
Technology
y Syllabus for 1st midsem exam

6 To find the factorial off a given num


mber.
m:-
Algorithm

Step 1 : Initialize countÅ1,factÅ


Å1
Step 2 : Read no
Step 3 : Calculate factÅfact
f * co
ount.
Step 4 : Incrementt count by 1, countÅcount+
c +1.
Step 5 : If count<=
=no, goto 3.
Step 6 : Print fact.
Step 7 : Stop.

Flowchartt:-

start

Read no

co
ountÅ1,factÅ
Å1

factt Å fact * count

cou
unt Å count + 1

Ye
es Is
count<=no?
?

No

Print fact

stop
Darsh
han Institu
ute of Engin
neering & T
Technology
y Syllabus for 1st midsem exam

7 To solve series
s 1!+2!+
+3!+4!+………
…….+n!
Algorithm
m:

Step 1 : Initialize count=1, fact=


=1, sum=0
Step 2 : Read no
Step 3 : Calculate fact=fact*cou
f nt
Step 4: Calculate sum=sum
s + fact.
f
Step 5: Incrementt count by 1, count=count+
c +1.
Step 6: If count<=
=no, goto 3.
Step 7: Print sum.
Step 8: Stop.

Flowchartt:

start

Read no
o

cou
untÅ1,factÅ1
1,sumÅ0

fa
actÅfact * co
ount

s
sumÅsum + fact

c
countÅcount +1

Is
count<=nno?
Yes
Y

N
No

Print sum
m

stop
Darshan Insttitute of En
ngineering & Technology Syllabus
S for 1st midsem exa
am

Computer Programmiing and Utiliization (CPU


U) – 110003
3

C) C Fundamen
ntals

1 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
Global Declaration Section
S 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;
}

2 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()
):
• scanf() is a library function that reads d
data with spec
cified format ffrom standard
d input (keybo
oard).
• 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.
• The function returns the total number o
of items succe
essfully read.
• 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 erally monitor.
d output, gene
• Syntax: int prin
ntf(char * format, arg
g1, arg2, …)

• Exampe: printf(“
“Your marks
s are %d”, mark);
m


Darshan Insttitute of En
ngineering & Technology Syllabus
S for 1st midsem exa
am

• 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.
• printf() returrns the numbe
er of characte
ers printed.

3 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) ure, union, enu


(structu um)

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
int is in mber without fraction partt. Its range is machine dependent
d
values. C has 3 class mely short int, int and long
ses of integerr storage nam g int. All of th
hese data
types ha
ave signed and
d unsigned forms.
sig
gned u
unsigned
Size Range S
Size Range
(bits) (bits)
short int 8 -128 to 127 8 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

b. 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 Uns
signed
Size
S (bits) Range Size (b
bits) Range
charr 8 -128 to 127 8 0 to 255

c. 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


Darshan Insttitute of En
ngineering & Technology Syllabus
S for 1st midsem exa
am

use the double to deffine the numb


ber. The doub
ble is same as
s float but with longer precision. To
extend the
t precision further
f we can
n use long dou
uble which consumes 80 bitts of memory space.
Size (bits) Precision Digits
D Rang
ge
float 32 6 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

d. 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…
i. Array: An arrray is a fixed-s
size sequence
ed collection of elements of the same datta type.
ii. Pointer: Pointter is a specia
al variable whiich contains m
memory addre
ess of another variable
b. 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. union: Union is like a struc
cture, except that
t each elem
ment shares the comman memory.
m
iii. enum: Enum is a user-defiined type cons
sisting of a se onstants called
et of named co
enumerators.. The enumera
ator names arre usually iden
ntifiers that be
ehave as cons
stants in
the language.
Example:
enum day
y {Mon, Tue, Wed, Thu, Fri, Sat, Sun};
enum day
y week1stday
y;
week1std
day = Mon;
4 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 Non
n numeric constant

Integer consta
ant Real 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
• There are three types of in
ntegers constant.
o 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
+
o 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
o Hexad
decimal intege
er
Hexad er consists of any combinattion of digits from the set 0 to 9 and A to
decimal intege oF
alphab
bets. It alway
ys starts with 0 epresents 10, B represents 11… F represents 15.
0x or 0X. A re
Ex: 0X
X2A, 0x95, 0x
xA47C.

Real co
onstant:-
• The numberr containing th
he fractional p
part is called real
r number. Ex:
E 0.0083, -0
0.75, +247.0,, -0.75.
• A real numb
ber may also be
b expressed in exponentia
al notation.
• The general form is: man nent, ex: 215.65 can be wriitten as 2.156
ntissa e expon 65e2.
• In exponenttial form, e2 means
m multiply by 102.

Single character co
onstant:-
• er enclosed within a pair of single quote mark.
It contains single characte
• Ex: ‘5’, ‘A’, ‘;’, ‘ ‘

String constant:-
• A string cons
stant is a sequ
uence of chara
acters enclose ouble inverted comma.
ed within a do
• The characte
ers may be lettter, number, special character, blank sp
pace, etc…
• Ex: “DIET”, “1988”,
“ “?A.B
B,!”, “5+3”, etc…
• ‘A’ is charactter but “A” is string.
s

5 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. First character must be an
n alphabet or an underscore
e.
3. Only first 31 characters arre significant.
4. Cannot use C keyword.

6 Define the followin


ng terms:
Token:
• Smallest unit of any langu
uage is known
n as token.


Darshan Insttitute of En
ngineering & Technology Syllabus
S for 1st midsem exa
am

• The tokens are


a the basic building
b blocks which can be
b put togethe
er to constructt programs.
• There are six
x classes of to
okens in C: ide
entifier, keywords, constants, string literrals, operators
s and
other separa
ators
Identiffier:
• e of letters and digits.
An identifier is a sequence
• The words which
w ned by programmer in a pro
are defin ogram are kno
own as identiffier.
• Identifier reffers to the nam
me of variable
es, functions and
a arrays.
Keyword:
• Keywords arre reserved wo
ords whose meaning
m is fixed and they arre used for som
me special pu
urpose by
the compilerr.
• They cannot be used by programmer
p fo
or other purpo
ose.
void - data
d type:
• void is a prim
mary data type. void means
s nothing, no value.
• It is generallly used to sho
ow that functio
on is not returrning anything
g.

7 Explain
n operators available
a in C
An operrator is a symbol that tells the
t t perform certain mathematical or logical operation. C has
compiler to
rich set of operators as below,
1. Arithmetic Ope
erators
on. C supports following arithmetic opera
Aritthmetic operators are used for mathematical calculatio ators
+ Addition or unary plus
s a+ b (additiion), +7 (unary plus)
- Subtracttion or unary minus 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…
< 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
3. Log
gical Operato
ors
Log
gical operators
s are used to test
t more than one conditio
on and make decisions
&&
& on zero then ttrue, either is zero then false)
logical AND (Both no
|| logical OR (Both zerro then false, either is non zero
z then true
e)
! logical NOT (non zero then false, zero then true)
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 Syllabus
S for 1st midsem exa
am

= 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
5. 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
Ex. a= a this state
ement, a= 9, b = 9.
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 s are used to perform opera
wise operators ation bit by biit. Bitwise ope
erators may not be applied to float
or double.
d
& bitwise
e AND
| bitwise
e OR
^ bitwise
e exclusive OR
R
<<
< shift le
eft ( shift left means
m multiply by 2)
>>
> shift right ( shift righ
ht means divide by 2)
8. 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.
8 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.


Darshan Insttitute of En
ngineering & Technology Syllabus
S for 1st midsem exa
am

• 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 ession expr2 is evaluated otherwise
hen the expre
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.

9 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.
Impliciit Type Castiing:
• 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.
• n is known as implicit type conversion.
This automatic conversion c
• The lower type is automattically convertted to the high
her type beforre the operation proceeds. The
result is high
her type.
• Example:
o If on
ne operand is int and otherr is float then int will be con
nverted to floa
at.
o 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

Explicitt Type Castin


ng:
• 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.
• The general form of cast is: (type--name) expre
ession.
• Where type-name is one of
o the standarrd C data type
e. The express
sion may be constant, varia
able, or
an expressio
on.
Example:
#include<std
dio.h>
#include<co
onio.h>


Darshan Insttitute of En
ngineering & Technology Syllabus
S for 1st midsem exa
am

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); // This will print
p 4
avg=
=(float)sum / (float)n; // explicit ty
ype casting
printtf(“Result of Explicit
E Type C
Casting: %f”, avg); // This will print
p 4.7
}
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 der to calculatte an expression, we
e in which ord
must use associa
ativity.
• Folllowing table provides
p a com
mplete list of operator,
o theirr precedence level, and the
eir rule of asso
ociation.
Ran
nk 1 indicates highest prece
edance level a
and 15 is the lowest.
l
Prece
edence As
ssociativity Operattor Des
scription
1 Lefft to Right () Func
ction Call
[] Arra
ay Element Re
eference
2 Rig
ght to Left +, - Unary Plus, Unary
y Minus
++, -- 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)
3 Lefft to Right * Multtiplication
/ Divis
sion
% Modulus
4 Lefft to Right + Addition
- Subttraction
5 Lefft to Right << Left Shift
>> Righ
ht Shift
6 Lefft to Right < Less
s than


Darshan Insttitute of En
ngineering & Technology Syllabus
S for 1st midsem exa
am

<= Less
s than or equa
al to
> Grea
ater than
>= ater than or equal to
Grea
7 Lefft to Right == Equa
ality
!= Ineq
quality
8 Lefft to Right & Bitw
wise AND
9 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 ==, *=, /=, Assignment Opera
ators
%=, +=
=, -=,
&=, ^=
=, |=,
<<=, >
>>=
15 Lefft to Right , Com
mma Operator
11 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 ckslash ‘\’ charracter.
pe sequence sttarts with bac
Escape sequence M
Meaning
‘\0’ End of string – NULL.
‘\n’ End of line – take
es the control to next line.
‘\r’ Carrriage return – takes the control to the ne
ext paragraph
h.
‘\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 y to enter certtain characterrs which are not
duces conceptt of “trigraph” sequence to provide a way
availablle in some key
yboard of non uage. Each trigraph charactter consists off a three characters.
n English langu
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

Computer Programmiing and Utiliization (CPU


U) – 110003
3

D)
D Decision Control
C Stru
ucture (if, if else, if else
e if, switch, …)

1 Expla
ain if with ex
xample and draw
d flowchart.

• iff is used to co
ontrol the flow
w of execution of statements
s.
• Itt is two way decision
d makin
ng statement.
• 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
st lock
}
nt-x
statemen

• Iff the test expression


e is true, the statement-b
s block will be executed; otherwise the statement-
b
block will be skipped
s and the execution will jump to th
he statement
t-x.
Flowc
chart:

Entry

T
Test True
Exprression?

False 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
printf ven");
f(no%2!=0)
if
f("no is od
printf dd");
}

1
Darshan Insttitute of En
ngineering & Technology Syllabus
S for 1st midsem exa
am

2 Expla
ain if…else…
… with examp
ple and draw
w flowchart.

• Iff supports statements only for true part


• Iff…else supporrts statements
s for true partt and false parrt.

The general
g formatt is given belo
ow.

if(test-exp
i pression)
{
-block stat
True- tement.
}
e
else
{
e-block sta
False atement
}
s
statement-x
x;

• Iff test-expre
ession is true
e, then true-b ement is execu
block state 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
Darshan Insttitute of En
ngineering & Technology Syllabus
S for 1st midsem exa
am

3 Expla
ain if…else....if ladder witth example a
and draw flo
owchart.

n multipath de
When ecisions are involved, we may use if…else
e…if ladder, which
w takes the
e following ge
eneral form.
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
lt—statemen
nt;
tatement-x
st

• F
First on-1 is checke
conditio ed and if it is true, then statement-1 will
w be execute
ed and control goes to
statement-x.
• Iff condition-
-1 is false, the
en condition
n-2 is checked
d and if it is trrue then stat
tement-2 will be executed
and control goes to stateme
ent-x.
• Iff condition-
-2 is false, the
en condition
n-3 is checked
d and process
s repeats
• T
This process is ds one of the conditions is true or all the
s repeated unttil either it find 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 if…els
se…if ladder.

Flowc
chart: Entry

Test
Conditio
on
True 1 F
False

Test
Condition
Stattement-1 True 2 False

Stateme
ent-2 T
Test
Con
ndition
True
e 3 False

Test
Statement-3 Condition
n
True N

Fa
alse
State
ement-N

Default
statemennt

Statemen
nt-x

3
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,
in ,m4,m5;
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>=
el =60)
printf
f("First class");
lse if(avg>=
el =50)
printf
f("Second class");
lse if(avg>=
el =40)
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


When nvolved, we m
may have to use more than one if…else statement
s in nested
n form
as shown below.

if
f(test-conddition-1)
{
if(ttest-conditiion-2)
{
Statement-1;
}
elsee
{
Statement-2;
}
}
lse
el
{
Statemment-3;
}
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.

4
Darshan Insttitute of En
ngineering & Technology Syllabus
S for 1st midsem exa
am

Entry
Flowc
chart:

False T
Test True
Cond
dition 1?

Te
est
Condittion 2?
Sttatement-3 False

True

Statem
ment-1 S
Statement-2

Statem
ment-x

Next sta
atement

Exam
mple: Find max
ximum numbe
er from given three numberrs.
#include<<stdio.h>
void mainn()
{
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");
}
}

5
Darshan Insttitute of En
ngineering & Technology Syllabus
S for 1st midsem exa
am

5 Expla
ain switch-ca
ase statement with exam
mple.

• T
The switch stattement is a multi-way
m decis
sion making.
• Itt tests whethe
er an expressiion matches a
any one of the
e constant valu
ues or not.
• G
General form of
o switch-case
e is as below,
switch(ex
xpression)
{
ase const-ex
ca xpr 1: sta
atement 1;
bre
eak;
ase const-ex
ca xpr 2: sta
atement 2;
bre
eak;
ase const-ex
ca xpr 3: sta
atement 3;
bre
eak;
efault:
de
ments
statem
}
• e
expression in switch
s pression. Float or any otherr data type is not allowed.
should be integer or character exp
• E
Each case is la
abeled by one or more integ
ger-valued con
nstant.
• Iff a case match
hes the expre
ession value th
hen execution starts at thatt case.
• V
Value of all cas
se expressions must be diffferent.
• Iff none of the cases are mattched then de
efault case is executed.
e defa
ault case is op
ptional.
• 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:
f("Good (C)\n");
printf
break;
;
ca
ase 4:
f("Very Good (B)\n");
printf
break;
;
ca
ase 5:
f("Excellent (A)\n");
printf
break;
;
de
efault:
f("You have inputted false
printf f grade\
\n");
break;
; // break isn’tt necessary here
}

6
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.
• Case labels must be con
nstant or cons
stant expression.
• Case labels must be uniique.
• Case labels must end with colons.
• The break statement is optional.
• The defaullt case statem
ment is optiona
al.
• Nesting of switch statem
ment is allowe
ed.

6 e difference between if-e


State else and swittch-case

if-else 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 can have valu


ues based on constraints.
c Swiitch can have values based on user choic
ce.

If implements Linear
L search. Swiitch implemen
nts Binary search.

Flo
oat, double, char, int and other data type
es can Only int and charr data types can be used in switch
be
e used in if con
ndition. bloc
ck.

Write a C Pr
rogram to….

1 Find out whetherr the given number


n is od
dd or even.

#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
pr s odd");
}

2 Find maximum number from given 3 num


mbers.

#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 which asks day number


n and prints
p corres
sponding day
y name using
g switch-cas
se.

#incl
lude<stdio.h>
void main()
{
int day;
enter day number
printf("e n (1-7)
) \n");
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
printf y");
break;
;
ase 6:
ca
f("friday");
printf
break;
;
ase 7:
ca
f("saturday
printf y");
break;
;
efault:
de
f("wrong input");
printf
}
}

8
Darshan Institute of Engineering & Technology Syllabus for 1st midsem exam

Computer Programming and Utilization (CPU) – 110003

E) Loop Control Structure (for, while, do…while)

1 Explain loops available in C with example

• Loops are used to repeat execution of a block of code.


• During looping, a set of statements are executed until some condition for termination is encountered.

Generally, looping process would include the following four steps


1) Initialization of a counter
2) Test for a termination condition
3) Loop body statements
4) Increment the counter

C supports three types of looping


while loop
• The simplest of all looping structure is while statement.
• The general format of the while statement is:
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.

Example: To print first 10 positive integer numbers


void main()
{
int i;
i = 1; \\ initialization of i
while(i <= 10) \\ condition checking
{
printf(“\t%d”,i); \\ statement execution
i++; \\ increment of control variable
}
}

1
Darshan Institute of Engineering & Technology Syllabus for 1st midsem exam

do…while loop
• In contrast to while loop, the body of the do…while loop is executed first and then the loop condition is
checked.
• The body of the loop is executed at least once because do…while loop tests condition at the bottom of
the loop after executing the body.
• do…while loop is also known as exit control loop because first body statements are executed and then
control-statement is executed, thus condition checking happens at exit point.
• The general format of the do…while statement is:

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
• for loop provides a more concise loop control structure.
• The general form of the for loop is:
for (initialization; test condition; increment)
{
body of the loop;
}
• When the control enters for loop, the variables used in for loop is initialized with the starting value such
as i=0, count=0. Initialization part will be executed exactly one time.
• Then it is checked with the given test condition. If the given condition is satisfied, the control enters into
the body of the loop. If condition is not satisfied then it will exit the loop.
• After the completion of the execution of the loop, the control is transferred back to the increment part of
the loop. The control variable is incremented using an assignment statement such as i++
• If new value of the control variable satisfies the loop condition then the body of the loop is again
executed. This process goes on till the control variable fails to satisfy the condition.
• For loop is also entry control loop because first control-statement is executed and if it is true then only
body of the loop will be executed.

2
Darshan Institute of Engineering & Technology Syllabus for 1st midsem exam

Example: // The following is an example that finds the sum of the first ten positive
integer numbers
void main()
{
int i; //declare variable
int sum=0;
for(i=1; i < = 10; i++) // for loop
{
sum = sum + i ; // add the value of i and store it to sum
}
printf(“%d”, 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 do…while Loop

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


{ while(i<=10) do
sum = sum + i ; { {
} sum = sum + i; sum = sum + i;
i ++; i ++;
} } while(i<=10);

2 State the difference between entry control loop and exit control loop.

Entry control loop Exit control loop


Entry control loop checks condition first and then Exit control loop first executes body of the loop and
body of the loop will be executed. checks condition at last.
Body of loop may or may not be executed at all. Body of loop will be executed at least once because
condition is checked at last.
for, while are example of entry control loop. Do…while is example of exit control loop.

3 Explain break, continue, goto with example.

• Sometimes it is required to quit the loop as soon as certain condition occurs.


• For example, consider searching a particular number in a set of 100 numbers, as soon as the search
number is found it is desirable to terminate the loop.
• A break statement is used to jump out of a loop.
• A break statement provides an early exit from for, while, do…while and switch constructs.
• A break causes the innermost enclosing loop or switch to be exited immediately.

Example : Read and sum numbers till -1 is entered


void main()
{
int i, num=0;

3
Darshan Institute of Engineering & Technology Syllabus for 1st midsem exam

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.

Example: Following program prints 10,9,8,7,6,5,4,3,2,1


void main ()
{
int n=10;
loop:
printf(“%d,”,n);
n--;
if (n>0)
goto loop;
}
Please refer book for flowchart or diagram of break, continue, goto. Page No: 167

4
Dars
shan Instittute of Eng
gineering & Technology yllabus for 1st midsem exam
Sy m

Compute
er Programm
ming and Uttilization (CP
PU) – 11000
03

F)
) Array and String

1 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 s of the same data type.
n of elements
• An array is derived 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.
• An array is very useful when you
y are workin
ng with seque
ences of the sa
ame kind of data.
• An array makes program easie
er to read, wrrite and debug
g.

Examp
ple:
#include<s
stdio.h>
void main()
{
int a[5] = {5,12,20,54,68
8}, i;
(i=0;i<5;i+
for( ++)
{
“%d”, a[i]);
printf(“
}
}

Types of
o an array:
1) Single dimension
nal array
2) Two
o dimensional array
3) Mullti dimensiona
al array

1
Dars
shan Instittute of Eng
gineering & Technology yllabus for 1st midsem exam
Sy m

2 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];

• An individual array element ca


an be used anywhere like a normal variable with a sta
atement such as
g = marks [60];
Morre generally if i is de
eclared to b
be an integ
ger variable, then the s
statement g=m
marks[i];
will take the valu a ith position in an array an
ue contained at nd assigns it to g.
• 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 ored at 60th position in an array.
95 is sto 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.
• Forr example we can very easily sequence through
t the elements
e in the array by va
arying the value of the
varriable that is used
u as a subs
script into the array.
for((i=0; i<66; i+
++);
sum = sum + marks[i];
Abo
ove for loop will
w sequence through
t the firrst 66 elemen
nts of the marks array (elem
ments 0 to 65) and will
add
d the values of
o each marks into sum. Wh
hen for loop is
s finished, the
e variable sum
m will then contain the
tota
al of first 66 values
v of the marks.
m
• 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]]

ngle Dimensiional array:


Initialization of Sin
The gen
neral form of initialization
i o array is:
of
data_type arrray_name[siz
ze]={list of va
alues};
There are
a three ways
s to initialize single
s dimensiional array,
1. 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 e 0th element to 1, 1st element to 5 and 2nd
xed to 3 then it will initialize
will be fix
ment to 6
elem

2
Dars
shan Instittute of Eng
gineering & Technology yllabus for 1st midsem exam
Sy m

Two dimensional arrays:


a
• 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];

• Herre m is declarred as a matrrix having 10 rows (numbe


ered from 0 to
t 9) and 20 columns (num
mbered 0
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]
• 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
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

Initialization of two dimension


nal array:
1. int
t table[2][3
3] = {1,2,3
3,4,5,6};
will initialize 1st row
r 1st column 1 1st row 2nd column to 2, 1st row 3rd collumn to 3, 2ndd row 3rd
n element to 1,
umn to 6 and so on.
colu
2. int
t table[2][3
3] = {{1,2,3},{4,5,6})
);
herre, 1st group is
s for 1st row and 2nd group is for 2nd row.. So 1st row 1st
s
ment is 1, 2nd row 1st
column elem
umn element is 4, 2nd row 3rd column ele
colu 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.

3 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 M
Meaning
strlen((s1) 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

3
Dars
shan Instittute of Eng
gineering & Technology yllabus for 1st midsem exam
Sy m

printf(“%d””, strcmp(s1,s
s2));
Output : -9
9
strcpy
y(s1,s2) Copies 2nd string to 1st sttring.
strcpy(s1,s
s2) copies the string s2 in to string s1 so s1 is now “Th
here”.
s2 remains
s unchanged.
strcat((s1,s2) Appends 2nd
n
e end of 1st sttring.
string at the
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) Reverses given string.
strrev(s1); makes string
g s1 to “riehT””
strlwr((s1) Converts sttring s1 to low
wer case.
printf(“%s””, strlwr(s1)); Outp
put : their
strupr(s1) Converts sttring s1 to upper case.
printf(“%s””, strupr(s1));; Outp
put : THEIR
strncp
py(s1,s2,n) Copies firstt n character of
o string s2 to
o string s1
s1=””; s2=
=”There”;
strncpy(s1,,s2,2);
printf(“%s””,s1);
Output : Th
h
strncat(s1,s2,n) Appends firrst n characte
er of string s2 at the end of string s1.
strncat(s1,s2,2);
printf(“%s””, s1);
Output : Th
heirTh
strncm
mp(s1,s2,n) Compares first n chara
acter of string
g s1 and s2 and returns similar result as
strcmp() fu
unction.
printf(“%d””, strcmp(s1,s
s2,3));
Output : 0
strrchrr(s1,c) Returns the
e last occurrence of a given
n character in a string s1.
printf(“%s””,strrchr(s2,’e’));
Output : erre

4
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

1 Whatt is user defined function


n? Explain with example.. Define the syntax
s of fun
nction in C.

• A function is a block of code that performs a specific task.


• Th
he functions which
w are crea ammer are called user-defined functions.
ated by progra
• Th
he functions which
w are in-b er are known as system fun
built in compile nctions.
• Th
he functions which
w are implemented in header
h librarie
es are known as
a library func
ctions.
• Itt has a unique
e name and it is reusable i.e
e. it can be ca
alled from any
y part of a pro
ogram.
• Pa
arameter or argument pass
sing to functio
on is optional.
• Itt is optional to return a va
alue to the ca
alling program
m. Function which is not re
eturning any value
v from
fu
unction, their return type is
s void.

While using function, three thing


gs are importa
ant
1. Function Declaration
• Like va
ariables, all th
he functions must
m be declarred before the
ey are used.
• The function declara
ation is also known
k ction prototype or function signature. It consists of
as func
four pa
arts,
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);
• In this example, fun
nction return type
t is int, name of function is sum, 2 pa
arameters are
e passed to
functio
on and both arre integer.

2. Function Definition
• Functio
on Definition is
i also called function
f imple
ementation.
• It has mainly two pa
arts.
• Function headerr : It is same as function de
eclaration butt with argument name.
• Function body : It is actual logic or codin
ng of the func
ction

3
3. Function call
c
• on is invoked from main fun
Functio nction or othe
er function tha
at is known as
s function call..
• Functio
on can be callled by simply nction name followed by a list of actual argument
y using a fun
enclose
ed in parenthe
eses.

1
Darshan Insttitute of En
ngineering & Technology S
Syllabus for 1st midsem exa
am

Syntax or general structure


s of a Function
<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
esult = x + y;
re
re
eturn (resul
lt);
}

2 ain different categories of


Expla o functions.

Functiions can be cllassified in on


ne of the follow
wing category
y based on wh
hether arguments are present or not,
wheth
her a value is returned or not.
1. 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 eive any data from calling fu
nction has no argument, it does not rece 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.
• In fact therre is no data transfer
t betwe
een the calling
g function and
d called function.

2
Darshan Insttitute of En
ngineering & Technology S
Syllabus for 1st midsem exa
am

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() No void Fun1
1()
pr
rintf("\n GT
TU \n");
{ Input {
} ……………… ……………
……………… ……………
void prin
ntline(void)
)
Fun
n1() ……………
{ ……………… ……………
……………… }
in
nt i;
} No
fo
or(i=0;i<10;
;i++)
Output
{
printf
f("-");
}
}
2. Fu
unction with no
n arguments and return a value
• nction has no argument, it does not rece
When a fun eive data from
m calling functiion.
• nction has return value, the
When a fun 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
void main
n() No int Fun1()
m=
=get_number(
();
{ Input {
pr
rintf("%d",m
m); …………… ……………
…………… ……………
} ……………
a = Fun1
1()
int get_n
number(void)
) …………… return no;
…………… }
{ Function
}
nt number;
in 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 gument, it receives data fro
nction has arg 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
Darshan Insttitute of En
ngineering & Technology S
Syllabus for 1st midsem exa
am

#include<
<stdio.h>
#include<
<conio.h>
void sum(
(int,int); // Argument
void main
n()
{
in
nt no1,no2;
pr
rintf("enter
r no1,no2:"); void main() Value of void Fun
n1(int a)
{ argument {
sc
canf("%d%d",
,&no1,&no2); ……………
………………
su
um(no1,no2);
; ……………… ……………
Fun11(a) ……………
}
……………… ……………
void sum(
(int no1,int
t no2) ……………… }
{ } No return
n
value
f(no1>no2)
if
printf
f("\n no1 is
s gretest");
el
lse
printf
f("\n no2 is
s gretest");
} //
/ No return value

4. Fu
unction with arguments
a and
d one return value
v
• When a fun gument, it receives data fro
nction has arg om calling func
ction.
• nction has return value, the
When a fun 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:");
void main()) Value of in
nt fun2(f)
sc
canf("%d",&n
no); { gument
arg {
…………… …
……………
x=
=sum(no);
…………… …
……………
pr
rintf("sum=%
%d",x); a)
b = Fun1(a …
……………
…………… re
eturn(e)
ge
etch();
…………… }
} } Fu
unction
int no)
int sum(i r
result

{
in
nt add=0,i;
wh
hile(no>0)
{
i=no%1
10;

4
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
• To receive more than on
ne value from function, we have to use pointer.
p
• 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 nction during function callin


ssed to the fun 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)
int max(i y // 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
Call by
b value
• 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 ed parameter, those chang
of passe 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

6
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 ant to change the value of local variables
ce is used whenever we wa 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 alue inside the swap function”);
rintf(“\n Va 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 Whatt do you mea


an by recursiive function?
? Explain witth example.

7
Darshan Insttitute of En
ngineering & Technology S
Syllabus for 1st midsem exa
am

• Recursive function is a function that calls itself.


• on calls itself then it is know
If a functio wn as recursio
on.
• Recursion is thus the prrocess of defin
ning somethin
ng in terms of itself.
• 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
• Terminating condition must
m be there which
w can terminates the chain
c of proces
ss, otherwise it will lead
to infinite number
n of pro
ocess.
Pictorial presentatio
on of recursion.
fact(4)

f=1;
if(…..)
……..;
f=4*fac ct(3)

return 24;
2
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

8
Darshan Insttitute of En
ngineering & Technology S
Syllabus for 1st midsem exa
am

Example: Find facto


orial of a given number usin
ng recursion.
#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
• Easy solution for recursively defined solution.
s
• Complex programs can be
b easily writtten with less code.
c
Disadv
vantages
• Recursive code
c is difficult to understand and debug
g.
• Terminating condition is must; otherw
wise it will go in an infinite loop.
• Execution speed
s decreas o function calll and return activity many times.
ses because of t

5 Whatt is scope, liffetime and viisibility of va


ariable?

Scope
e
• The scope of variable can
c be defined
d as that a part
p of a prog
gram where th
he particular variable is
accessible
• In what part of the program the varia
able is accessible is depends on where th
he variable is declared.
d
• Local varia
ables which arre declared in
nside the body
y of function cannot
c be acc
cessed outside
e the body
of function.

9
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
• Lifetime is a time limit during
d the program executio
on until which
h a variable ex
xist in a memo
ory.
• It is also re
eferred to the longevity of variable.
v

Visibility
• Visibility is the ability of the program to access a variable from the
t memory.
• ope of variablle, the variable losses the visibility in th
If variable is redeclared within its sco he scope of
variable wh
hich is redecla
ared.

10
Darrshan Institute of Eng
gineering & Technolo
ogy 2nd Mids
sem Syllabu
us

Computer Prrogramming and Uttilization (CPU) – 11


10003
Pointers
s

1 What is pointer? How to dec


clare and initialize it?

• s a variable that contains address or lo


A pointer is ocation of ano
other variable
e.
• Pointer is a derived dataa type in C.
• Pointers coontain memo ory address as their va alues, so theey 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
• p is integer pointer variable
• & is address of or re eferencing opperator whichh returns memmory address s of variable
• * is ind
direction or deereferencing operator which returns va alue stored at
a that memo ory address
• & opera ator is the inv
verse of * opperator ( x = a is same as
s x = *(&a))

Variable Valu
ue Address

a 10 5000

p 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; // Declaares pointer variable
v p andd regular varriable a and x
p = &a // Initializes p with address
a of a
x = *p; // p conntains address of a and *p p gives value stored at tha
at address.

1
Darrshan Institute of Eng
gineering & Technolo
ogy 2nd Mids
sem Syllabu
us

2 How pointer
p is diifferent from
m array?

Array Pointer
Arrray is a constant 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 meemory space which canno
ot Alloc
cated memorry size can be
e resized.
resize or reassig
gned.
It is
s a group of elements.
e It is not a group of elements. It is single variable.
v

3 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 arraay can alwayss 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+i:

. .
. .
. .

a[9] *(a+9) 2018


a+9:

4 Explain Array of Pointers


P

As wee have an arrray of char, int, float ettc…, same way


w we can have an array of pointe ers, individua
al
elements of an array will store the address values. So, array
a of pointers is a colle
ection of poin
nters of same
e
type known
k by sing
gle name.

2
Darrshan Institute of Eng
gineering & Technolo
ogy sem Syllabu
2nd Mids us

x :
Syntax
data_type *name[size];;
Examp
ple :
int *ptr[5];; \\Declarres an array of integer po
ointer of size 5
int mat[5][[3]; \\Declarres a two dim
mensional arrray of 5 by 2

Now, the
t array of pointers
p ptr can
c be used to point to diffferent rows of
o matrix as follow
f

0;i<5;i++)
for(i=0
{
at[i][0];
ptr[i]=&ma \\ Can be re-written as ptr[i]=mat[i];
p ;
}
ptr 0 1 2
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 wo variables using pointter. OR


Swap value of tw
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 numbeers:");
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;
}

3
Darrshan Institute of Eng
gineering & Technolo
ogy 2nd Mids
sem Syllabu
us

6 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[100], sum=0, i;
p=a;
printf("Enteer 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();
}

4
Darrshan Institute of Eng
gineering & Technolo
ogy 2nd Midsem Syllabu
us

Computer Prrogramming and Uttilization (CPU) – 11


10003
Sttructure, Union
U

1 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 x data in a more meaningful way.
anize complex
x of Structure
Syntax e:
struct struc
cture_name
{
datta_type mem
mber1;
datta_type mem
mber2;
……
……….
};
• struct is a keyword.
• _name is a tag name of a structure.
structure_
• member1, member2 arre members of
o 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");
anf(“%s”,book1.title);
sca
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);

1
Darrshan Institute of Eng
gineering & Technolo
ogy 2nd Midsem Syllabu
us

prin
ntf("%d",boo
ok1.pages);
prin
ntf("%f",book
k1.price);
gettch();
}
• ucture whose
book is stru e members arre title, autho
or, pages and
d price.
• book1 is a structure varriable.

2 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;
We can declare structure variab
ble in two way
ys
1) Just after the structure body like boo
ok1
2) With structt keyword and
d structure ta
ag name like book2
ssing structu
Acces ure memberrs:
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.
• The “.”(dott) operator orr ‘period operrator’ connec
cts the memb
ber name to structure
s nam
me.
• for ex:
book1.price
e represents
s price of boo
ok1
We can assign valu
ues to the me
ember of the structure varriable book1 as below,
strcpy(book1.title,”ANSI C”);
strcpy(book1.author,”Balagurusamy
y”);
book1.page
es=250;
book1.price
e=120.50;

2
Darrshan Institute of Eng
gineering & Technolo
ogy 2nd Midsem Syllabu
us

We can also use sc


canf function to assign value through a keyboard.
scanf(“%s””,book1.title);
scanf(“%d””,&book1.pag
ges);

3 What is Union?

• ser defined da
Union is us ata type just like structure
e.
• gned its own unique storrage area wh
Each member in structture is assig here as in Union,
U all the
e
members share
s commoon storage are ea.
• All memberrs share the common
c area
a so only one
e member can
n be active at a time.
• Unions are used when all e at the same time.
a the members are not assigned value
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
Each member is assigned
a its own
o unique All members
m sharre the same storage
s area.
storage area.
Total memory req
quired by all members
m is Maximum memorry required by
y the membe
er is
ated.
alloca allocated.
All members
m are active
a at a tim
me. Only one member is active a time.
t
All members
m can be initialized.. Only the first mem
mber 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 ytes for c,b,a
4 by a a c
2 by
ytes for a b
4 by
ytes for b

Total bytes = 1 + 2 + 4 = 7 bytes. 4 byttes are there between


b a,b and
a c becausee
large
est memory oc ccupies by floa
at which is 4 bytes.
b

3
Darrshan Institute of Eng
gineering & Technolo
ogy 2nd Midsem Syllabu
us

5 Explain nested sttructure witth example

• 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();
}

4
Darrshan Institute of Eng
gineering & Technolo
ogy 2nd Midsem Syllabu
us

6 Explain Array of Structure


S w
with Example
e?

• As we have
e an array of basic data ty
ypes, same way
w we can ha
ave an array variable of structure.
s
• It is better to use array of size 66 in
nstead of 66 variables
v to store
s result off 66 student.

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);
}
printf("\n detail
d of stude
ent:\n");
for(i=0;i<6
66;i++)
{
ntf(“%s”,r[i]..name);
prin
ntf("\t%d",r[i].rollno);
prin
ntf("\t%f\n",r[i].cpi);
prin
}
getch();
}

5
Darsh
han Institu
ute of Engin
neering & T
Technology
y
 

 
Computer Progra
amming a and Utiliza
ation (CP
PU) ­110003 
J) File  Handlingg 

Fille Manage
ement 
• In real life, we want tto store data permanentlyy so that laterr on we can reetrieve it and reuse it. 
• A file is aa collection o
of bytes stored on a second dary storage device like haard disk, pen drive, and tape. 
• There arre two kinds o of files that p
programmers deal with texxt files and bin nary files. 
• Text file are human rreadable and it is a stream of plain Engllish characterrs. 
• Binary fiiles are not human readab ble. It is a streeam of processsed characteers and Ascii ssymbols. 

Fille Opening
g Modes 
• We wannt to open file
e for some purpose like, reead file, create new file, ap ppend file, reaad and write file, 
etc… 
• When wwe open any ffile for processsing, at that ttime we havee to give file o
opening mode e. 
• We can do limited opperations onlyy based on m mode in which h file is opened. 

e.g.   fp = fope
en(“demo.t
txt”,”r”); //H pened in read only mode.
Here file is op

C has 6 diffeerent file open
ning modes for text files,

1. r    open for readding only. 
2. w  open for writting (If file exists then it is overwritten) 
3. a  open for app
pending (If file e does not exist then it creeates new filee) 
4. r+  open for readding and writting, start at b beginning 
5. w+  open for readding and writting (overwritte file) 
6. a+  open for readding and writting, at the en nd (append if file exists) 

Same modes are also sup
pported for binary files by just adding b
b, e.g. rb, wb,
w ab, r+b,
r w+b, a+b

Wrrite a C program to d
 display fille on scree
en. 
#inclu
ude <stdio.h>
void main()
m
{
FILE *fp;; // fp is file pointerr. FILE is a sttructure defin
ned in stdio.h

char ch ;

fp = fope
en(“prog.c c”, “r”); // Open Pr rog.c file in read only mo ode.
c = getc(
(fp) ;
while (ch
h != EOF) // EOF = Ennd of File. Reaad file till end
d
{
putcchar(ch);
ch = getc (f fp);
//Reads single chaaracter from file and advances position n to next charracter
}
p);
fclose(fp // Close thee file so that others can acccess it.
}
Darsh
han Institu
ute of Engin
neering & T
Technology
y
 

 
 

Wrrite a C program to c
 copy a file
e. 
#inclu
ude <stdio.h>
void main()
m
{
FILE *p,**q;
char ch;
p = fopenn(“Prog.c”
”,"r");
q = fopenn(“Prognew
w.c”,"w");
ch = getcc(p);
while(ch != EOF)
{
putc
c(ch,q);
ch = getc(p);
}
printf("FFile is co
opied suc
ccessfully
y. ");
fclose(p);
fclose(q);
return 0;;
}

Ex
xplain file h
 handing fu
unctions w
 with example. 
C provides a set of functions to do operatiions on file. TThese functions are known
n as file handlling functionss. 
Eacch function is used for som
me particular p
purpose. 

fop
pen()  (Open file)  
• fopen is used to open a file for operattion. 
• Two argumeents should be supplied to o fopen function,  
• File name orr full path of ffile to be ope
ened 
• File openingg mode which h indicates wh hich type of ooperations aree permitted o
on file. 
• If file is open
ned successfu
ully, it returnss pointer to fiile else NULL. 

Exaample: fp = fope
en(“Prog.c
c”,”r”); me is prog.c and it is opened for readiing only. 
// File nam
fclo
ose()  (Close file)  
• Opened filess must be closed when operations are o over. 
• The function n fclose is use
ed to close the file i.e. indicate that we are finished p
processing th
his file. 
• To close a file, we have to o supply file p
pointer  to fcllose function. 
• ed successfully then it retu
If file is close urns 0 else EO OF. 

Exaample:  p);
fclose(fp
fprrintf()  (Write form
matted outpu
ut to file) 
• The fprintf ffunction printts information n in the file acccording to th
he specified fformat. 
• fprintf() worrks just like prrintf(), only difference is wwe have to pass file pointer to the functtion. 
• It returns the number of characters ou utputted, or aa negative nu umber if an errror occurs. 

Exaample: fprintf(f
fp ”Sum = %d” su
um);
Darsh
han Institu
ute of Engin
neering & T
Technology
y
 

 
fscanf()  (Read form
matted data f
 from file) 
• The function ds data from the given filee. 
n fscanf() read
• It works in aa manner exacctly like scanff(), only differrence is we have to pass fiile pointer to the function. 
• If reading is succeeded th hen it returnss the number of variables tthat are actuaally assigned values, or EO OF if any 
error occurrred. 

Exaample:  fscanf(fp
p, ”%d”, &sum); 
&
fse
eek()   (Reposition
n file  positio
on indicatorr) 
• Sets the possition indicatoor associated with the file pointer to a n
new position defined by ad
dding offset tto a 
reference po osition speciffied by origin.. 
• You can use  fseek() to mo ove beyond aa file, but not before the beginning. 
• fseek() clearrs the EOF flagg associated with that file. 
• We have to supply three arguments, ffile pointer, h how many chaaracters, from
m which location.  
• ero upon succcess, non‐zero
It returns ze o on failure.

Thee origin value should haave one of the e following vaalues 
Namme     Explanation 
SEE EK_SET   Seek from th he start of thee file 
SEE EK_CUR   Seek from th he current location 
SEE EK_END   Seek from th he end of the file 
 
Exaample:   fseek(fp, ,9,SEEK_SE ET); // Mo oves file positiion indicator to 9th position from begging. 
ftelll()    (Get curren
nt position in
n file) 
It re
eturns the current value o
of the position
n indicator off the file. 

Forr binary stream e returned corresponds to the number of bytes from
ms, the value m the beginnin
ng of the file. 

Exa
ample: position = ftell (fp);
(
rew
wind()  (Set positio
on indicator  to the begin
nning) 
• Sets the possition indicato
or associated with file to th
he beginning of the file. 
• wind is equivalent to:
A call to rew fseek (fp p, 0, SEEK K_SET);  
• On file openn for update (read+write), a call to rewind allows to switch betweeen reading and writing. 

Exaample:  rewind (f
fp); 
gettc()    (Get characcter from file
e) 
• getc function returns thee next charactter from file o
or EOF if the eend of file is rreached. 
• After reading a characterr, it advances position in file by one chaaracter. 
• getc is equivvalent to getcchar(). 
• fgetc is identical to getc. 

Exaample:  ch = getc
c(fp);

puttc()    (Write charracter to file
e) 
• o the file and advances thee position ind
putc writes aa character to dicator.  
• After reading a characterr, it advances position in file by one chaaracter. 
Darsh
han Institu
ute of Engin
neering & T
Technology
y
 

 
• putc is equivvalent to putcchar(). 
• fgetc is identical to putc. 

Exaample:  putc(ch, fp);


f

gettw()    (Get intege
er from file)  
• getw functio
on returns thee next int from the file. If eerror occurs tthen EOF is reeturned. 

Exaample: i = getw(
(fp);

puttw()   (Write integ
ger to file)  
• putw functio
on writes inte
eger to file an
nd advances indicator to next position.
• It succeeded
d then returns same intege er otherwise EOF is return
ned. 

Exaample:  putw(I, fp); 


f

Wrrite a prog
gram to co
ount the nu
umber of l
 lines, tabss, characte
ers and wo
ords in a fiile. 
#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] ;
f(“Enter file name
printf e: “);
gets( filename ); /// You can also o use scanff(“%s”,fil lename);
fp = fopen(
f filename, “r”
“ );
if ( fp
f == NULL ) /// File is not opened successsfully then it returns NULL. 
{
printf(“CCannot 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 );
f(“Lines=%d Tabs=%
printf %d Wods=%d
d Characters=%d”, lines, ta
abs, words,
charac
cters);
}
Darsh
han Institu
ute of Engin
neering & T
Technology
y
 

 
Computer Progra
amming a
 and Utiliza
ation (CP
PU) ­110003 
K) D
Dynamic M
 Memory A n, Storage Classes 
Allocation

Static  Memory  Allocatio
on  Dynam
mic Memo
ory Alloca
ation 
• d  to  variablees  before  •
If  memory  is  allocated If  memory  is  allocatted  at  runtime  (during 
execution  of 
o program  starts  then  it  is  called  n of program) then it is called dynamic 
execution
static memo
ory allocation.  memory.
• It is fast and
d saves runnin
ng time.  • It is bit slo
ow. 
• It allocates m
memory from
m stack.  • It allocatees memory fro
om heap 
• e  of  an  array  is known  •
It  is  preferreed when  size It is preferred when nu
umber of variables is not 
in  advance  or  variabless  are  require
ed  during  known in advance or vvery large in size. 
most of the time of execu
ution of program. 
• Allocated  memory 
m t end  of  •
stayss  from  start  to  Memory ccan be allocaated at any time and can 
program.  be releaseed at any time. 
• The  storagee  space  is  given 
g olic  name  •
symbo The  storaage  space  alllocated  dynaamically  has 
known  as  variable  and  using 
u this  variable  we  no  name
e  and  thereefore  its  value  can  be 
can access vvalue.  accessed only through a pointer. 
• e.g.   • e.g. 
  int i;    p = malloc(sizeof(in
nt)); 
  float j; 

Ex
xplain varrious funcctions use
ed in Dyna
amic Mem
mory Allo
ocation. 
ma
alloc( ) 
• malloc()) is used to allocate a certaain amount byytes of memo
ory during thee execution o of a program.
• malloc()) allocates siize_in_byt tes bytes of memory from m heap, if thee allocation su
ucceeds, a po
ointer to 
the blocck of memoryy is returned e else NULL is reeturned. 
• malloc()) returns an uninitialized m
memory for yo ou to use.
• Malloc()) can be used to allocate space for complex data typ pes such as structures. 
• Syntax:    ptr_ _var = (c cast_type *)malloc( (size_in_ _bytes); 
• Example e : 
#inc clude<std dio.h>
int main()
{
int *p ;
p = (in nt *)malloc(sizeof f(int));
*p =25; ;
printf( (“%d”,*p);
free(P) );
}
callloc( ) 
• calloc() is used to alloocate a block of memory d
during the exeecution of a p
program, e.g. for an array.
• calloc() aallocates a reegion of memory large eno
ough to hold n no_of_blo ocks of size s size_of_bl lock 
each, if tthe allocationn succeeds th of memory iss returned elsse NULL is returned. 
hen a pointer to the block o
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); 
• Examplee: 
#inc
clude<stddio.h>
int main ()
{
n;
int i,n
int *pp;
printf ("Enter how many numbers:"
");
scanf ("%d",&n)
( ;
nt*) calloc (n, si
p = (in izeof(int)
));

for (i=
=0; i<n; i++)
{
scanf(“%d”
”,p);
p
p++;
}
}
rea
alloc( ) 
• realloc()) reallocates aa memory blo ock with a sppecific new sizze. If you calll realloc(), thee size of the  memory 
block po ointed to by tthe pointer is changed to tthe given sizee in bytes. Thiis way you arre able to exp pand and 
reduce tthe amount o of memory yo ou want to use. 
• 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  too  new  memo ory  and  old  memory  is  released 
automattically. 
• The content will remain unchangeed means it iss copied to neew location.
• If the po ointer is NULLL then the reaalloc() will behave exactly like the mallo oc(). It will asssign a new block of a 
size in bytes and will return a poin nter to it. 
• Syntax:    ptr_v var=* reallo oc ( void * ptrr, size_t size );; 
• Example e: 
#inc clude<std dio.h>
int main()
{
int *p ;
p = (in nt *)malloc(sizeof f(int));
*p =25; ;
p = (in nt *)realloc(p, 2 * sizeof( (int));
printf( (“%d”,*p);
free(P) );
}
fre
ee( ) 
• When th he memory iss not needed anymore, you must releasse it calling th
he function free. 
• Just pass the pointer of the allocated memory to free function and mem mory is releaseed.
• Syntax:    void d free(vo oid *point ter); 
• Examplee:  free e(p); 

   
Darsh
han Institu
ute of Engin
neering & T
Technology
y
 

 
Sto
orage Cla
ass 
• Storage class decidess the scope, liifetime and m
memory allocaation of variable. 
• Scope of a variable iss the boundarry within whicch a variable can be used.
• orage classes are available in C, 
Four sto
o Automatic (a auto) 
o Register (reg gister) 
o External (ext tern) 
o Static (static) 

auttomatic: 
• Variablees which are ddeclared in fu
unction are off automatic sttorage class.
• Automatic variables aare allocated storage in th he main memory of the computer. 
• Memoryy is allocated automatically upon entryy to a functio on and freed  automatically upon exit ffrom the 
functionn. 
• The scop pe of automaatic variable iss local to the function in w
which it is declared. 
• It is not required to u
use the keywo ord auto becaause by defau ult storage claass within a b
block is auto.

Exaample: 
int a;
auto int a;

reg
gister: 
• Automatic  variables  are  allocateed  storage  in  the  main  memory 
m of  th
he  computer;;  However,  for 
f most 
compute ers, accessingg data in memmory is considderably sloweer than processing directlyy in the CPU.
• Registerr variables aree stored in registers within
n the CPU where data can be stored and accessed quickly. 
• Variable
es  which  are  used  repeattedly  or  whoose  access  tim
me  should  bee  fast  may  be 
b declared  to 
t be  of 
storage class registerr. 
• Variable
es can be declared as a reggister:   regis ster int var;

extternal: 
• Automatic and registter variables h have limited sscope and lim mited lifetimes in which theey are declareed. 
• Sometimmes we need global variab bles which aree accessible th hroughout the program. 
• extern n keyword deefines a globaal variable thaat is visible to ALL function ns. 
• extern n is also used when our prrogram is storred in multiplle files instead of single filee. 
• Memoryy for such variables is allo ocated when  the program  begins execu ution, and remains allocatted until 
the proggram terminaates.  Memoryy allocated fo or an externall variable is in
nitialized to zeero. 
• Declarattion for exterrnal variable is as follows: extern int var;

sta
atic: 
• static c keyword deefines a globaal variable thaat is visible to ALL function
ns in same filee. 
• Memoryy allocated fo or static variabble is initializeed to zero. 
• Static storage class caan be specifieed for automaatic as well ass external varriables such aas:
static
c extern innt varx; //static ex
xternal
static
c int var; // static a
automatic
• Static au
utomatic variables continu
ue to exist eveen after the ffunction termminates.  
• The scoppe of static au
utomatic variiables is identtical to that o
of automatic vvariables. 
Darsh
han Institu
ute of Engin
neering & T
Technology
y
 

 
Ex
xplain Inp
put / Outp
put functions. 
• C languaage provides  a set of stanndard built‐in
n functions w
which will do tthe work of  reading or diisplaying 
data or information oon the I/O devices during pprogram execcution. 
• O functions esstablish an intteractive com
Such I/O mmunication bbetween the program and d user. 

Fo
ormatted I
  nput/Outp
put functions 
sca
anf(  ) 
• It is usedd to read all ttypes of data.. 
• It cannoot read white space between strings. 
• It can reead multiple d data at a timee by multiple format speciffier in one scaanf( ). 
• Example e:  scan nf(“%d%d” ”, &a, &b) ); 

priintf( ) 
• It is used
d to display all types of data and messaages. 
• It can display multiple data at a tim ple format speecifier in one printf( ). 
me by multip
• Example e:   prin ntf(“a=%d d b=%d”, a a, b); 

Un
nformatted
d input ou
utput functtions 
getts() 
• It is used
d to read a sin
ngle string wiith white spacces. 
• It is term
minated by ennter key or att end of line.
• Example e:  
char str[10];
s
gets(s str);

gettchar(), getcche( ), getch
h( ) 
• d to read singgle character at a time. 
It is used
• getchar(( ) function reequires enter key to terminnate input wh
hile getche( ) and getch( ) does not require. 
• getch( )  function doe es not displayy the input ch
haracter while getchar( ) aand getche( )) function dissplay the 
input chharacter on thhe screen. 
• Example e: 
char ch; c
ch = getchar()
g ;
ch = getche();
g
ch = getch();
g

putts() 
• It is used
d to display a string at a tim
me. 
• Example e: 
char str[]=”He
s llo”;
puts(s str );

puttchar() 
• d to display single character at a time.
It is used
• Example e: 
Darsh
han Institu
ute of Engin
neering & T
Technology
y
 

 
putcha
ar(ch);

Ch
haracter ch
hecking fu
unctions. 
Chaaracter checkking functionss are available
e in ctype.h header file. 

1. isdigit(in
nt);  for checking number (0‐9) 
2. isalpha(int);  for checking letter (A‐Z or a‐z)
3. isalnum(int);  for checking letter (A‐Z or a‐z) or digit (0‐9)
4. isspace(int);  for checking emptty space 
5. islower(int);  for checking letter (a‐z) 
6. isupper((int);  for checking letter (A‐Z) 
7. ispunct(int);  for checking puncctuation symb bols (like ‐  : , ; , {, } , ?, . etcc. ) 

Ex
xample: Wrrite a prog
gram to ch
heck the en
ntered cha
aracter is  digit or no
ot 
#inclu
ude<stdio.h>
ude<conio.h>
#inclu
ude<ctype.h>
#inclu
void main()
m
{
char c;
clrscr();
;
scanf("%c
c",&c);
if(isdigi
it(c))
prin
ntf("True
e");
getch();
}

Potrebbero piacerti anche