Professional Documents
Culture Documents
▼▼
Disclaimer
Please note none of the content or study material in this document or content in this file is prepared or
owned by AceTechie.com. This content is shared by our student partners and we do not hold any
copyright on this content.
Please let us know if the content in this file infringes any of your copyright by writing to us at:
info@acetechie.com and we will take appropriate action.
Darshan Insttitute of En
ngineering & Technology Syllabus
S for 1st midsem exa
am
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
m
ALU + CU
U
INP
PUT SECTIO
ON OUTPUT SE
ECTION
(Mouse
e, Keyboard, ettc...)
o (
(Monitor, Printe
er, etc…)
.c
PR
RIMARY MEM
MORY
(
(RAM, ROM, ettc…)
ie
h
SEC
CONDARY MEMORY
(Hard
d disk, Pen driv
ve, etc…)
c
e
1) Central
C Proce
essing Unit (CPU):-
(
• Central processing unit is a main parrt of the comp
puter system.
• It contains
T
s electronics circuitry
c that p
processes the data based on instructions
s.
e
• It also con
ntrols the flow
w of data in the
e system.
• It is also known
k as brain of the comp
puter.
c
• CPU consis
sts of,
1
1.1) Arithm
metic Logic Un
nit (ALU)
A 9
9
9
Itt performs all arithmetic callculations and takes logical decision.
Itt can perform add, subtractt, multiply, compare, count,, shift and oth
Itt calculates ve
ery fast.
her logical activities.
2) Input
I Section
n:-
• es used to entter data in to computer sys
The device stem are called
d input device
es.
m
• 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
o
• Examples:: Mouse, Keyb
board, Touch s
screen, Joystick etc…
.c
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
ie
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):-
h
• Secondary
y memory is also
a
c
called Aux
xiliary memory
y or External memory.
e
• User can store
s data perrmanently.
• It can be modified
m easily.
•
• T
It can storre large data compared
c to primary
Examples:: Hard disk, Floppy disk, CD
p memo
ory. Now days
D, DVD, Pen drive,
d etc…
s, it is availab
ble in Terabyte
es.
e
c
2 Describe
e advantage
es and limita
ations of co
omputer. Or Explain cha
aracteristics
s of compute
er.
Advantages
• S
s
s
A
Speed:
second
solved
It can calculate millions of expre
units are
a used to measure
within specified
s
m
essions within a fraction of second. The micro
peed of computers. There are
the sp
time limit without computer.
m second and nano
a some problems which cannot
c be
• 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,
m
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
o
has its ow
wn machine la
anguage.
• ADVANTA
AGES:
.c
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.
ie
3. Trans
slation is not required.
4. Suita
able for low vo
olume applicattions.
• DISADVA
ANTAGES:
1.
2. ugging is very difficult task..
Debu h
g and difficult to write and understand
Progrrams are long u for human.
3. It is not portable.
c
e
4. Progrrammer requires detailed k
knowledge of architecture
a o microproces
of ssor.
2) Assembly la
anguage:-
• Every ma
achine langua
T
age instruction
n is assigned to English word
w MNEMON
NIC such that it should
e
describe function of ins
struction.
• System cannot
c unders
stand this language directly
y so we requiire translator that convert assembly
c
language
e to machine la
anguage. This
s translator is called assembler.
• Example : 8086 Instru
uction Set
A
• ADVANTA
1.
2.
AGES:
Progrrams are easy
Progrrams are sma
y to understan t machine level language.
nd compared to
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
Darshan Insttitute of En
ngineering & Technology Syllabus
S for 1st midsem exa
am
m
4 Why C is
s called mid
ddle level lan
nguage?
C is called
d middle levell language bec
cause
o
• 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.
.c
• 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.
ie
• 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.
e
called sofftware.
System Software
S
System software is des
T
signed to operrate the comp
puter hardwarre efficiently. IIt provides an
nd maintains a platform
e
for runnin
ng application
n software. Siince system s
software runs at the most basic level off computer, itt is called
"low-level" software.
c
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
2) SA
to user. It is a bridge betwe
System suppo
ort software: It
een computer hardware and
I makes worrking of hardw
I//O devices or routine for so
ocket program
nux, UNIX, etc…
d user. Ex: Wiindows XP, Lin
ware more effficiently. For example
mming, etc…
e drive
ers of the
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
m
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.
o
5. A
Assembler
A
Assembler is system
s software which conv
verts program
ms of assembly
y language to machine lang
guage.
.c
6. C
Compiler
It translates programs
p of higher level language to ma
achine langua
age. It converrts whole prog
gram at a
ie
time.
7. I
Interpreter
It translates programs of higher level language to mac
chine language. It converts program line by line.
h
c
e
T
e
c
A
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. m
• Easy to show brranching and looping.
l
o
.c
Disadv
vantages
• Tim
me consuming
g.
• Diffficult to modiify.
ie
• ery difficult to draw flowchart for big or complex proble
Ve ems.
h
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
c
in the natural langua
ages like English.
Advan
ntages
• Easy to write.
e
T
• Hu
uman readable
e techniques to
t understand logic.
• Alg
gorithms for big
b problems can
c be written
n with modera
ate efforts.
e
Disadv
vantages
• Diffficult to debu
ug.
•
c
Diffficult to show
w branching an
nd looping.
A
• Jum
mping (goto) makes it hard
d to trace som
me problems.
Compariso
on:
Flowcharrt Algorithm
Easy to sh
how branching
g and looping. Difficult to show branching and looping.
Start / Stop
Input / Output
(Read / Print)
Process
m
Decisio
on making
o
.c
Subrou
utine
ie s
Arrows
h
rite an algo
Wr orithm and
d Draw a flo
owchart
c
e
3 To find wh
hether given
n number is even
e or odd.
Algorithm
m:-
Step 1 : Input no.
T
e
Step 2 : If no mod 2=0, goto 4.
Step 3 : Print given
n no is odd, go
oto 5.
c
Step 4 : Print given
n no is even.
Step 5 : Stop.
A
start
Flowchartt:-
Read
R No
Yes No
Is No
o mod 2=0?
sttop
▼▼ Scroll Down to View your Downloaded File! ▼▼
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
m
Step 11 : Print pos, neg,
n zero.
Step 12: Stop.
Flowchartt:- o
.c
start
ie
posÅ0,neg
gÅ0,zeroÅ0
Read no
h
c
Yes
s
e Is no>0?
n
No
T
e
posÅpos+1
1
Yes Is no<0? No
c negÅ
Åneg+1 zeroÅz
zero+1
A
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.
m
Flowchartt:-
start
o
.c
Read a, b, c
Yes
s
ie
Is
No
h
a > b?
Yes No c Yes No
e
Is Is
a>c? b>c?
T
Print “max =” a
e Print
P “max =”” c Print “max =” b Print “ma
ax=” c
c
A
stop
Darsh
han Institu
ute of Engin
neering & T
Technology
y Syllabus for 1st midsem exam
Flowchartt:-
start
m
Read no
o
co
ountÅ1,factÅ
Å1
.c
ie
h
factt Å fact * count
ccou
unt Å count + 1
e
T Is
e
Ye
es
count<=no?
?
c No
A 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:
Flowchartt:
start
m
o
.c
Read no
o
cou
ie
untÅ1,factÅ1
1,sumÅ0
h
c
fa
actÅfact * co
ount
e s
sumÅsum + fact
T
e c
countÅcount +1
c
A Yes
Y
Is
count<=nno?
N
No
Print sum
m
stop
Darshan Insttitute of En
ngineering & Technology Syllabus
S for 1st midsem exa
am
C) C Fundamen
ntals
1 Explain
n basic structure of ‘C’ program.
ie
area=areao
ofcircle(r);
printf(“Area
a of Circle is :- %f“,area);
h
}
Subpro
ogram Section
n (User Define
ed Section) float areaofcircle(flo
a oat r)
c
Function1() {
Function2() return PI * r * r;
e }
T
2 Explain
n printf() and
e
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
c
writing (printf) forma
atted data to output
o devices
s (monitor).
A
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
1
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)
m
D
Derived data type
o
User defined
d data ttype
.c
(array, pointter) ure, union, enu
(structu um)
ie
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 h
mber without fraction partt. Its range is machine dependent
d
values. C has 3 class
c mely short int, int and long
ses of integerr storage nam g int. All of th
hese data
e
types ha
ave signed and
d unsigned forms.
sig
gned u
unsigned
Size
T Range S
Size Range
e
(bits) (bits)
short int 8 -128 to 127 8 0 to 255
c
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
A
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
2
Darshan Insttitute of En
ngineering & Technology Syllabus
S for 1st midsem exa
am
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
m
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
o
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…
.c
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
ie
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
grouped toge
ether and know h
ollection of log
wn by a single
gically related data items off different datta types
e name.
ii.
c
union: Union is like a struc
cture, except that
t each elem
ment shares the comman memory.
m
e
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
T
the language.
e
Example:
enum day
y {Mon, Tue, Wed, Thu, Fri, Sat, Sun};
c
enum day
y week1stday
y;
week1std
day = Mon;
4 Explain
ConstanA
n types of co
onstant in de
nt is somethin
etail.
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
3
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
m
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:-
o
.c
• 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.
ie
• 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.
h
Single character co
onstant:-
• er enclosed within a pair of single quote mark.
It contains single characte
• Ex: ‘5’, ‘A’, ‘;’, ‘ ‘
c
String constant:-
e
•
•
A string cons
The characte T
stant is a sequ
uence of chara
acters enclose ouble inverted comma.
ed within a do
ers may be lettter, number, special character, blank sp
pace, etc…
• “
e
Ex: “DIET”, “1988”, “?A.B
B,!”, “5+3”, etc…
c
• ‘A’ is charactter but “A” is string.
s
A
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.
4
Darshan Insttitute of En
ngineering & Technology Syllabus
S for 1st midsem exa
am
m
• It is generallly used to sho
ow that functio
on is not returrning anything
g.
o
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
.c
rich set of operators as below,
1. Arithmetic Ope
erators
ie
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)
h
* Multiplic
cation a*b
/ Division a/b
% Modulo division
d
c a % b (this
s operator can
n be used with
h only integer
e
data type)
2. Rellational Operrators
Rela
T
ational operattors are used to compare tw
wo numbers and
a taking dec
cisions based on their relatiion.
e
Rela
ational expres
ssions are use
ed in decision statements su
uch as if, for, while, etc…
< less th
han
c
<=
= less th
han or equal to
o
> greate
er than
>=
=
==
=
!=
=
A 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
5
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.
m
-- 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 o
xpression is ev
valuated.
.c
=10; b=--a; after
Ex. a= a this state
ement, a= 9, b = 9.
6. Con
nditional Ope
erator
ie
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)
h
c
x=a;
else
e
e
x=b;
7. Bitw
wise Operators
Bitw s are used to perform opera
wise operators
T ation bit by biit. Bitwise ope
erators may not be applied to float
e
or double.
d
& bitwise
e AND
|
^ c
bitwise
e OR
bitwise
e exclusive OR
R
8.
<<
<
>>
>
Spe
A shift le
eft ( shift left means
shift right ( shift righ
ecial Operato
ors
m multiply by 2)
ht means divide by 2)
& 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.
6
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
m
evaluated wiithout losing any
a significanc
ce.
• n is known as implicit type conversion.
This automatic conversion c
o
• The lower type is automattically convertted to the high
her type beforre the operation proceeds. The
result is high
her type.
.c
• Example:
o If on
ne operand is int and otherr is float then int will be con
nverted to floa
at.
ie
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.
h long
g double
c double
e
e
float
Conversion
T
Hierarchy unsigned
d long int
e
long int
c
unsigned int
int
A shortt char
7
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.
m
• 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.
o
• 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.
.c
• 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.
ie
• 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.
h
• 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
c
Operattor Des
scription
e
1 Lefft to Right () Func
ction Call
[] Arra
ay Element Re
eference
2 Rig
ght to Left
e
++, -- Increment, Decre
ement
! Logical Negation
c
~ Ones Complemen
nt
* Poin
nter Reference
e (Indirection)
A
& 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
8
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
%=, +=
=, -=,
m
&=, ^=
=, |=,
<<=, >
>>=
15 Lefft to Right , Com
mma Operator
o
.c
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
ie
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
h
es the control to next line.
c
‘\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’
e
Horizontal tab
T
‘\b’ Back space
‘\\’ Prin
nts backslash c
character \
Trigrap
‘\a’
ph characterr:- e Alerrt – provide ed
dible alert.
C introd
c y to enter certtain characterrs which are not
duces conceptt of “trigraph” sequence to provide a way
A
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
9
Darshan Insttitute of En
ngineering & Technology Syllabus
S for 1st midsem exa
am
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
m
• Iff the test expression
e is true, the statement-b
s block will be executed; otherwise the statement-
will be skipped
s and the execution will jump to th
he statement
t-x.
o
b
block
Flowc
chart:
.c
Entry
ie
T
Test True
Exprression?
False
h
Sttatement-bloc
ck
c
e
State
ement-x
Next-s
statement
T
e
mple:
Exam
c
A
#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.
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
uted otherwise false-bloc
m
block state ck
statement is executed.
o
• 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.
.c
Flowc
chart:
Entry
y
ie
h
False True
Test
sion?
Express
c
e
False block T
True-block
T Stateme
ent-x
e Next statement
c
A
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.
m
• 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.
o
• 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
.c
th
he conditions are false, the
en default-statement willl be executed
d.
• E
Else part is opttional in if…els
se…if ladder.
ie
Flowc
chart: Entry
Test
Conditio
on
h
c
True 1 F
False
e
Test
Condition
True False
T
Stattement-1 2
e
Stateme
ent-2 T
Test
Con
ndition
c
True
e 3 False
A Statement-3
True
Test
Condition
N
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");
m
lse if(avg>=
el =50)
printf
f("Second class");
o
lse if(avg>=
el =40)
printf
f("Pass class");
.c
lse
el
f("fail");
printf
ie
}
4 Expla
ain nested if with examp
ple and draw
w flowchart.
h
may have to use more than one if…else statement
s in nested
n form
c
e
if
f(test-conddition-1)
{
if(ttest-conditiion-2)
T
{
Statement-1;
e
}
elsee
{
c
Statement-2;
}
A
}
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
m
Statem
ment-x
o
Next sta
atement
.c
Exam
mple: Find max
ximum numbe ie
er from given three numberrs.
#include<<stdio.h>
h
c
void mainn()
{
e
in
nt a,b,c;
pr
rintf("Enter
r value of a, b, c:");;
T
sc
canf("%d%d%d
d", &a, &b, &c);
if
f(a>b)
e
{
if(a>c
c)
c
printf("a is max");
else
A
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;
m
efault:
de
ments
statem
o
}
• e
expression in switch
s pression. Float or any otherr data type is not allowed.
should be integer or character exp
.c
• 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.
ie
• 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
h
c
switch (g
grade)
{
e
ca
ase 1:
printf
f("Fall (F)\n");
T
break;
;
ca
ase 2:
eprintf
f("Bad (D)\n");
break;
;
cca
ase 3:
f("Good (C)\n");
printf
A
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.
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 implements Linear
L search. Swiitch implemen o
nts Binary search.
Flo
oat, double, char, int and other data type
es can
.c
Only int and charr data types can be used in switch
ie
be
e used in if con
ndition. bloc
ck.
Write a C Pr
rogram to….
T
{
int no;
e
enter no:");
printf("e
scanf("%d
d",&no);
c
if(no%2==
=0)
pr
rintf("no is
s even");
}
A
else
rintf("no is
pr s odd");
#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 ;
}
#incl
lude<stdio.h>
void main()
{
int day;
enter day number
printf("e n (1-7)
) \n");
m
o
scanf("%d
d",&day);
switch(da
ay)
.c
{
ase 1:
ca
f("sunday");
printf
ie
break;
;
ase 2:
ca
h
f("monday");
printf
break;
;
c
ase 3:
ca
f("tuesday");
printf
break;
;
e
T
ase 4:
ca
f("wednesday");
printf
e
break;
;
ase 5:
ca
c f("thursday
printf y");
A
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
m
4) Increment the counter
ie
Initialization;
while (test condition)
{
h
body of the loop ;
increment or decrement;
c
}
• Test condition is evaluated and if the condition is true then the body of the loop is executed.
•
e
After the execution of the body, the test condition is once again evaluated and if it is true, the body
is executed once again.
•
T
This process is repeated till the test condition is true. When it becomes false, the control is
e
transferred out of the loop.
• On exit, the program continues with the statements immediately after the body of the loop.
c
• 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.
A
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;
}
m
o
while(test-condition);
.c
Example: To print first 10 positive integer numbers
void main()
{
ie
int i;
i = 1; \\ initialization of i
do
h
{
printf(“\t%d”,i); \\ statement execution
c
i++; \\ increment of control variable
} while(i <= 10); \\ condition checking
e
}
for Loop
T
e
• for loop provides a more concise loop control structure.
• The general form of the for loop is:
c
for (initialization; test condition; increment)
{
A
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)
o
.c
for( i=1; i < = 10; i++) i=1; i=1;
{ while(i<=10) do
sum = sum + i ; { {
ie
} sum = sum + i; sum = sum + i;
i ++; i ++;
} } while(i<=10);
2
h
State the difference between entry control loop and exit control loop.
e
Entry control loop checks condition first and then Exit control loop first executes body of the loop and
T
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
c
for, while are example of entry control loop. Do…while is example of exit control loop.
A
3 Explain break, continue, goto with example.
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.
•
m
The continue statement tells the compiler, “SKIP THE FOLLOWING STATEMENTS AND CONTINUE WITH
THE NEXT ITERATION”.
o
Example: Find sum of 5 positive integers. If a negative number is entered then skip it.
.c
void main()
{
int i=1, num, sum=0;
ie
for (i = 0; i < 5; i++)
{
scanf(“%d”, &num);
h
if(num < 0)
continue; // starts with the beginning of the loop
c
sum+=num;
}
e
printf(“The sum of positive numbers entered = %d”,sum);
T
}
goto:
e
• 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
c
above or below the goto statement.
• Generally goto should be avoided because its usage results in less efficient code, complicated logic and
A
difficult to debug.
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
m
e int, float or char.
o
• 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:
.c
ie
• 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.
h
• An array makes program easie
er to read, wrrite and debug
g.
c
Examp
ple:
e
#include<s
stdio.h>
void main()
T
{
int a[5] = {5,12,20,54,68
8}, i;
(i=0;i<5;i+
for(
e ++)
c
{
“%d”, a[i]);
printf(“
A
}
}
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.
Syntax : data
a_type arra
ay_name[size
e];
Example : int marks[5];
m
sign
n like marks[6
60]=95; The value
v 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
o
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
.c
varriable that is used
u as a subs
script into the array.
for((i=0; i<66; i+
++);
ie
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
h
c
• 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]]
e
T
values[1]]
values[2]]
e
values[3]]
c
values[4]]
2
Dars
shan Instittute of Eng
gineering & Technology yllabus for 1st midsem exam
Sy m
Syntax : data
a_type arra
ay_name[row_
_size][colu
umn_size];
Example : int marks[10][20];
ie
85.5
5 78.5 65.3
marrks [3][0] marks
s [3][1] marks [3]][2]
h
25.6
6 35.2 76.2
A
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.
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”));
m
Output : he
eir
strrev(s1) Reverses given string.
strrev(s1); makes string
g s1 to “riehT””
o
.c
strlwr((s1) Converts sttring s1 to low
wer case.
printf(“%s””, strlwr(s1)); Outp
put : their
strupr(s1) Converts sttring s1 to upper case.
ie
printf(“%s””, strupr(s1));; Outp
put : THEIR
strncp
py(s1,s2,n) Copies firstt n character of
o string s2 to
o string s1
h
s1=””; s2=
=”There”;
strncpy(s1,,s2,2);
printf(“%s””,s1);
c
e
Output : Th
h
strncat(s1,s2,n) Appends firrst n characte
er of string s2 at the end of string s1.
T
strncat(s1,s2,2);
e
printf(“%s””, s1);
Output : Th
heirTh
strncm
mp(s1,s2,n)
c
Compares first n chara
acter of string
g s1 and s2 and returns similar result as
A
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
m
• 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.
o
.c
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.
ie
• The function declara
ation is also known
k ction prototype or function signature. It consists of
as func
four pa
arts,
h
1) Function ty
ype (return ty
ype).
2) Function name.
3) Parameter list.
c
e
4) Terminatin
ng semicolon
Syntax
x: <retur
rn type> Fun
nctionName (Argument1,
, Argument2,
, Argument3
3……);
Exampl
le: int su
T
um(int , int
t);
e
• 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. c
Function Definition
•
• A Functio
on Definition is
It has mainly two pa
•
i also called function
arts.
f imple
ementation.
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
m
{
in
nt a, b, ans
s;
sc
canf(“%d%d”,
, &a, &b);
o
.c
an
ns = sum(a, b); \ Function
\\ n Calling
pr
rintf(“Answe
er = %d”, ans);
ie
}
int sum (int
( x, int y) \ Function
\\ n Definition
n
{
h
nt result;
in
esult = x + y;
re
re
eturn (resul
lt);
c
e
}
T
2 ain different categories of
Expla o functions.
wheth e
Functiions can be cllassified in on
ne of the follow
her a value is returned or not.
wing category
y based on wh
hether arguments are present or not,
1. Fu
c
unctions with no arguments
s and no returrn value \ void printlin
\\ ne(void)
A
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;
m
} No
fo
or(i=0;i<10;
;i++)
Output
{
printf
f("-");
o
.c
}
}
2. Fu
unction with no
n arguments and return a value
ie
• 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.
h
Examp
ple:
#include<
<stdio.h>
int get_n
number(void)
);
c // No argument
a
e
void main
n()
{
nt m;
in
T void main
n() No int Fun1()
e
m=
=get_number(
();
{ Input {
pr
rintf("%d",m
m); …………… ……………
……………
c
……………
} ……………
a = Fun1
1()
int get_n
number(void)
) …………… return no;
A
…………… }
{ 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
m
f(no1>no2)
if
printf
f("\n no1 is
s gretest");
el
lse
o
.c
printf
f("\n no2 is
s gretest");
} //
/ No return value
ie
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.
h
• nction has return value, the
When a fun e calling functtion receives any
a data from the called fun
nction.
Example:
#include<
<stdio.h>
c
e
#include<
<conio.h>
int sum(i
int); // Argumen
nt
void main
n()
T
e
{
in
nt no,x;
c
cl
lrscr();
pr
rintf("enter
r no:"); Value of in
nt fun2(f)
A
void main())
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);
m
vo
oid main()
{
int x=20,
,y=10,s,d;
o
.c
mathopera
ation(x,y,&s
s,&d);
printf("s
s=%d \nd=%d"
", s,d);
ie
}
vo
oid mathope
eration(int a, int b, int *sum, int
i *diff)
{
h
*sum = a + b;
*diff = a - b;
}
c
3 Expla
ain actual arg
e
gument and formal argument with example.
e
eived in the definition of a function are called
c formal arguments
a or parameters.
c
Examp
ple:
#include<
<stdio.h>
A
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.
m
• 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:
o
.c
#incl
lude<stdio.h
h>
void swap(int, int);
i
ie
void main()
{
h
int x, y;
;
printf("E
Enter the va
alue of X & Y:");
c
scanf("%d
d%d", &x, &y
y);
swap(x, y);
y
printf(“\
\n Values in
e
nside the main
m functio
on”);
T
printf(“\
\n x=%d, y=%
%d”, x, y);
;
getch();
}
e
c
void swap(int x,
,int y)
{
A
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 *);
m
void main
n()
o
{
in
nt x,y;
.c
pr
rintf("Enter
r the value of X & Y:
sc
canf("%d%d",
, &x, &y);
ie
sw
wap(&x, &y);
;
pr
rintf(“\n Va
alue inside the main function”);
f
pr
rintf("\n x=
=%d y=%d", x, y);
h
}
void swap
p(int *x, in
nt *y)
{
c
e
in
nt temp;
te
emp=*x;
*x
x=*y;
T
e
*y
y=temp;
pr alue inside the swap function”);
rintf(“\n Va f
c
pr
rintf("\n x=
=%d y=%d", x, y);
}
Outpu
ut:
A
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
7
Darshan Insttitute of En
ngineering & Technology S
Syllabus for 1st midsem exa
am
.c
f=1;
if(…..)
……..;
ie
f=4*fac ct(3)
return 24;
2
h
fact(3)
f=1;
if(…..)
……..;
c
e
f=3*factt(2)
T
return 6;
6
fact(2)
e f=1;
c
if(…..)
……..;
f=2*factt(1)
A 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
m
int fact(
(int n)
{
in
nt f=1;
o
.c
if
f(n==1)
{
return
n 1;
ie
}
lse
el
h
{
f=n*fa
act(n-1);
return
n f;
c
e
}
}
ntages
Advan
T
e
• Easy solution for recursively defined solution.
s
• Complex programs can be
b easily writtten with less code.
c
c
Disadv
vantages
• Recursive code
c is difficult to understand and debug
g.
•
• A
Terminating condition is must; otherw
Execution speed
s decreas
wise it will go in an infinite loop.
o function calll and return activity many times.
ses because of t
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.
m
o
.c
ie
h
c
e
T
e
c
A
10
Darrshan Institute of Eng
gineering & Technolo
ogy 2nd Mids
sem Syllabu
us
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 m
•
•
p is integer pointer variable
& is address of or re eferencing opperator whichh returns mem o
mory address s of variable
.c
• * 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))
ie
Variable Valu
ue Address
a 5000
h
10
c
e
p
T 5000 5048
e
c
Declaration of po
ointer,
Syntax: data_type *pt_name e;
A
Example: int *p, float
f *q, charr *c;
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.
.c
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.
c
a+1:
e
. .
. .
.
T
.
. .
e a[i] a+i:
*(a+i) 2000+i*2
2
c . .
A
. .
. .
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 m
ptr[0]
o
.c
ptr[1]
ptr[2]
ie
ptr[3]
ptr[4]
5
c
wo variables using pointter. OR
Swap value of tw
Swap value of tw
e
wo variables using call by
b reference
e
#include<stdio.h>
T
e
wap(int *,int *);
void sw
void main()
m
c
{
int a,b;
A
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++)
{
m
sum
m=sum+*p;
p++;
o
}
printf("sum
m=%d", sum));
.c
getch();
}
ie
h
c
e
T
e
c
A
4
Darrshan Institute of Eng
gineering & Technolo
ogy 2nd Midsem Syllabu
us
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
{
m
datta_type mem
mber1;
datta_type mem
mber2;
……
……….
o
.c
};
• struct is a keyword.
• _name is a tag name of a structure.
structure_
ie
• member1, member2 arre members of
o structure.
Examp
ple:
h
stdio.h>
#include<s
#include<c
conio.h>
struct book
k
c
e
{
cha
ar title[100];
cha
ar author[50]];
T
e
int pages;
floa
at price;
};
c
void main()
{
A 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
m
2) The structu
ure tag name
e
3) List of varia
able names separated
s by commas
o
4) A terminatiing semicolon
n
For ex
xample:
.c
k
struct book
{
ie
cha
ar title[100];
cha
ar author[50]];
h
int pages;
floa
at price;
c
} book1;
struct book
k book2;
We can declare structure variab
e
ble in two way
ys
T
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:
e
c
The fo
ollowing synta
ax is used to access the member
m of strructure.
stru
ucture_variab
ble.member_
_name
•
•
A
structure_v
variable is a variable of structure
member off a structure.
s and
d member_na
2
Darrshan Institute of Eng
gineering & Technolo
ogy 2nd Midsem Syllabu
us
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
m
{
ar title[100];
cha
o
cha
ar author[50]];
int pages;
.c
floa
at price;
};
ie
4 Differrence betwe
een Structurre and Union
n
Struc
cture on
Unio
Each member is assigned
a its own
o unique
h All members
m sharre the same storage
s area.
c
storage area.
Total memory req
quired by all members
m is Maximum memorry required by
y the membe
er is
ated.
alloca
e allocated.
T
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.
e Requ
uires less mem
mory.
c
Exam
mple: Exam
mple:
struct SS union
n UU
A
{ {
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
3
Darrshan Institute of Eng
gineering & Technolo
ogy 2nd Midsem Syllabu
us
• 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 m
{
o
.c
char name[100];
struct addrress a;
ie
int salary;
};
void main()
m
{
struct employee e; h
printf("ente
c
er name,addrress,city,salary");
e
scanf(“%s””,e.name);
scanf(“%s””,e.a.add1);
scanf(“%s””,e.a.add2);
T
e
scanf(“%s””,e.a.city);
scanf("%d"",&e.salary);
c
printf("deta
ail of employa
aee:");
A
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
• 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;
m
float cpi;
};
o
void main()
m
{
.c
struct result r[66];
int i;
ie
er detail of sttudent :");
printf("ente
for(i=0;i<6
66;i++)
{
prin
ntf("\nenter name,roll
n
h
no,,cpi");
c
sca
anf(“%s”,r[i]..name);
sca
anf("%d%f",&
&r[i].rollno,&r[i].cpi);
}
e
T
printf("\n detail
d of stude
ent:\n");
for(i=0;i<6
66;i++)
{
e
c
ntf(“%s”,r[i]..name);
prin
ntf("\t%d",r[i].rollno);
prin
} A
getch();
ntf("\t%f\n",r[i].cpi);
prin
5
Darsh
han Institu
ute of Engin
neering & T
Technology
y
Computer Progra
amming aand Utiliza
ation (CP
PU) 110003
J) File Handlingg
Fille Manage
ement
• In real life, we want to
t store data permanentlyy so that laterr on we can reetrieve it and reuse it.
• A file is a collection of
o bytes stored on a second dary storage device like haard disk, pen drive, and tape.
• There arre two kinds of o files that programmers
p deal with texxt files and bin
nary files.
• Text file are human readable
r 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 symbols.
s
Fille Opening
g Modes
• We wannt to open file ppend file, reaad and write file,
e for some purpose like, reead file, create new file, ap
etc…
• When we
w open any filef for processsing, at that ttime we havee to give file opening
o mode e.
• We can do limited opperations onlyy based on mode
m in whichh file is opened.
m
e.g. fp = fope
en(“demo.t
txt”,”r”); //H pened in read only mode.
Here file is op
o
.c
C has 6 diffeerent file open
ning modes for text files,
ie
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)
h
4. r+ open for readding and writting, start at b beginning
5. w+ open for readding and writting (overwritte file)
c
6. a+ open for readding and writting, at the en nd (append if file exists)
e
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
e
#inclu
ude <stdio.h>
void main()
m
c
{
FILE *fp;; // fp is file pointerr. FILE is a sttructure defin
ned in stdio.h
h
A
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
.c
fclose(q);
return 0;;
}
ie
Ex
xplain file handing
h fu
unctions with
w 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 purpose.
p
h
fop
pen() (Open file)
c
e
• fopen is used to open a file for operattion.
• Two argumeents should be supplied to o fopen function,
• File name orr full path of file
f to be ope
T ened
e
• 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
c
en(“Prog.c
c”,”r”); me is prog.c and it is opened for readiing only.
// File nam
fclo
•
•
ose()
The function
A
(Close file)
Opened filess must be closed when operations are o
n fclose is use
over.
ed to close the file i.e. indicate that we are finished processing
p th
his file.
• To close a file, we have to o supply file pointer
p 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 function
f 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 a 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
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 new
n position defined by ad dding offset to
t a
reference po osition speciffied by origin..
• You can use fseek() to mo ove beyond a file, but not before the beginning.
• fseek() clearrs the EOF flagg associated with that file.
• We have to supply three arguments, file f pointer, h how many chaaracters, from
m which location.
•
m
ero upon succcess, non‐zero
It returns ze o on failure.
The
e origin value should haave one of the e following vaalues
Nam
me Explanation
o
.c
SEE
EK_SET Seek from thhe start of thee file
SEE
EK_CUR Seek from thhe current location
SEE
EK_END Seek from thhe end of the file
h
ftelll() (Get curren
nt position in
n file)
It re
eturns the current value of
o the position
n indicator off the file.
Exa
ample: position = ftell (fp);
(
e
rew
wind() (Set positio
T
on indicator to the begin
nning)
• Sets the possition indicato
e
or associated with file to th
he beginning of the file.
c
• 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:
gettc()
A
rewind (f
fp);
(Get characcter from file
e)
• getc function returns thee next charactter from file o
or EOF if the end
e of file is reached.
r
• 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);
Exaample: i = getw(
(fp);
Wrrite a prog
gram to co
ount the nu
umber of llines, tabss, characte
ers and wo
ords in a fiile.
m
o
#in
nclude <s
stdio.h>
voi
id main()
.c
{
FILE *fp;
*
int li
ines=0, tabs=0, ch haracters= =0, words = 0;
ie
char ch,
c filename[100] ;
f(“Enter file name
printf e: “);
/// You can also o use scanf
h
gets( filename ); f(“%s”,fil lename);
fp = fopen(
f filename, “r”
“ );
c
if ( fp
f == NULL ) /// File is not opened successsfully then it returns NULL.
{
printf(“CCannot ope
en %s for
e
r reading \n”, file ename );
T
exit(1); /* terminate
t e program */
}
e
ch = getc(
g fp ) ;
while ( ch != EOF )
c
{
if ( ch == ‘\n’ )
A
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) Dynamic
D Memory
M A n, Storage Classes
Allocation
.c
can access value.
v accessed only through a pointer.
• e.g. • e.g.
ie
int i; p = malloc(sizeof(in
nt));
float j;
Ex
xplain varrious funcctions use
ed in Dyna
amic Mem
mory Allo
ocation.
h
ma
alloc( )
c
e
• malloc()) is used to allocate a certaain amount byytes of memo
ory during thee execution ofo a program.
• malloc()) allocates siize_in_byt tes bytes of memory from m heap, if thee allocation su
ucceeds, a po
ointer to
T
the blocck of memoryy is returned else
e NULL is reeturned.
e
• malloc()) returns an uninitialized memory
m for yo
ou to use.
• Malloc()) can be used to allocate space for complex data typ pes such as structures.
•
•
Syntax:
Example e: c ptr_ _var = (c cast_type *)malloc( (size_in_ _bytes);
A #inc clude<std
int main()
{
dio.h>
int *p ;
p = (in nt *)malloc(sizeof f(int));
*p =25; ;
printf( (“%d”,*p);
free(P) );
}
callloc( )
• calloc() is used to allo
ocate a block of memory during
d the exeecution of a p
program, e.g. for an array.
• calloc() allocates
a a reegion of memory large eno
ough to hold no_of_blo
n ocks of size size_of_bl
s lock
each, if the
t allocation n succeeds th o memory iss returned elsse NULL is returned.
hen a pointer to the block of
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);
m
p
p++;
}
o
}
rea
alloc( )
.c
• realloc()) reallocates a memory blo ock with a sp pecific new sizze. If you calll realloc(), thee size of the memory
block poointed to by the
t pointer is changed to tthe given sizee in bytes. Thiis way you arre able to exp pand and
ie
reduce the
t amount of o 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 to o new memo ory and old memory is released
automattically.
h
c
• The content will remain unchangeed means it iss copied to neew location.
• ointer is NULLL then the reaalloc() will behave exactly like the mallo
If the po oc(). It will asssign a new block of a
•
size in bytes and will return a poin
e
nter to it.
T
Syntax: ptr_vvar=* reallooc ( void * ptrr, size_t size );;
• Example e:
e
#inc clude<std dio.h>
int main()
c
{
int *p ;
A p = (in
*p =25;
p = (in
nt *)malloc(sizeof
;
nt *)realloc(p, 2 * sizeof(
f(int));
(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 declared
d in fu
unction are off automatic sttorage class.
• Automatic variables are
a 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 from f the
m
functionn.
• The scop pe of automaatic variable iss local to the function in which
w it is declared.
o
• It is not required to use
u the keywo ord auto becaause by defau ult storage claass within a block
b is auto.
.c
Exaample:
int a;
auto int a;
ie
reg
gister:
• Automatic variables are allocateed storage in the main memory m of th
he computer;; However, for f most
h
compute ers, accessingg data in memmory is considderably slowe
er 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 who
c ose access tim
me should bee fast may be b declared to t be of
e
storage class registerr.
• Variable
es can be declared as a reggister: regis ster int var;
extternal:
T
•
e
Automatic and registter variables have
h limited scope
s and lim
mited lifetimes in which theey are declareed.
c
• 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.
A
• 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 as:
a
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 function
f term
minates.
• The scoppe of static au
utomatic variiables is identtical to that of
o automatic variables.
v
Darsh
han Institu
ute of Engin
neering & T
Technology
y
Ex
xplain Inp
put / Outp
put functions.
• C languaage provides a set of stan ndard built‐in
n functions which
w will do tthe work of reading or diisplaying
data or information on
o the I/O devices during p program execcution.
• O functions esstablish an intteractive com
Such I/O mmunication between
b the program andd user.
Fo
ormatted Input/Outp
put functions
sca
anf( )
• It is usedd to read all types
t of data..
• It cannoot read white space between strings.
• It can reead multiple data
d at a timee by multiple format speciffier in one scaanf( ).
• Example e: scan nf(“%d%d” ”, &a, &b) );
priintf( )
m
• 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);
o
.c
Un
nformatted
d input ou
utput functtions
getts()
ie
• 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.
h
• Example e:
char str[10];
s
gets(s str);
c
gettchar(), getcche( ), getch
h( )
e
T
• 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
e
es not displayy the input ch
haracter while getchar( ) aand getche( ) function dissplay the
c
input chharacter on thhe screen.
• Example e:
A
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
m
o
ude<ctype.h>
#inclu
void main()
m
.c
{
ie
char c;
clrscr();
;
scanf("%c
c",&c);
if(isdigi
it(c))
h
prin
ntf("True
e");
c
e
getch();
T
}
e
c
A