C Programming Notes Module 1 to Module 5 Notes
C Programming Notes Module 1 to Module 5 Notes
Semester I
Module 1: Introduction to C
Introduction to Computers:
Introduction to C:
• Structure of C program
• Compilers
• Variables
• Constants
• Input/output statements in C
Module 1 : Introduction to Computers
1 2
Data :
Data is a piece of information that is input to the computer. Speed :
Data is representation of facts or concepts in an organized manner.
Data does not convey any meaning. Computers process data at very high speed.
Numbers : 0 to 9, Alphabets :A to Z etc can be considered as data. Computers performs millions of operations per second.
Speed is measured in Millions of Instructions Per Second(MIPS).
Information : 1 byte = 8 bits
Information is collection of data from which conclusion can be 1 kilobyte (K / Kb) = 1,024 bytes
drawn. 1 megabyte (M / MB) = 1,024 Kb(1,048,576 bytes)
Information is obtained from data & it is result of processing, 1 gigabyte (G / GB) = 1,024 MB(1,073,741,824 bytes)
manipulating & organizing the data. 1 terabyte (T / TB) = 1,024 GB(1,099,511,627,776 bytes).
Information may be hello .
3 4
1
Accuracy : Storage Capability :
Computers can store large amount of data & can be retrieved at
any time in fractions of second.
Computers does not make mistakes in calculations hence they
produce accurate results.
5 6
Mechanical Abacus
Diligence (Carefulness) :
computers Pascaline
Computers does not suffer from carelessness, tiredness etc.
Efficiency does not decrease with increase in time. Differential Engine
Computing
devices
Electronic ENIAC
computers EDVAC
IBM PC
7 8
2
Mechanical Computers
Pascaline :
Abacus :
In 1642, Blaise Pascal (French
Computer means compute.
mathematician, physicist, philosopher)
Abacus is a oldest mechanical counting
invented a mechanical calculator
machine.
called the Pascaline.
It is used to perform basic arithmetic operations
9 10
Differential Engine :
Electronic Computers
It was implemented by ENIAC (Electronic Numerical Integrator And Computer) :
Charles babbage.
ENIAC was built in the 1940s.
It is used to perform basic mathematical It was the first electronic digital
calculation. computer used to solve all types
of problems.
He also designed another machine It weighs 30 tons &
called as analytical engine that consumes 160 kw of electrical
performs other types of operations also. power.
Size is 1800 square feet(60x40 size).
It consist of more than 8000 parts, Main problem is instructions are
weighing 5 tones & 11 feet long. given manually by connecting
wires and switches.
All this mechanical
computers works with out
software 11 12
3
EDVAC ( Electronic Discrete Variable Automatic Computer) : EDVAC ( Electronic Discrete Variable Automatic Computer) :
It was developed in 1950.
Avoid giving instructions manually.
The concept of storing data and instructions
inside the computer memory was
introduced here.
EDVAC is faster than ENIAC.
Drawbacks :
Large in size.
Power consumption is more.
13 14
The computer has evolved from a large-sized simple Currently, there are five generations of computer. In the
calculating machine to a smaller but much more powerful following subsections, we will discuss the generations of
machine. computer in terms of the technology used by them
(hardware and software), computing characteristics
The evolution of computer to the current state is defined (speed, i.e., number of instructions executed per second),
in terms of the generations of computer. physical appearance, and their applications.
15 16
4
The first computers used vacuum tubes(a sealed glass tube
containing a near-vacuum which allows the free passage of electric
current.) for circuitry and magnetic drums for memory.
17 18
19 20
5
Advantages : The development of the integrated circuit was the hallmark of
the third generation of computers.
Size reduced considerably
They were relatively fast Transistors were miniaturized and placed on siliconchips,
called semiconductors.
Very much reliable
Instead of punched cards and printouts, users interacted with
third generation computers through keyboards
Disadvantages : and monitors and interfaced with an operating system.
They over heated quickly Allowed the device to run many different applications at one
Maintenance problems time.
21 22
23 24
6
Fifth generation computing devices, based on artificial
intelligence.
25 26
27 28
7
Input devices:
Input devices Allows user to enter data & commands into memory of a
eg. Keyboard, mouse computer.
Keyboard, mouse, scanner etc are various input devices.
Typical parts Output devices
of a eg. Monitor, printer
Computer
System unit
Storage devices
eg. CD, DVD
Fig : Input devices
29 30
31 32
8
System unit : Various units of System unit are classified based on the visibility as
System unit consists of circuit board called motherboard. follows:
Motherboard has two main components : Units that are visible from the front end
Central Processing Unit(CPU) & Units that are visible from the back end
Memory. Units that are visible inside the system unit.
33 34
Visibility from the front end Visibility from the back end
35 36
9
Visibility from the back end Visibility from the back end
37 38
Motherboard
Central Processing Unit (CPU)
Basic Input Output System (BIOS)
Memory
Secondary memory
Cards
Switch Mode Power Supply (SMPS)
10
Processor Random Access Memory (RAM)
Expansion card
Fig : Motherboard
41 42
CPU Represents
Control Signals
Fig : Structure of a Computer
43 44
11
Output unit :
Input unit :
It displays the result in the form suitable for human understanding.
Example : monitor, printer, speaker etc.
It allows the user to enter data or program (instructions) to the
computer system.
It converts data into a suitable form that can be understood by Memory unit :
computer.
Converted data is stored in form of 0 & 1 in memory. It takes data from input device & stores it until the computer is
Example : keyboard, mouse etc ready to process it.
Memory can be either Primary memory or Secondary memory.
45 46
47 48
12
Data Handling Technique
(Technology)
Data Handling Technique (Technology)
49 50
Desktop Computers
Network Server
Workstations
Mini Computers
Computers for Notebook Computers(Laptops)
Individuals Computers for
Organizations Mainframe Computers
Tablet Computers
Super Computers
Smart Phones
51 52
13
Computers based on Data Handling Technique
Data Handling Technique (Technology) (Technology)
Analog Computers :
Accept the data whose values keep changing with respect to time.
Data may be in form of continuous voltages, frequencies, temperature
etc.
Process the data by measuring.
Analog Digital Hybrid
Process mathematical & scientific data easily.
Eg. Thermometer Eg. Personal Computer [Link]
Requires less or no memory.
Example : Analog Speedometer, Thermometer.
53 54
Accept the data & process the data in terms of digital data such as 0 & Designed to handle both digital & analog data.
1 ( binary digits , in short bits ). Also called as analog-digital computers.
Process the data by counting. Accepts analog signals, converts it into digital form & processes them in
Process mathematical & scientific data by using complex logics. digital form.
Requires memory. Process mathematical & scientific data easily.
Example : all modern day Personal Computers . Requires less amount of memory.
Example : Robotics.
55 56
14
Desktop Computers Computers for individuals
Smart Phones
57 58
Workstation
Uses :
For communication using e-mails etc
A personal computer but with most powerful microprocessor,
Listening to music, watching movies, playing games
large & high resolution monitor for better quality of pictures
Business applications etc.
Has large amount of memory
Advantages : Normally uses UNIX operating system.
Powerful
Maintenance Uses :
Cost
For business or professional use
Disadvantages : Architectural or engineering design
Space Video editing & animations.
Portability
59 60
15
Advantages : Notebook Computers (Laptops)
Costly Advantages :
Not portable Portable
Integrated unit
Less space
Power
61 62
63 64
16
Advantages :
Handheld (Personal Digital Assistant)
Notes can be written using own hand written style or can be
A computing device small enough to fit in palm
converted into standard text
Also called as Palmtop or Pocket computers
Paper work is eliminated
Has all features of Tablet
Very slim & light hence Portable Provides additional features such as calendar, address book,
Stylus avoids typing. notepad & so on
Commonly used by doctors,
Disadvantages : students etc.
Expensive & delicate
High replacement cost.
65 66
Advantages :
Smart Phones
Reduces paper work
Small size & portable An electronic handheld device that has the functionality of a
Can be used to access internet. mobile phone & a PDA
Achieved by adding mobile phone features to an existing PDA or
Disadvantages : vice versa.
Expensive
Very limited memory
Uses batteries & needs charging frequently
Some come with a keyboard which is small & difficult to
key in.
67 68
17
Advantages : Network Server
More expensive
Larger than standard handsets
High replacement cost. Super Computers
69 70
71 72
18
Advantages :
Avoids duplication of data & software.
Mainframe Computers
Mainframe is a term used for very large computers in an industry.
Personal computer based network servers gives more flexibility to
users to do different kind of tasks. Used for commercial Applications & other organizations to
perform large scale computation & supporting large volume of
data & large number of users simultaneously.
Business organizations like Insurance companies, Banks,
government offices needs more powerful features in terms of data,
storage & speed.
Automated Teller Machine (ATM) also uses Mainframes.
73 74
Disadvantages : Minicomputers
Mainframes occupies very large space.
Computers whose capabilities lies between mainframes &
microcomputers are called as Minicomputers.
Also called as mid-range computers.
Used by small & mid-size business organizations.
A multi-user computer capable of supporting hundreds of users
simultaneously.
They can handle very large input & output compared to
75 76
19
Data or information to be shared between various users will be Super Computers
available in various servers. An extremely fast computer that can perform one Trillion (10 12 )
Users can access central minicomputer through a terminal or operations per second.
standard PC. Super computers are used for scientific & engineering applications
that must handle very large databases or do a great amount of
computations or both.
It is the fastest, costliest & most powerful computers available
today.
Super computers have highest processing speed at a given time for
solving scientific & engineering problem.
77 78
Uses :
For Weather Forecasting. Super Computer is dedicated to execute few programs as fast as
In Military Applications. possible where as a Mainframe is dedicated to execute many
In Earth-quake Predictions. programs simultaneously.
Mainframes can be considered more powerful than Super
computers because they support more simultaneous execution of
programs.
But Super computers can execute a single program faster than a
Mainframe computers.
79 80
20
The essential parts of a computer system are : Hardware :
Hardware Physical components that makes up the computer system are
termed as hardware (mechanical devices).
Software
Anything that can be touched & felt including cables & wires is
Data called hardware.
User All hardware units are categorized as Input devices, Output
devices, System unit & Storage devices.
Software :
A Program is a set of instructions given to a computer to perform
a specific task.
A set of Programs that does the specific job are called Software.
Using software, computer can receive data, store data, manipulate
data & output data in correct order & format.
81 82
Data :
Piece of information (input to the computer). Input devices
Computer organize (manipulate) and present data in the form of
information.
Example : Numbers 0 to 9, Alphabets A to Z etc can be considered Processing devices
as data. Essential Computer
Information may be hello . Hardware
Storage devices
User :
People operating the computer.
Output devices
Most important part.
Tell the computer what to do.
83 84
21
Input devices : Processor :
Devices using which data or commands can be entered into It carries out various instructions that come from either user or
computer for processing. software.
Various input devices connected to computer system such as Processor usually consists of one or more specialized chips called
keyboard, mouse helps user to enter data or give commands to microprocessor which is plugged into motherboard.
computer system.
Memory :
Is one or more sets of chips that stores data & instructions
Processing : permanently or temporarily.
Transformation of data into an useful information is called Data & instructions to be processed are brought into memory
processing. execution.
Processing is done using 2 components : Personal computer uses 2 types of memory :
Processor Random Access Memory (RAM)
Memory Read Only Memory (ROM)
85 86
87 88
22
Software : System Software (SS) :
A Program is a set of instructions given to a computer to perform
The programs that support the operation of a computer are called
a specific task.
System Software.
A Set of Programs that does the specific jobs are called Software.
System programs that helps the user to utilize various resources of
Using software, computer can receive data, store data, manipulate computer system effectively & efficiently.
data & output data in correct order & format.
Example : Operating System (OS)
Software can be classified as follows :
Set of Programs that helps the user to interact with various
System Software (SS) resources in computer system is called Operating System.
Example : Windows XP, UNIX, LINUX etc.
Software
89 90
91
Differences between System Software & Application Software 92
23
Input devices are used to enter data & commands into Pointing devices (variants of Mouse)
memory of a computer.
Keyboard
Optical
devices Pen Touch Screen Game Controllers
Audio Visual
Input devices
24
Alphanumeric & Character
keys
Numeric keypad
Function keys
Keys that have letters from' to are Alphabetic Group of keys located on the right side of keyboard is
keys. numeric keypad.
Keys that have numbers from 0 to 9 are numeric keys. These keys are associated with a Numlock key.
Keys with [, ], {, }, <, > etc are called as special When Numlock is ON, we can type digits from 0 to 9,
character keys. . & symbols such as +, -, *, / .
Other keys in this group are Tab, Capslock, spacebar, When Numlock is OFF, keys are used to move the
Backspace & Enter key. cursor.
25
Modifier keys : Cursor movement keys :
Modifier keys modify the normal function of a key These keys helps the user to move the cursor around
when used together. the screen.
Shift, Ctrl & Alt keys are modifier keys & they occur in Also called as Navigation keys.
pairs on either side of the Spacebar key. Placed between Alphanumeric keys & keypad.
Meaning of these keys differ from one program to
another program. To move cursor Upwards.
Eg. Shift + letter(a) A. To move cursor Downwards.
Ctrl + x cut.
Ctrl + c copy. To move cursor to the Right side.
Ctrl + v paste.
To move cursor to the Left.
Function keys :
Home : to move cursor to beginning of current line. Special keys labeled from F1 to F12.
These keys have different meaning depending on which
End : to move cursor to end of current line. program is running.
26
Fig : Standard Keyboard Layout (QWERTY)
27
What is an Operating System? What are the functions of operatingsystems?
• Operating System is defined as Set of Programs that helps the user to interact with
various resources in computer system.
• In other words, it is a well-organized collection of programs that manages the hardware.
• The operating system is an integral part of modern computer systems.
1. Program execution
2. Input Output Operations
3. Communication between Process
4. File Management
5. Memory Management
6. Process Management
7. Security and Privacy
8. Resource Management
9. User Interface
10. Networking
11. Error handling
12. Time Management
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Rata type de<enes det co operalFon and Jel
’A
46
bi] [32 47
o s?y The
ytes atleast s unt dong
attuast o}size The
bytu
brl6 a is int
o}t
ot s unt Shont ol size The
[is
bibytes en
aen
natue
always untegS
ae unstgrud *
osiAve
in
hagatfuey natuu
polfe
çn ae thuy daault
an &rgned
osftue
ot dethet eiintegs
igned uithut
e úntegu Can applied
to
H
quali'es ae dong and Shot *
beanthat
unaignad Jum,l dong
int9unstgned
num Jong |
||num; ntdong
(ompuls
od is npBum; uit
2reot hostn &I|
unt Shot 1
Clong) int Jong Example
untunt
Srtegou
gt) (Ah unt hat
yolows gntegues
as e cOn
The tang o sgned integ Vastes yom
-3,168 to +3,161
The tong o unsfqned integ Vasies t om
Sxam ple :
than ub epoesentalon
Lololoo ooololoooooo 2.
Sgned +
48
oatfng pount Can e chategosyd as yououd
Type Byt es bft es Range
loat H byte 3 brt3.4 E- 38 to 3.4E t 38
double 8 bytes64 6Pb.1E-308 to l.1E +30 &
loat s
Sngle psucdslon loat ng potnt
doubie is double pu cia?on qloaling poirt.
Jong double s lttendud
tehate Po cision pofrt .
49
J To Apecr b4 a otun ype o, yuncHon wh
the yuncton tuens no vae .
mainc) o l 2
Indicatu etuns no valueotpd
Q Tospeeb the patamcto t ol tunctfof
s umpty Cçwhun the unton aclepts no
Oguments Hom the Calsgd olg
Jndlat es that paaamct
VoJdimasn (veed
) J a t us emply
50 tAtovol add Cveid) itochi l u a h
Compiling and Executing C Programs:
The following are the phases through which our program passes before being transformed into an
executable form:
1. Preprocessor
2. Compiler
3. Assembler
4. Linker
Preprocessor
The source code is the code which is written in a text editor and the source code file is given an
extension ".c". This source code is first passed to the preprocessor, and then the preprocessor
expands this code. After expanding the code, the expanded code is passed to the compiler.
Compiler
The code which is expanded by the preprocessor is passed to the compiler. The compiler converts
this code into assembly code that is the C compiler converts the pre-processed code into assembly
code.
Assembler
The assembly code is converted into object code by using an assembler. The name of the object
file generated by the assembler is the same as the source file. The extension of the object file is
'.obj. If the name of the source file is 'hello.c', then the name of the object file would be '[Link]'.
1|Page
51
Linker
In C programming, the majority of programs rely on library functions. These functions come pre-
compiled, and their object code is stored with extensions like '.lib' or '.a'. The primary function of
the linker is to merge the object code from these library files with the object code of our program.
Sometimes the situation arises when our program refers to the functions defined in other files; then
linker plays a very important role in this. It links the object code of these files to our program.
Therefore, we conclude that the job of the linker is to link the object code of our program with the
object code of the library files and other files. The output of the linker is the executable file. The
name of the executable file is the same as the source file but differs only in their extensions.
2|Page
52
✓ Firstly, the input file, i.e., hello.c, is passed to the preprocessor, and the preprocessor
converts the source code into expanded source code. The extension of the expanded source
code would be hello.i.
✓ The expanded source code is passed to the compiler, and the compiler converts this
expanded source code into assembly code. The extension of the assembly code would
be hello.s.
✓ This assembly code is then sent to the assembler, which converts the assembly code into
object code.
✓ After the creation of an object code, the linker creates the executable file. The loader will
then load the executable file for the execution.
3|Page
53
Explain the five characteristics of an algorithm with an example.
1. Input: An algorithm has zero or more inputs. Each that contains a fundamental operator
must accept zero or more inputs.
2. Output: An algorithm produces at least one output. Every instruction that contains a
fundamental operator must accept zero or more inputs.
3. Clear and Unambiguous: The algorithm should be unambiguous. Each of its steps should
be clear in all aspects and must lead to only one meaning.
4. Well-Defined Outputs: The algorithm must clearly define what output will be yielded and
it should be well-defined as well. It should produce at least 1 output.
5. Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time.
6. Feasible: The algorithm must be simple, generic, and practical, such that it can be
executed with the available resources. It must not contain some future technology or
anything.
7. Language Independent: The Algorithm designed must be language-independent, i.e. it
must be just plain instructions that can be implemented in any language, and yet the
output will be the same, as expected.
54
Module 2
• Operators in C
• Iterative statements
• Nested loops
• goto statement.
55
Module 2
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
Define the terms: precedence and associativity.
Precedence is used to determine the order in which different operators are to be evaluated in a
complex expression.
Associativity is used to determine the order in which operators having same precedence are to
be evaluated in a complex expression.
Precedence is applied first and Associativity is applied if necessary. Associativity can be either
from left to right or right to left.
74
75
Sample Programs
76
/*Program to demonstrate working of bitwise XOR operator */
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 12, b = 25;
clrscr();
printf(“Output = %d”, a ^ b);
getch();
}
77
/* C Program to demonstrate the working of assignment operators */
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 5, c;
clrscr();
c = a;
printf(“c = %d \n”, c);
c += a; // c = c + a
printf(“c = %d \n”, c);
c -= a; // c = c – a
printf(“c = %d \n”, c);
c *= a; // c = c * a
printf(“c = %d \n”, c)
c /= a; // c = c/a
printf(“c = %d \n”, c)
c %=a; // c = c%a
printf(“c = %d \n”, c);
getch();
}
78
/* Program to demonstrate increment/ decrement operators */
#include<stdio.h>
#include<conio.h>
void main()
{
int x, y, z;
printf(“Input the value of x, y and z: \n”);
--x;
--y;
--z;
getch();
}
79
/* Program to demonstrate implicit type conversion */
#include<stdio.h>
#include<conio.h>void
main()
{
80
/* C program to demonstrate explicit type casting */
#include<stdio.h>
#include<conio.h>
void main()
{
double x = 1.2;int
sum; clrscr();
// Explicit conversion from double to intsum =
(int)x + 1;
printf(“sum = %d”, sum);
getch();
}
81
R'sien Conliol and sta limeita- Condilonat
buandng stakaet, Ituafi satak, Neta loopk, burak,
Cont:nue and slatement
btatuent
uncondionol
longtönal
82
&atonont [3.1.]
slatiment tu most biuplect decialon nuaking Cantuol
te
ktate uet
It wsed to execut bet 9ne Moe instauetone
Cenditon tiue
NoTE:
and tst expaesion % eetalionol expuesion
statement May bebe a shgk statiment
Statauenti
Cxpues ion tie, btatement will
wl! bebe enented, otheuwne
trl st taMent ntwil! be sk ippeol an
and u eeulion st
Jump to theu Satmen wWhen te Condten & tie st betu
tue stbhtemet aLe exe uled
Sequene .
O! statmet:
(est tapueston)
lest
btateent n; epuesion PaLsE
Stotenyent s TRUE
Aatement block 1
Statenent
83
yhehu numbu!
odd eing
Ln clude< Conoh
Void ain l)
int
cluseu ();
enlu oy iaequ \n);
bcany'%d", mun';
nun);
(num %<=0)
getch();
ent
84
iaguam to uid heikeu a
# ncude <stdio. h
# clude < Conto.h
Void nain ()
Cnt
Cluscu C);
(" entu
bcan ("%d'" nu);
num >0)
eleed num
(nu < o)
enluel um
Y(nu=o)
cnued nun cquad to iuo");
Cnteu
entanecd
85
ele statenAeat: [3. l.2]
" "Ihe i-eke
statement an elensibu
tst' Cxpueuiou tüetr. sple
theu statement blo c!
-stalbment
CXecuted
ond apuuin
upuein &false, taen statiment bleck 2 K Cxecuted.
-ese sament:
(tet capuesion)
Stotenent bock ;
elie
stateent blek 2
Stotement x; Fas sE
Test
Cpuession
StotenMent x
86
Paequam e dtunîne hetheu a
Ihdhu
to Vote not
include <stdio-u
+ include <Conie"h
Veid man()
int
cuscn):
6cadl% d
(age z8)
elgibl. to veti);
lage<is)
not to vot):
3
gekeh ();
|Batut:
Entu the nge g9 The beon
ctyible t veti
Entee te
15
not es aible te Vet
87
Poguam to deteeelmine khetheu clued olphabtte
Chauadleu % Vovet u Consonent */
# &nclude <[Link]
# include <Co nlo.u
yoid Main ()
chau ch ();
Chuscu ();
puinty enteu any alphabiti Chasacta \n):
bcan' ( %c» l);
i(chza'A ch=f' | Ch-I Hch=0 ch=U'Hch=a'!| ch=ze
ch-?' ch='e' ch's')
Vével"", ch);
ese
Censonent ch);
ebe
þuint (%c s neilhe Yovel ou Consenent
99
ch);
Batput
Cntu chaacteey:V
Cosonat
88
heghon enla any Chauac te enlited
iobeu Case
loweu (ace chauateu tn Conyeut t nto Case
+ nclu de Kstdto h
Vold main ()
Cha ch
Cluscn
chanates :"):
puint (\n enta any canatu
kcany ("%c ch):
(\n e enteued chaacli u Cose. In
lense Case it %: /%c", cht32));
cke
tu enlued chanadu in loweu Cae- In
Case tt %: Voe", Ceh- 2):
getek e) ;
chasncta :a
Tae entuuid chauacle was in lowey Cos
Case ß:A
89
fuogunny o cheek hihe lleu
clue 6laleniet *
Veld Moin
mMaln ()
int
icluscu ():
uinty ( eata nti
4num);
(n um >o)
qedch ();
Patput:
enteu
90
Wuite a fuoquan to cheek aethuu a 9iven
odd een bising - ehe slotement
+ include sldto - h>
+ inclucde <Conio .hs
Veid Main ()
int
cusu C);
(" entau any intiqu ln"):
Scany(%d» onun);
ij (núm %2==0)
ebe
puint|("%. d s is cven Mum);
num):
ge tch () ;
3
entu
3 B pdd
91
A
ebe' stotement */
Void noin C)
int
clus Cu( );
else
lauqu):
ghchto;
etu
5 6
laq.
92
tle- statament [3..3
-ehe-Y stateent to eet addtlo nal
CondÝn
Constiuct ouke àCn tu bame nay nocemal Q statement.
ne stid Constuet
ebke block
lhat ereystalant ssuld have
Stalementt
tust expuesipn bu aheh, the fuoquomen Can has
eke'
buanchee oi he wont
tot hae
have t be tatd
tutis
-ela- y statauent:
Stalement blsck 1;
ebe
Ctit
(tost
expuealen 2) Test
expuston 1 FaLse
TRUE
Stalement block 2;
|stalenient blocki|
else
lest
expusion 2 Fakse
Sta feent Block X;
TevE
btalenment |6talenent block2 staleme nt bleck X
93 stoleuent Y
Nested ele statesuent [s. b.
hen Seies de ?si ou asie molved
havr ta e ke
One -
Ypueasion 1)
bto tt nent 1;
ese
6tole me nt;
ese
stalement 3;
FAkSE
eUE Cprion
94
to Conpaur tioe numbu /
V icd lan l )
t 1WM 1, num2;
cbsu ();
þutnt! (" entu any tv unbuys\ ):
r"/od d" numA, nume);
(nuns =num 2)
4(numi> num)
than mum2;
cke
to nu 2");
Cqualk
3
eke
3. enfu, we numbus
35
any
95
lement; Sto 96
eke -
slalenment
n;
(e*pueuien
n) reke Taue
eent3 6lat
(ypuenion)
-else
ente;
H(pueaion
2) Statena Taue
ehe
6lateuent
1;
lepucsia
i) Ikue
hclanuloay uplement omeel statenent
k eke *.
oqiho lg wainvolved
y anotha dectsisn
OMe
tfath Mu
&.Theue
I.5a) [3. tsjent: sta ele )
loddu -ehe
kutteh ciHhcu uiupleentd
n
taementt 6elekon vyay
6elecheu li. puevidec
oies, "han
wo Moue chek
ou 6rualon
lo Many
1choiee hyo(onsdeu Only
eleelron daawbok tu
[3.1.5)
to tuuee numbue loddun
# ucude <stdfo .h>
# ne ude <conto. )
Void main ()
Sutput:
enteu 3 rubeys
2
auty
entey
augert
3 nunbus
6
nUm2
3 umbeus
4
laugat
97
) Sutkh stanent:
( has a hitll - n
mutyas de ihipn slatcvent tnown
6iuibeh ktaleneut tat tu vadne a qiven eapucnin
Ihe t Q Casc Values and hen
a bleck 6tatenenk asecialed oith
bwitch (enpucaian)
Case Vaue 1: btatementi;
bueat;
Case Value 2: Stote ment;
hucak ;
Lase value n:
statementn;
bueak;
3
dqaut dejault stote ment,
he cpuusion Bhoutd be i intequ Valne (te Lupuusian ype
inte chaactu ). (But not Jo afiag point expÁson)
Vone i, Value2.. ae Constant Luere
knon Cose labelk, Cacu
the Vaue sheuld be
unique with in he
hhen
bnitch staternent.
bnitch execuiled te Vabue
(ose Jound whos alue motche with tue ahue
Cpunibn block Btatement that
exe cuted .
de<aut
epues ion Vale
oplional
doesnot th
match
Case. 1 eLe cuted ohen tue
with any 9 Values
98
e oeiten aboe te dyault statement
Flons haut:
TZUE
Value
|Stotenent Blok 1
FaLsE
TevE
Valne
8iotement block 2 fALSE
FALSE
TwE Vaue
Stotement bleck N
fAsE
stolement blackD
Stotenent x
99
Preguam t unt Cuntcpon dihg
dokg dlay ? a werk wing
byvtch 6tatement beek Slosn t fuona monday/"
# ineude <stdio .h>
# cde (conie - h)
Veicl Man l )
int
cluscu (0;
(enlu uubu
bcan! %d", 4 dan);
Cose 1 :
bueak
Case 2:
bueak;
Cas e 3:
beak;
Case 4i
bucak's
Case 5: p.
bueak;
Case 6 :
batuday
en tu numbu fuom 1 to
bunday ahy
entua nunbeu 1 to
1
Invaid
101
Loop1NG
Looprg:
áaping
[3.2)
faevide MechanàM by ich
ieh w Can iepeat
bame bet g
aqain and oqaim nlill hu Cond:tb.
tlu Coditio
faken
theuse
flace
e
3loops in C
1) fou loop
t) ile
) Do Wiale
hsle loop
du Thue laops hax ollowing in Conymen:
"Lantializalon
" Test - londilisn
body (slatemnt to be enecuta)
wpdotön neaenment/duhent)
do Wile
lap fnt test bep
102
Entay Contild bap tutt Cotolld loop
(cdo. nuile Iep)
enfoy
Body ,tae
Test Loop
Condien
TevE
TevE
taat
Conditeen
|Bedy loop
te
exit
tnithaligaon
Cupuion
Cxpueoson 1
Cp ueson 2
TKe
False
6tatement
Cit.
104
/s pueqam oto daplay num b
Veid
cluscu (0;
fuint (r cnta Vabue
Bcan (* d" 4n):
(o (ics ; i(=n; trt)
i);
qeteh ();
3
Butput:
|entu te Vaue
105
Wktte toop? 9. 2]
wl. loop buovide hond byby weh (nn
tue
ovslinelbn agan anel again
the l&ndileen
tecu lian 1 body
fakes flae
wule loop k fue tut loop
sile(lendieu)
statement ;
updolla
Fleo Chaat.
Condiln
TRue
Sta tement
106
t faint m bULs 1 o nn wing oa hlopy
Veld Main ()
int i, n
Khueul );
entu tte Valne fou nln)
Scany %d", n);
wile ?=n) / Condi Eou
autpuat:
entau ta Values to
5
107
wwlle loopr. {323)
do hilile
Mecheniau by wieh
(an cpent
Covdieu
takee plae
pat ftel lbopl chee lhed
Cxeculien
'u um
bod bu
y Pne.
Byntak
initaligao
do
stalement
p dolon
3 usile ( tondilion );
Floo chat:
|Body ie bop
TRVE
test Condihän
fesE
tt
108
109
3
1
Value Sukpattie: enlu
qetchl);
(i<=n) wile
do
n); d, bCan!
%
(i«
n\n; fou alnes tae enta Burty (
(; cusu
()
main Void
<[Link] hclude
aiat Pueqran
to do
to 1 nunbu
Nested Ts.2.4]
Nected lou loop 9ne laeol'
within tu body9 onothe
loop
Strtenent (s):
3
statement (s) 3
2
ouplei
tu (ie1 ; i<=5; ++)
110
fake 111
bueak Gndlian
Tane
Code
linal Condi
bueak tlhee,
ak
|buc
cebla the lime nent zeculing
tu Baut
nd lorp Code
mat sånu Ie exccuien
k e loop tu stap wibtolenent
l
Cose tuninale to seol
looP:beCoun t'
&tatenent 7eit
puoquam
tüminald ately Lo p Conctuol
enol Btatement
ik iuedi k
bueak when atenent; ide Ens
)bucak
statment label and goto
stotenent Contnue i)
Statemett:
bugpont C
diten Con without
nent stout Cankol Condfti'
olon aement buanching
Condilo
no ln- Hefuied
Contol fayanjaehg stalementt
du otheu Seme
toBloulem
ent ne
nti ne
stale
leaupt d to
used statmnt mp
Mal 104
[3.3)Sttimet:
tt ncdude <sldto .h>
-i
Eat a:10;/* local Vaciable dyialou / ,
Aile (aco) oale boop eeeulon
Value a:%d \n a)
(a5)
aatuen (o);
Butput:
Valne q a: O
Value
Vatue
Value a : J3
Valne 14
112
Conue satovent:
" Tnstead
leup (ovhat Bueak 6tlennent
dees)
in batdeon
tumialig ecatt
then Contt ae
'sialementk by sirpiny a Cude
Stote ment Can be sed.
Contnue Statment % used only
Cuuent iteuato
Continue Canot be eol side
Cont nue
Flow chaxt :
leop
XCond?Lbu Falke
Yes Centrue
No
Coce ohstole
body
Loop aftu Contiu
Stateent
113
Ename:
(int
Btfput:
o1 2 3 5 6 g
NloTE 3
Volue 4 tue Gutput. Becase he Vaue
Voutable tra puoquam mCown tuyed a Cortnue stalement
n9hich moke ttu Contl te at tu
got label ;
label : statemet;
nt n, buM=0;
clscu (0;
top:
palnt (n waunnq !!! þues q99 tbto exit.");
Pint! (*}nn entu umbus te be 6um: )
4n):
goto bottom :
botlem 3
uintj \ n swm all nunibuss= % bwn);
Butput:
oauniing !! pues q99 to exit.
Cntuu nunebu to be bum :
1 2 3
ol nmbeus = 15 .
116
Sample Programs
/*Example 1: Program to print half pyramid using *
*
**
***
****
*****
*/
#include <stdio.h>
int main()
int i, j, rows;
scanf("%d",&rows);
printf("* ");
printf("\n");
return 0;
117
/* Lab Program 1 : Program to implement a simple calculator using switch
statement */
#include<stdio.h>
int main()
char coperator;
switch(coperator)
break;
break;
break;
break;
break;
return 0;
118
/* Program to print day of a week using switch statement*/
#include <stdio.h>
int main()
int day;
scanf("%d",&day);
switch(day)
case 1 : printf("Sunday");
break;
case 2 : printf("Monday");
break;
case 3 : printf("Tuesday");
break;
case 4 : printf("Wednesday");
break;
case 5 : printf("Thursday");
break;
case 6 : printf("Friday");
break;
119
case 7 : printf("Saturday");
break;
return 0;
int main()
int num;
scanf("%d",&num);
if(num % 2 == 0)
printf("%d is even",num);
else
printf("%d is odd",num);
return 0;
120
/*Program to find largest of Largest of 2 nos*/
#include <stdio.h>
int main()
int n1,n2;
scanf("%d%d",&n1,&n2);
printf("n1 is largest");
else
printf("n2 is largest");
return 0;
121
/* An electricity board charges the following rates for the use of electricity:
beyond 300 units Rs 1 per unit. All users are charged a minimum of Rs. 100 as meter charge.
If the total amount is more than Rs 400, then an additional surcharge of 15% of total
amount is charged. Write a program to read the name of the user, number of units consumed
*/
#include<stdio.h>
#include<conio.h>
void main()
char name[10];
clrscr();
scanf("%s %f",name,&unit);
if(unit<=200)
charge=charge+unit*.80;
else if(unit<=300)
charge=charge+(unit-200)*0.90+160;
else
charge=charge+(unit-300)*1+250;
if(charge>=400) // simple if, executes only when charge is greater than or equals to 400
charge=charge+charge*0.15;
122
printf("Name: %s\nCharge: %5.2f",name,charge);
getch();
123
/* program 3-To calculate roots of a quadratic equation */
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
void main()
{
float a,b,c,d,r1,r2;
clrscr();
printf("Enter the coefficients of the equation\n");
scanf("%f%f%f",&a,&b,&c);
if(a==0)
{
printf("Roots cannot be determined");
getch();
exit(0);
}
d=(b*b)-(4*a*c);
if(d==0)
{
printf("Roots are real and equal"); r1=-b/(2*a); r2=-b/(2*a);
printf("\nRoots are %f and %f",r1,r2);
}
else if(d>0)
{
printf("\nRoots are real and distinct");
r1=(-b+sqrt(d))/(2*a);
r2=(-b-sqrt(d))/(2*a);
124
printf("\nRoots are %f and %f",r1,r2);
}
else
{
printf("\nRoots are imagnary"); r1=-b/(2*a); r2=sqrt(fabs(d))/(2*a);
printf("\nThe first root is %f+i%f",r1,r2); printf("\nThe second root is %f-i%f",r1,r2);
}
getch();
}
125
/*
Write a C Program to display the following by reading the number of rows as input,
1
121
12321
1234321
…………………
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n;
clrscr();
printf("Input number of rows : ");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
/* print blank spaces */
for(j=1;j<=n-i;j++)
printf(" ");
/* numbers in ascending order */
for(j=1;j<=i;j++)
printf("%d",j);
/* reverse order */
for(j=i-1;j>=1;j--)
126
printf("%d",j);
printf("\n");
}
getch();
}
127
//Program to demonstrate break statement
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5)
{
break;
}
printf("%d\n",i);
}
getch();
return 0;
}
Page 1
128
//Program to demonstrate continue statement
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
printf("%d\n",i);
}
getch();
return 0;
}
Page 2
129
//Write a C Program Which Print 1 To 10 Number Using goto statement.
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr();
count: //This is Label
printf("%d\n",i);
i++;
if(i<=10) {
goto count; //This jumps to label "count:"
}
getch();
}
Page 3
130
Programs on Looping Statements
131
/* Program to print numbers from 1 to n (natural numbers) using while loop */
#include<stdio.h>
#include<conio.h>
void main()
{
int num,i;
clrscr();
printf("Enter any value for num\n");
scanf("%d",&num);
i=1; //initialization
while(i <= num)
{ // body of while loop begins here
printf("%d\n",i);
i++;
} // loop ends here
getch();
}
132
/* Program to print numbers from 1 to n (natural numbers) using do...while loop */
#include<stdio.h>
#include<conio.h>
void main()
{
int num,i;
clrscr();
printf("Enter any value for num\n");
scanf("%d",&num);
i=1; //initialization
do
{ // loop begins here
printf("%d\n",i);
i++;
}while(i <= num); // a semicolon is must at the end here
getch();
}
133
/* Program to find sum of n natural numbers using for loop */
#include<stdio.h>
#include<conio.h>
void main()
{
int num,i,sum=0;
clrscr();
printf("Enter the value for num\n");
scanf("%d",&num);
for(i=1; i<=num; i++)
{
sum += i; // sum = sum + i;
}
printf("sum of first %d numbers is %d\n",num,sum);
getch();
}
134
/* Program to find sum of n natural numbers using for loop */
#include<stdio.h>
#include<conio.h>
void main()
{
int num,i,sum=0;
clrscr();
printf("Enter the value for num\n");
scanf("%d",&num);
for(i=1; i<=num; i++)
{
sum += i; // sum = sum + i;
}
printf("sum of first %d numbers is %d\n",num,sum);
getch();
}
135
/* Program to print numbers from num to 1(Reverse order) using for loop */
#include<stdio.h>
#include<conio.h>
void main()
{
int num,i;
clrscr();
printf("Enter the value for num\n");
scanf("%d",&num);
for(i=num; i>=1; i--)
{
printf("%d\t",i);
}
getch();
}
136
/* Program to print even numbers(2,4,6,8...) using while loop */
#include<stdio.h>
#include<conio.h>
void main()
{
int num,i;
clrscr();
printf("Enter the value for num\n");
scanf("%d",&num);
i=2; // initialize loop variable to 2
while(i <= num)
{
printf("%d\n",i);
i += 2; //i = i + 2;
}
getch();
}
137
/* Program to print odd numbers(1,3,5,7...) using do...while loop */
#include<stdio.h>
#include<conio.h>
void main()
{
int num,i;
clrscr();
printf("Enter the value for num\n");
scanf("%d",&num);
i=1; // initialize loop variable to 1
do
{
printf("%d\n",i);
i += 2; //i = i + 2;
}while(i <= num);
getch();
}
138
Module 3
Arrays
&
Functions
ARRAYs
3ioatudion
Not that a Vasuabe lan stae ordy one alue it any
lint!
Can be usect ony to handle
amounts data
Houwesen, an many afficana, e ned to hanle a
Tt
Jt an be lustotd as below
(o)
Numbor [o
lumben [2)
Nunben (3)
Nlumben
Alurnbu [a &
Neumbu C8)
141 (5)
* Mauks is the aay name wieh can hold a maimum
the elemet
Snput
)9 design valu to the elmuiti
Snitialie tte eleunt
Paotal ilaligalon
int manks (5]- o, o03;
mauks ooo
NOTE:
the lemt the Shitaligd ate gruat, than
the Comhilhu will todce
143
TNPUT VaLvES FoR THE ElEmENTS Run Tine Thstaligtion J:
Exþlitly Shitaligd at sun tine
Can de Exiy
Jhis abhsucach is
Éx:- ut mata S),:;
# incude <stdio.h>
+ nde <conio. h>
void main l )
Ilauate irittalizalin
int i, aw [9) -{5,9,3,2,100,-2,145;
|3
are
The elenei asay 9
5 9 8
145
x Augam to ead 'n awvay elemeit om the
Knybvnd and thun doint he cemeita o the asay on dhe
Console (autpt Soen) - Runline inttal'yaton */
ineade<stdio.h>
+ou<lonio.h>
Void main l )
int i,n, au
a lo0);
dscrt);
Scany (" d",Gn);
/* cace to suad elemunts atay */
fonli=l; icz0;?tt)
Stant (" %a",aroi);
It code to urt elemuit aUay */
foali =l ;ic=n;it+)
int C%dlt", a[:);
oucthit
Ent sig anay n)
5 6
The elemtt asay
146
5
Ix oogam to sead the clemints o the asay
the clemnts the aay nn haweose odu xl. and aint
#odude <Stdio.h>
toclud <onio.h
woid main ( )
tt i,n,nCo0;
tol? =l ; lc=n;++)
San} (" %d",fonn C):
uint CThe eemet arei \o");
fos li= n;?=l; i--)
1 2 3 y 5
The leut aray ae i
1475 4 3 1
to ad olerest and rint along
with then Squas */
nlude <stio.h>
# iocude conio. h>
95
5
3
148
* fogam to ind Sum and mean d all thu eemit stoude
asay
loclu cstdio.h>
#indude< Conio. h >
Void maio( )
Stan Cd",n):
tor (izI; i<=n;t+)
Stan (" d', amc));
bum = Buma
t i
3
mean /
ean = Sumln ;
4\", Sum, mean );
149
output
5
the elemit
1
5
Su is 15.0 mean s 3.0
150
SenRcHING
Suanding psuas feding an dmut
(Rebhie an elenet) om a lit elmet.
The eemust ohih we ae itustd do tind is
sukoad to as a elnut oH
* TÏ Seanch an elemut in a it lan be done
STEP G: Rag=0
then oint elmit not ound
STEP : Stop.
TRACTNG7
t us impement ineas Seaeh on
to fid the Ky tlenment
Snfut:
58o 12 ++
4
lemet to de Basched
Vasitables wsed n oghann
a(oo) kuy ,i,n, fag
Case huy elmnt to be Seaschd. he SeancA
s5 o2+
5 8 o124
Ky thust 4a faund at
’ Seanch is Suunhu and kuy
poatton 5.
153
Ia oogptam to dmontrat lineas Seasch *l.
lt mainC)
for(i=0;ie=mm;it+).
i+1D;
ag- 1:
Break
3
154
outßu
bu eleut, in
5
5 is eseit at Loaton a
155
BîNARY SEARCH
a 35 lo
’
Vayüablu wied in ogiam
156
a(io], dauo, high, mid, i, n, Kuy ,ag pos.
a 3 5 7 8 lo
() (2) (3) (4) (5)
35+|8 10
O 2) 3) (4) (5)
35+ 8 10
159
Psa tanm to imjlemt hiany Ftanch on diut
tlemeta x).
tncude <Stio. h>
nude < Corio.h>
int main ()
tlmut
is greata than the mtddle elmit /
low =mid +1; l then update law
slue
high =mid- 1; k ! Key slunit is Smallen than
mddle elemut thun updatt high *}
ilse
shmuit nt faud;
3
stusn o;
161
outhat
(n)
6
Enta slemuta he aay
5
9
Entu Kuy tlemt to le Seanchud
Sanch Suas7ul
Biasy Seandh
162
USER LFINED_FUNCTIONS
Lrtaoductíon : Lutuoduet io n
Junction : Junction :
to buak up a buoquam into heg ment,
ctnables puoquammeu whtch Can be wttlen
Communl known au Sunchion. each oh
Ydependnlly of otheui.
t function ia a bleuk of code ulhich pufoums a pauttalan
faak.
Auarlagu ounctitens :-Advantagu op Junctions . -
Modulas&gation:- lauge puoquam Can be diuidd into a sule
i
oß aeunable moduy. Jhis puocss is caud as modulauiz atfon.
Ii. Resabitts:- Asunution faPA ulattun
itun one bul Can be used.
any
numbuu of temy .e ît+alows the UAm
alows the Usn to ueuhe the Codo
it Eay to debug Iduntiying and inolattng an euuo4 becoms
Ainee th uiu Can divide the puoquam Pnto Beuies of
acuheab moduly.
ív Built libua ay:- A be unud by many othee
funetion may bu
function&. i.e a uicu Can uluitu one hunetton and F can
int n, n aeAult
puinif ("entu any intqui\n;
Scang (u Y.d%d', yn1, n);
ehult add (n, ) . / function call
puintf The aedt ia 7.d \n", esulr):
etuun co)
int add (Int numl, nt num )
int aumj
Aum /(OR) Qetuun Cnumi tnum);
etunn Chun)
IOutpuf:r
Entuu
any two ints
167
/*t puoguam to jInd bquaue of a numbe ustng uackon
tinclude<stdio. h
#inlude <conio. h
int bquaue (tnt num);
Void main ()
int n, uesult ;
clusuc))
puintf ( Cntu any fntequ\o;
Scanj (' d, Gn);
Qesult Bqu Cn;
puint (" Squaue of %d ia 7.d \n", n, aehult);
gutch );
int sou Cint num )
Output:
Entu any intg
168
Sunttion Pana malo:
fnput that fhe fua tion laku ia hnoun u fauome leu agument,
I'auomdlu: To tuanafen da ta yuom Calling Jan tion lo call d Junitton
(ou) fuom calld funton to calling 7unt lion, lale uae panom
Pauamea Tpu;
- tual pauametes (Ralpauamteu)
Q. foumal pauameton ( Dummy pauamctu)
.
Atual Pasamela:
x Jhese pauametus oaue aho calle d as Beal pauametea.
X Jhe pauamelus that aue uhed in function call aue
actual
ou aeal pauamutuus
* ihual pauamtus a the valuu that aue paud to fhe unction
When E i6 inuohd.
* Aetual pauametuuA Can be Constant, lauiables ou expuslon.
*Aetual pauametus bund lalae to foumal paua metu
pauamet
* Addus o actual pauamefas Can be hent to founal paaameta.
a. Soumal Pasamui
* foumal panamfuy aue aho caled as dummy Paua nefe
foumal pauamétus au lauiableu dipined by the Sunction tha
Guives Ualaa uthn the functto n ia called.
Foumal Pauomtus aue pount in unction defnition.
* foumal Pauametua Should be onli one Vaulables
+ foumal pauamleus aucaive valuu fuo mthe autual pauamefu.
foumal pauamufus Contains add uu. ohould be
169 dulaued as poinfuA.
Pasamden) A;umeaf pasuting tuknigua i
Jhe trchnique by ulhich the pauamtea ou augumenth aue
paad aom the caling 7unctlon to the called funetlon is
to as pauamu tcu pansing technige
Calby ualue Cou) paw
Pa by Value
.
Cal by aufuuune (ou) pan by ausuene
Cal
. Call by Vaue:
n this tehnique, the caling Suntion tuanifes th eualae
actual
pauamtun to the couneupon ding joumal pauamfus
in fhe Called Kunction
Suncton
Jhe uala of actual pauamefu Juom the Caling unctian to be
Copid into the foumal pauamitu caled junction, Hene
the name Called by Vaue
Any chang in the Valae of Soumal panametes in Calkd tunctton
il not o change to the atual pauametus,
the data.
Jaia technique paotuts
/: Paws by Vae+/
Examplei - # incude <stdio.h>
koid fun Cnt num);
Loid main C)
int x 8
num a num + 6
Qetuun )
Qutput:
num 3
num 3+ 6
num 4
ajfut
Because changt in fomal pauametuu (num e) wiilnot
the actual pauameteu.
:x3.
X3
aA
A ApuogMam to buuap &numbuus uaing pas by Value+/
t ineude <stdio. h
fincude < conio. h>
Void buap Cint n, intn); lfunction delauaton.
LoTd matn l)
int a= , b= 22;
cluseuc)
painty (" Bojoue hwoping\n';
puintj (a= %d\t b /.d\n, a, b)
puintf (" Ajt funpingn');
Sulap (ab); dunetion call.
t ( a 7. d\t 6- 7. d\n', a, b);
171
getch );
(48)
Moid dwbap (intn, fnt n )
tnt emp
emp n
4etuun ;
Qufput
6ujoue Bo pping
be
Ajleu hoapping
b
cluscu c);
muliply C); tunction call.
174
Void multiply )
int n, n:, þuod;
puint (" Enteu any
Stans (" /.d7e", n,n)
oActuun;
Qutputi
Cntu any numbeud
5 3
Besult iA IS.
int n, n
cluscuc); numbualn).
putntj(" Entem any
`cang (" 7.d d, gnn,gn);
Muttiply ( n, n);
qctchc);
Woid multHiply (int ni, int na)
int þuod,
puod
4etuunj
Out put:
Entuu any tuo numbens
Hetuun (nn)
Qutput i
Enteu any two num bu
3 4
177
4. uncfion wi h no augumunta but ot ih ochun Vala :
On thia calt,hesu ia no data Iuanah huom lalling huniton
calud yunion to caling juntog
Taunsg juom
but thtse i data uaniu tom
a value, the calltng Junthon
ahn he Xuneton depinton a4uuns
Qecives only one value uom the called juncton.
/* Roguam to maltiph numbus +/
7 incude< stdto.h
tf include< conio hz
lnt multipyc)y
Void natn c)
int puodj
cluse;
puod mliiply );
pulnt (" Ruult u 7.d\n', þuod):;
nt multiply )
int n, n2
Pant ( Enta the valu oh ntnt and n \n'
Acang (/.d 7. d", 4nn);
hetuun (n1* n2);
Qutput:
Enteu the Wahu o) n and n
2 |2
fact Co) |t
Recunsion tach call eithen holve One -paut of fhe
puoblem ou adeus the Aye of he puoblm
The cal that holvu one paut of the puo blem id aeh uuud to au
Bae Cae and the unaining Cuhich que the Aig of the puoblun
is called Genuel Cale.
tnt Quault, nj
puinth (" Enteu the value jou n\n)
paint (" Facfoural octns
7.d 147. ', n, ehull);
gutehc);
int faut Cint num);
/Base Cae
4utuun)
actuun (numt jout (n)); lGnual Caue.
Qutputi
Cntu the value fou n.
3
Putouial of 3 iA 6.
180
ii) 5 8 I3
Qetchl):
Ftbonati Stutu id
Outputi
S01 2 3
182
Puoguam to pas entie aaayto a utton 7
# inlu de < st dio. h
void dinplay ( int al));
loid main C)
3
Woid diuplay tntalJ)
in ti;
tou Cle oj I<s, itt)
puintf (u d\t", ali);
0ufput:
2 3
183
StJheouage clasy speciflad:
tope and
Vauiou4 Blouage clauu hawe difuunt A Lf Hn &
lautous dtouoqe clastu in i' au Llautfred a jollows.
Gocal
lautablu
Q. Global lauta blu
3. Statrc aua bly
4. Brgtateu Waufabla
(. kocal lauiably:
’ Then aae the Wautabld dulaned tnside a funetion.
’Jhey aue aho ufeuued to as automatie Vautabla
theue autablu ae Cucatud uhen a functon ia calle d
and deatuoyd auto matically ulhen the unchon i exctud.
conaiduu the fo owing d junc ton d
Noid fun lC) uoid jun l)
int x=20;
Q. Global Vasiably :
Jhue aut the Vau'a blu declaued outaide a
Jhue wania bly Can be acesae d by any
afoncton
nctton tn
Vhuy aye active and alve
Hence fhe name
thuoughout the en ti e
184 puaguam, global vauiably
l tode to demonsty afe global Vauta blu
tt tncudesstdio h>
#(ndude< conio.h >
fnt (ount 76lobal Vaiable.
\Moid þunl ()
lord hun 2 )
Count (ooj
funs c)j
punt ( in man un, Count - d\n" Count)
Qulput:
(n
Suncttton l, Coun t too
tn unctro n Count =loo
185
3 Statie aulables :
\laluea ob Slalic tla u'ablu peuatat4 until the chd of a
puoqam.
Static lautable aue tntraliyud only onte that is ulhen
the puoquam tA Compiled and
and nuWu
nikalged agatn
Stattc lauablu dulaud by wing kuyoud sfafrc
Examplei Statrc int num }
ntt)
Quetuun
3
Vord Mamn C)
tun C))
tunC),
fun C) j
186
Qutput
187
Module 4
Strings
&
Pointers
IH I 1-t_ft l ~[_J~ L~ J [Tl l\O l
e, 71, cA_,
>
~
;) E~ :
~
I
a W..!A.w., ~ v ~ N\C\N\11.v cru,,.o ~ o., ~ '°'b 10
• ~ ~ -~ ~ L', o·)
t,
I
.lv'\.l.).)N..L - I
1- rl ' ,-\ I
~
l
~o l
LO) ln t2-') r~1 f+J [5] [,] [-1J rs1 [9]
188
:it;; [n
fo)
l_e,1~1~ 1. o_l__[wI
{1'1 [2.J f~J [41 fol [~J r:n
O l R-
rBJ
I L-
[C\l
I_ 0
tol
I \lJ
tn1
(~3: ~ ~ CV., 01M, ~ i ~
drtvv .s. [I OJ ~ s \ ~ I 'o I ' 0I 'd I D' .... A 'y r ' I 'i 1)\ l. '
1 ' ' ' ,
'
'
I
,/ , . ,
I I
JJ
189
~ -[~~ ~ 0,Y¼l st ~~
u I c, [Link] s1;;, r o l ~ " I· &tf ,1 ,Ja,J,ol" ;
'\J I
'\) ,U;:cJ- ~ ~ ~ ~.
~ 'i ~ .t- ~ -o, ~ -<hi ~ ~ i
..t,~ .(,fN/1. -1 /V \~ ,w.J,t,
" . s~
-, ~ ~ °'- ~ ~ ~~
~<Ah
~~ nk ~ ~ 4 "
e,~
-, . A-
._. ~
~
a
"°'- t-, : ••
=a-
.
Q_ + et
J
J
;) \\ ,,
~ s,t.;:.,.
~
, I
~~
.
-~
~~ ~ ~ ~ ~ ~ ~ ~ I
> _( '! ~ : i I
0
: •
M, anvJ.
, eJ1>1.,0lv ',
~ ~i
~ - UGc,v\Jv
•
Dv\. ~
~- ~ ~ °' teu. CUM'.8"""e.t
t G] ~ '-' H<ll&,) •
190 )
~~ t,c fG ]~
S,\,\ = s.1;, J. ·, // -" [Link]
.r 2.
hMAt ~ ,t;}<MJ ( ~ ~
,\',c(,l,Wl!o,~
) JJ"A ~ Jvo.Mo1
,~ 1 U,u, ~ p r~
o..b ~ ~ .
11 k
~ " :: " ~ ' • ; 1,~••
,i,,, ~ 't ~ -I M lt -~ ·
S J~ ()
r ~
. 54a·c)
·I~ ~ - ~ ~ U,Mo\., lo, ~ (WU , ~ a- t; ~ . :
~h a_ vo .M ~ a,w,,l ,5.C ,Wlc t.- - ~
.(CM'\, eAi1tuX k °'-- ~! ~ o91.,, ~ ~~ · •
~
4
t
•4
.4
•t
t
-
•
•
4
•t
•
•
~
191 4
I ~
l v ~ ivJ,M.
l~
-I ~
"
l
'~
l "
1~
[: :.1,,1,n r$ \), ) i.
l "'
r 'j
•"\~1
~
'J
-~
"'
;;J
:= :vf ~f ~~ ()
~1~ '
s ~ ~ .lwi5 ~ J , ~
I
st ,, :~ ( ) ,
-~ ~ ~ ~ ~ ~
~ 1A, WM '\J, _a-
::) ~
~ lMlt:.l ~ c.-t-,v,o,.,Ju~ -¼\
~- ~
t - !u; F
~ ~
., ~ ~ ~ -~ . [Link]-- !Pt..-
;) ~ p ~ , ( h ~~ML~ ~ J tw , ~
) w J ,l ~ ~~~,if;~ ~ ~ J.
.~ IN \,tl ~ ~ ~ ~ * Ovl, ~
' wJ;.:,t, 0-. ~ - , J , ~ ~
(1, o.M-
,M ,!) w. l:,
-, . . .
wJ,l .l,.z ~~ .\
ti, f'J.,J,.t \9-\. ,uu:;- ~ [Link].J.._ :
~ ·
~
[Link]- ~ C ~ g i , ~! 2-) -7
192
. s ~ c ) {w"\Cc~"' ~ ,< W \ ~ v:,,),JJ.., ~ O Jv -- o--6
. ji ~
~ l o w6 ·
~
v~ z o ft-wi,
~~
.J-- -W\ c:ti, W t£
J-- -V> k M
~
. J{ -~ -0,_ J~:, 0 ~ ,i f W \c ;U ~ ~a :i- ,t), 1w,
&~JI ~ 0 \/ Y '
/f~hiv
~
~ ~ .t ff 5 j
t:- \' ~ C~~ll
~ ~
t
:i- fr~ 1 ~ ,, ~ c ~ ti J '
c-WJ✓ w-;
AJ- & t ,: : ~ ( ~ '\ .~
I 1 ~~ 2 -) j
:=
\r
I ~ { (., 1/. &\ Jl<l-) ;
I
193
~~
.0 /~ 11 \M ~~ V 'I \.
1 c\,\
,(;\,'t ~l~ \t, 01, ~J'-..2.\'\Ql)
, t.·,,v~ lt N\ )
ck , v c ")j
~ f C~ 4 ~ (:J;; .1- J \:,,/);
s 4 (" 1/,S", ~~)~
k =:~C~.t)j
f'~4C'¥1
~c~sr ~1 cc1,&\Y'\
w ;; ~ ~ ¼ 1, 0 \1 \' ')
J
4);
8 ~ ( '1 o/,S
"~ ~ 1 ) j
~~ ( Ml\, .i 1 ,.J;j
; .2-) j
~ t c~-~ &t,crt ~i ~ \ri" I 6-k:i.-)j
O~"(fl\C);
L~---- - - - - - -- -
1~ :
I ~ ~
~ q(dO;- "\
i), V\ , .(_ )
4\dt-0
~ ° ' \ &t"-Ws~.i=b
~ .\. \-\JLv \ o l
l
194
- - - - - -- -
\-
' /q., p,.,.,_~Mvwl, .to ol, ,\M/0 \M;'\11,<'\ h ..c,loi:c ""'f ~ l )V \ ~J
~ ~vV{ t,v\,("~ t -<. sht (o- h ;-
t\ .,\M,vtA.~\. .( <~ v,A:o ' \.\>
t~l\ .\ ,\ll,,\;ch I.. 6,\,\,~v\ ,o ·Y\ 7
\ CQ "<-t v\ ,o.d•'" ( ')
t
,<;V\{>J\.. 5k r2 0 ·1 ~ ,, ~ ,, ~
.,wv\,- ~ ;
vt t~ c) ;
·1""4 (••~, 1 N> {» ci ); ;I, 5 '-" '',
f 4 C." s ~ ~ ~ ( 4 :L) w ~ ,
\,V\ ,, ) ·,
~ (" 1· 6\ ~; t) ;
~toMAA- ~ ~
4 ! 'r 5K )-) ; c~
lf ( ~ J =;; ct)
~1 (~>o)
~ fC '~ q 1 ,V, \~ Rr>.M. ~ f - "" '') i
I
l
l
l
- I
195
I
') /<k fMrlCIAM to· <u,4,uh
\) !ildx"" ~" - t(0111 t/
\) -I\ \ N , ~ .. ~,clt <6 ~~J • \i\,~
u
~ . ,ti i\,\,\ vlv,~l . < vO•\I\M) ~ 1 /
() \ ;( QA~ \1\1\,0UM., ( }
I 1
~
, e-~\CJ\ ~ l101 ,
~(),
~ ("~a ~3 \VI" ) ;
1,k ,(~) ; j[d'l H) ~ ~ ~ ~ w .
Q
1==-0 .'·.)
~ c~r-n, = , \o) .,
1
J
~ { ( ~ ~,tt c- 'i ~ ~
d~c )j
}
196
- - - - - -- - - - - - -- - - - -
J~ f,wr to ~ (,\_ -v,M1w1.h-Ul, ~ ~ a °' wl-lf4.
~~IA."' r
4\' .N\l\,~\Nlt. <- Mc:l~o, \t\ /
~ V1\ C-t \/~0 <.. c~..\I\M• \I\_>
Vlll~& ~ C)
1
~~1 \10], ~2 -L 10 ];
~~ -
,1,, )
J ~()'
)
~ t C"~ ~ l '""l,;
aJ,; c ~ j )~
~ { l" ~Q -l M 1/.
~ { (" ~ Q ,_ ;;, f,
~~ (_ );
- 197
- - _ _ _,_ _ _ _ _ _ __J
~ ~ - - -- - - - - -·- - - - - -
~ !« IA_ r·:r,(,wY\ J.o l/l>V' - F ~ & t, ~ ~ - 4 ~
\) 1~P\,\"' I
\) \ \- ,v\l\lJ v\iott. <. ~eJ,~ , V\.>
\) \ \ .W\[Link],ctL <.. t.o-,NW • h':7
~
~ \J Pt~ W\,C\.,VV\ C)
) 1
) ~ ~j ho1 ., ~ 2 11°1 ·,
~J'
(~1j '
fl'4 l" sJ w -~ J \v,"J:i
l~.-"?c~1 ");
~ i LC ,~ ~ a .,_ "' °' J;
tlJ,., ( ~.2 \ j
1,, ::: D j
W,kJv ( ~ ) \i] = "\ o" &..~ ~~ '-"~ 1:::::: ~' -l- t l]
11-t- + )'
4" C ~f l, il n ="" stc,f n J
r:, f~~ (\\~ .i CW\cA ~ .J_ W\ L ~CU VV\, {,, h J~
~ 1 (~tC3J > ~ ih 1)
r ~ c~~ 1 7 st : 2-J'):,
~
r~ t ( ~ .i- ~ J~ \l <_ 2ll
i~ ("); .
1 r - - - - -- ---
~ ~ -.
~~\WAll~-
~ UJ\AM~ _L ~
198 u¾ - 1 ~ ~ 2-. ~ ~
I/t- ~~ ~ ¼lvvvt,~ J,wv ~ ~~~ -
~Vv\ 4:- J
-'v\A ~l < 6tol.(o, l--\ >
.NV\vt\Nctl, c V9VvW I h.>
~ ~~ i \.2.0] ,~[lD ]j
~t ~) 1;
~C);
~i c\~ ~ 2 •• ,, )_;
~<lb- CS,l;i,-'-- J; Q
t.::: 0;
W~ (~..t \{] I f
::: '\0 1 j
~
1
pAW-1{ \" {o,,,.tAJ;~~ ~ 1 .i:, 1/. S \_'Y\\I J ~ ~ J•J
~ VY\ () )
~199
1
j
II .- - - - - - - - - ~ - - - - ~- . -
I
I 200
-pointes [s.)
a wauabte that crilais o totos
Naddus o anolhe Vaiable mumoy location
same data Jhe two imauy opuaos
d uith ond4
onU e
Lhe
Vaialte
to dine onn
DEFERENCE d a
ponto.
eelaatio
Like
e dclard vauiabte aon aiabe mst
toe y Lhe
dutonce
opaten *) is sd te cclaing boi
syntax :
Vaiable
datalype
-dalalyp apucties type onin t it can be
int,
char, eat e
Poit Vauate s a
Vaiabe t at hotds he
adds o anothun Vauable
int tpti;
toat *pti;
201 (45)
L
sntiaiyatio f a c y od omigning add
Ihe
known
o vauàltes to onte Vaiable is
Snilial'zaliorn o onln Vaiable
Jhe can be one in 2 wa
inilialigatim
tolos
SYNTAX:
202
to a Vaiable i,
hun ws value can e accsed y
Dpuale acto as dutenu opualoy.
" accessng he valwe o The vaiables
to
Waiable
Eample
#iudex oLdio. h)
Votd main()
OUTPUL:
Lh ontent n Va is = 50
he content n Vo
Jhe
by aeng dtneing poii e 50
conent in ati is = l001
The dd ova is
50
2047
Van
A nomal vasialde eVan' has a memony a d d s of loot
Va l e So.
v lemunt sng
paint netaion is as toleus
* (aayame+ poaiton)
actual arametes
Any pdatus made umide he cald tuntun ul
moeity the ouginal copy ainewe dinctly modiing
hu conlet o he exaet memey dacation
ta i ncude<stoio .6}
pointU atb pointo to
wap ( i t *a, nt *b) /*
void
n m1 and um 2 usp*|
int temps
*a = * b
b temp;
main ()
L uput
205
Numb 1n 2 = 05
A cop aclual aquments Zhe addus a c u a l
is hased to toma -agumnts is a d to
agints o the caled tomal argumt the
tunet^ nd ay chnge tuncen. This
calleo tuneuon
made to he tomal mby occng
guents cn caled tunet the ddsoactuat
haue no tct -argumnents we
Vaues t actual avguments ter then ithin
caling tunetien the c l d tuntiom.
5.12]
Peuilo povLde oUucr ccrs mumey
Paint pede to s t n m oe han 1
value to the tunctio.
Ruducs hu sleaye apud and comple ty oy
thu
Ruduces he
eetion time ou The
poogam
edes an tnatue to
206 he
vay lement.
can be sd Io has intomalion back 4
Dhe caluing f cald tuneth.
ws to tpoyem dutnamic memog
alecalion and ole - allecaon) .
with ceuct
Values, t might ead to memey
dad
207
coupiori
Different types of pointers in C:
It is said to be good practice to assign NULL to the pointers currently not in use.
//Program to illustrate the use of NULL pointer
#include<stdio.h>
int main()
{
int *var = NULL;
printf(“var=%d”,*var);
}
2. Void pointer:
The Void pointers in C are the pointers of type void. It means that they do not have any associated
data type. They are also called generic pointers as they can point to any type and can be typecasted to
any type.
Syntax:
208
//Program to illustrate the use of void pointer
#include<stdio.h>
int main()
{
int a=2;
void *ptr;
ptr= &a;
printf("After Typecasting, a = %d", *(int *)ptr);
return 0;
}
3. Wild pointer:
The Wild Pointers are pointers that have not been initialized with something yet. These types of C-
pointers can cause problems in our programs and can eventually cause them to crash.
//Program to illustrate the use of wild pointer
#include<stdio.h>
int main()
{
int *ptr;
printf(“ptr=%d”,*ptr);
return 0;
}
4. Dangling pointer:
Suppose there is a pointer p pointing at a variable at memory 1004. If you deallocate this memory,
then this p is called a dangling pointer.
You can deallocate a memory using a free() function.
209
/* Program to demonstrate string manipulation functions(In-built functions)- strcpy()
and strlen() */
#include<stdio.h>
#include<string.h>
int main()
int len;
printf(" string1 is %s\t string2 is %s \n", string1,string2); // both sting1 and string2 are same
return 0;
210
/* Program to demonstrate string manipulation functions(In-built functions)- strcat()
and strcmp() */
#include<stdio.h>
#include<string.h>
int main()
char string1[20], string2[10]; // both string1 and string2 are not initialized
int result;
scanf("%s", string1);
scanf("%s", string2);
211
scanf("%s", string3);
else if(result > 0) // strcmp() returns value greater than 0 if string2 > string3
return 0;
212
/*Program to find the Length of the String (with out using strlen()) */
#include<stdio.h>
int main()
char str[20];
int i=0;
printf("enter string1\n");
scanf("%s",str);
while(str[i]!= '\0')
i++;
return(0);
213
// PROGRAM TO DEMONSTARE STRCOMPARE WITHOUT USING strcmp()
#include<stdio.h>
int main()
char str1[20],str2[20];
int i=0;
printf("enter string1\n");
scanf("%s",str1);
printf("enter string2\n");
scanf("%s",str2);
i++;
if(str1[i] == str2[i])
else
return 0;
214
//Program to concatenate two stings without using strcat() function
#include<stdio.h>
int main()
char s1[20],s2[20];
int i,j;
printf("enter string1\n");
gets(s1);
printf("enter string2\n");
gets(s2);i=strlen(s1);
for(j=0;s2[j]!='\0';i++,j++)
s1[i]=s2[j];
s1[i]='\0';
return(0);
215
// C program to copy one String to another Without Using strcpy()
#include <stdio.h>
int main()
scanf("%s",s1);
s2[i] = s1[i];
s2[i] = '\0';
return 0;
216
/* Lab Program 11: Develop a program using pointers to compute the
sum, mean and standard deviation of all elements stored in an array of
n real numbers. */
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a[10], *ptr, mean, std, sum=0, sumstd=0;
int n,i;
clrscr();
printf("enter the no of elements\n");
scanf("%d",&n);
printf("enter the array elements\n");
for(i=0;i<n;i++)
scanf("%f",&a[i]);
ptr=a;
for(i=0;i<n;i++)
{
sum=sum+ *ptr;
ptr++;
}
mean=sum/n;
ptr=a;
for(i=0;i<n;i++)
{
sumstd=sumstd + pow((*ptr - mean),2);
ptr++;
}
std= sqrt(sumstd/n);
printf("sum=%.3f\t",sum);
217
printf("mean=%.3f\t",mean);
printf("standard deviation=%.3f\t",std);
getch();
}
218
Module 5
Structures,
Unions
&
Enumerated
data type
219
~ ------ 4 ===.::-~ ~ - ~ .J [ s . 1]
~ ___;;;-
~~ ..u. --[Link] 1 ~ 1 ~ ~
~~ -[Link] ~ ~ P-, ·
~ ~ ;
l;
220
I
I
•
•
[Link] STRUCTURE [SYNTAX]
01.
•
--- ---- --= === -III IC: Zl: :l:~= = = = = =- •
---- .i•
~ •
•
I
~
~ YYl~ ;
1;
221
-lYU ~0 .
) -Ll'\..t [Link] ;
5; 1 .6.U • d 1 , ~ ;
~ ~ .4Cu .,d .j_ ;
-Lr\t ~ o ;
~ ~;
~ r'Y),a.n,R/4 ;
l STD;
~TD '6Xd i , ~ ·,
~
--0-t Lh e
'•
.~t u., -u _ ---eo.n ...lx ~ -~ t
1 Xh.-W1
:h.r yu -..d__t.L~~ .
i
•
4 S\INTAX :
4
~
•
•
•
f
~ m~; 1
i; C
4~~:
. ~ ~
t
~ IL.() ..yy) e. [ '0J ;
--l/\.1" ~ () )-
223
~~ ~ ,__ --- 4 c~~-~
~~
~ t~ ~ ~e ~ G~
~
J:'~ ~ e Xo 6.
~ -t., -f:>-..c\.½ ~ .:to ~ --a.n. .oL
~ 0
1. ~
PA gI NG I N DI\I l DLl A L 1V1 E fVJ BI: Rg OP A S TJ\ UC T U R E_
~ 03.
\J' PAf glN G THE ADDREg~ OP STRUCTURE
~
~ n--; ~ .
,
'.) ..u.->< ~e
> 224
)l
# i t'\.C.l.u_de <. ~ ·n>
\Jot..d ~ Le.. [Link]" '...u\I ) ; II ~ I) ~ I"'\ •
~ ~
i
~ 1,b;
} A:: ~ \0 .2..01;
1
v ·~ [Link]) C. J
1
~l.?;
~~ ( A--l, A .. b);
~.Jc.h ();
}
"o-id ~ e . [Link]-- ~ • w- ~ )
t
~ ~
1
~);
~ ~ 10 ~ J...o !2.0 •
225
t4 PA3~\NC, (NT\R t STRUCTURE:
~ _e. -C.O.n -p..a...½ ...(..r(wu _ ~ ~ -CL ~ ,.., ~ UJ'Yl .e.,.d:-
~~ ..liR..e. ~ ~ v ~ . ~ ...a.. ~ ~
~ ...Q/2 -Of\ ~ [Link]- I _l.;t ...U, ~ ~ --C..a..U,
't~\I [Link]..t.e. re-, d-h..o-d .J.•• t. --a_ ~ °1 ...A...0-Ch U'YL-6 V , ..the.
YY) 1
I~ t .Lb ~ .
1; I * r~ .:to . ~ ~ ...o..nd ~ , , _.
t #=iru:.[Link].<~-~~ ~ ~ "/
1ft in.c..1t • d e-<.ur-n..i..o ·h>
f-'o-i.d ~~ (~ ~ . ' s) ;
~ ~-
~ J. b·
l~ A
& = '-1. ,~.2.01;
o-t2d. rn [Link] ( )
~CJ;
~ ~ e . (_A);
~t?;
~
~ [Link]. ~e.. l ~ ~ s)
·- - ~ :
~ ~lo
E 226
~ PAg~JNG TH.[ ADDREfg OF fNT1RE gTR_ UCTU RE:
in ~ ~
, .:th.,L ~~~ 0--, -0. ~ V ~
~ ~ .to ~ t Uf\-c"L.:o-n ~ ~ -Lt 6-'-rJ
~[Link] :.e..
4 / ~ r~ Xo _.d..e..r nffY\.-6X,ca .te ~ ~ ~
~ .tJv_ ~ 1~ ~~ /
:8:i t'\.[Link]..Lde~ ~ - h ~
#-i [Link].. cl e..-< ~ h'> I
void ~±~ -1 e C
-- -er- ~
A, ...... _. . ...[Link] ~ s) ;
~ ~ .
{
JI\! --l ~ b j
j A ;: 1 to_, 2. o] ;
\J o-icl rY) a.1n (_ )
~
~ t '.) ;
~~ l+A) ;
~l.?;
J
V otcf. ~ o.n..te. (~ --0.X...US. 1'-S)
i
.fu-r .inti l '' -lU\..nXh / d
r- -- -7 u -· -1.6 . · \::t- b~ -th ·/.d \1.,••, l:ws). -l, l*s). b);
}
4 Q~l AT:
227
l? =-==-l..r\~.,, rs~ 41 ]
~~ ~ ~
l\ L.----l..,,~ a,r., 1 ~""'--'
~ We .:to ::0-,e 1
~ ~ V Q.)'(_L~ .
ip; ~ e.-·
~ ~M ~ ½ ~ oj
~~ ~ ~
.in -Th C o-/i:t-<llrvLd,. ..ct_
~ _,th t ~ 1 ~ ~ V .
f~ °l ~ , -ure. ~ -ti<U. -0 ~ ~ ~
t~ e . n l : h..[Link] --0..n.-d YY)~ o i , _ t ~ . .l.r, Va>t..uru..d
'. ~ ~ \ ; ~ . .
t ~ ~, ~ ~ °b
~~~,
in -<..v< ~e. ..o..r.
l.,.:, 1
~
~e --[Link] ~cn:t- · ..0-.e ·~
7 . . . .- _. - ---_.. _.
i., 4
-0\.. \J~ .
b
f~
,'1,
~,~
J,,228
p ____1-f>_ _ _ _ _ _ _ I"
I,) ~ "1 ~~ ~ .
y
w)
~ ,,,,....
229
JNIN
Unieni
Sinilag to stauny olletion
Vaiates
at an Bne
3his me
means the LJnion rnenbeis, all eha
he Same memat
membey eah as t loctfon.
enions
Dedantion a Wnion :
t.
Kewod unien
Sytay :
Lninname
nion
Vanname,
Sotatye
Ata-type Van name )
230
965
Examle
unien
cha sn[e
cha name 15];
be lse t
Ntz: Jhe tped Kegloon Can
stud name
tud. WSN,
ohee d ’ VasiaS)
&tu nane
name WsN menb
noln
names
232
Sntiaizatfon o Unfon.
Aota.
data
to ohuawe the
Corvid the tolloing yample
Mali zed
e to be n
tipedet staut PoTNT 1
it
Union PoTNTa
tipey
tn ain ()
233
too1dinat q P
7.d, p. x,Pl))
ond
coeadinátis 2P2 ae V.d
234
235
cocdinat y thu ("punt
P245)
P2.4),
cocadinate paunt("
the
Pl:4)) x, Pl- d', and
cocndinalis
PI The ln punt(
P2j PoTNT
3y; {2 PoTNT
PI
Mainc)
y nt
Lnt
PoNT2 Union Gpey
X,y) int
cut topeiy
PonNTI
Output 2 and 3
-the tooadinates q Pl ane
cons tratis a P2 is 4
-the x
P2 5
the Y toodinatu
Union
Vauablus
Aan i nila to
stauituy.B t
Unon PoTNT
tikt X
nt
PoTNT points C3;
poirtC. : 2;
Output
Coondinats point[)
Lo a 33 and 3.
238
239
5
Mon()
<stdis include
ab-dat
data and funguam
fte
Butfile and
awe
dec tftle edat .
-coclename a cbt name ile
data Cxlenston
2 and
flu dat apeáy ifle:
e, pnegnam Cueott
C
an we e, "
bame the Cealec
n Can
be
e as : ledata ueatbng
Gatpat Bandaud
fle inAoucd
hat 8Cueen lou moni 1e tobent Data :Batput
yle
execuliou Slandaud
inbloaed keyboan
k d u ton Datcta el): (data file Lapat
diak haud instoued Colleclion &I4 Fi:le
B.data16)elated MbuE
AnT EM
ANAG
diantaqe g Cucatig and data es
Dak
Cbuoguam
File 'pohta has data tipe :
Ele (yeam,foiatu t
Fele i deficd fle).
lettae
) dec lelalon
240
puoguanhneee tnou t
onddue
cale ota t adduces te (b slouling add uea
le). Tn tu abeve
to to 4?lel. dat
dat eand
a So On
ekeetatan tloue. tu adduoe 3q (aurespo nd aq {l)
au e
Ftl. 1. dat
2 data
20 o
sze 5obyta
3. dat
50
3Medes
241
heye ae
3 yodes;
nill Head fuom a fle
6heulel
dees
wode "w: oquam will wri tz
t will be Cueated
’ exat t will veu ite append
Output to tae
ede % "a :
Cnol tu
ponquat will append
dees net enist t wll Gueote
kx: Ys topen "ta -dot 9)
Nore :
tieue
uncion fepenn
elwins coheu a pointau NolL
doesnt
’f°le name
ile toinlu Can be ta bome
Ex; fP fepen ("f Pa . dat", *a").
not n
de<ault dieetay
ffa fopen ("c:1 tuequam tile dot', *w'): 66
242
T6 chelk shetheu Not
FILE
nqite fopn ( lettet. del'?,
(nglr:= Noki)
le doenot eat \n):
Ex:tclae (fP1);
tclose (+P-):
felosc (+P3)
fnum);
abar leads and soue num
enomple
(B)
Recietnq Cos e
Ex;
inile
Geeal founm;
fp (detglil, "" fum at diy
slking" )
it Vauiable):
w").
{ eutjile % \n nun);
In this Cse
fiuat fasantaa 2le ata
Tt bends Value nto
245
to yead tu oll e.
quam
an to
# ndude <stdis.h)
Veid mainl)
nt
fLE
4R: topen (" input . dat",
66
):
open (" putput- dat, "w);
input. dat
Iol
Must exLst AJleu Ceuhsn 3eguam
pen to nill Copy t output- dat
. dat uto
wil! 2ead
input
[Link] into Sutput
Sutput -dat.
will Wita
-’
246
Programs to demonstrate the use of Structures
/*1. Write a program to illustrate structure definition, declaration,
and initialization of its members */
#include<stdio.h>
#include<conio.h>
void main()
{
struct point // Structure Declaration
{
int x;
int y;
};
struct point P; // Structure Variable Declaration
clrscr();
P.x=3;
P.y=2;
printf("x=%d\n",P.x);
printf("y=%d\n",P.y);
getch();
}
247
char DOB[80];
};
struct student stud1;
clrscr();
printf("\n Enter the roll number:");
scanf("%d",&stud1.roll_no);
printf("\n Enter the name:");
scanf("%s",[Link]);
printf("\n Enter the fees:");
scanf("%f",&[Link]);
printf("\n Enter the DOB:");
scanf("%s",[Link]);
printf("\n *****STUDENT’S DETAILS*****");
printf("\n ROLL NUMBER : %d",stud1.roll_no);
printf("\n NAME : %s",[Link]);
printf("\n FEES : %f",[Link]);
printf("\n DOB : %s",[Link]);
getch();
return 0;
}
248
};
struct student
{
int roll_no;
char name[100];
float fees;
struct DOB date; // NESTED STRUCTURE
};
struct student stud1;
clrscr();
printf("\n Enter the roll number:");
scanf("%d",&stud1.roll_no);
printf("\n Enter the name:");
scanf("%s",[Link]);
printf("\n Enter the fees:");
scanf("%f",&[Link]);
printf("\n Enter the DOB:");
scanf("%d%d%d",&[Link],&[Link],&[Link]);
printf("\n**********STUDENT’S DETAILS**********");
printf("\nROLL NUMBER: %d",stud1.roll_no);
printf("\nNAME :%s",[Link]);
printf("\nFEES :%f",[Link]);
printf("\nDOB :%d-%d-%d", [Link],[Link],[Link]);
getch();
return 0;
}
249
/* 4. Program to pass individual members of a structure to a function */
#include<stdio.h>
#include<conio.h>
void display(int a,int b);
struct point
{
int x;
int y;
};
void main()
{
struct point P={2,3};
clrscr();
display(P.x,P.y); // function call
getch();
}
250
};
void main()
{
struct point P={2,3};
clrscr();
display(P); // function call
getch();
}
void main()
{
struct point P={2,3};
clrscr();
display(&P); // function call
getch();
}
251
void display(struct point *P)
{
printf("x=%d\n",(*P).x);
printf("y=%d\n",P->y);
}
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20],usn[11];
int marks;
};
void main()
{
struct student s[100];
int num, i,total=0;
double avg = 0.0;
clrscr();
printf("\nEnter the number of students : ");
scanf("%d", &num);
printf("\nEnter the Student details\n");
for(i=0;i<num;i++)
{
printf("\n**********************************");
252
printf("\nName : ");
scanf("%s", s[i].name);
printf("\nUSN : ");
scanf("%s", s[i].usn);
printf("\nMarks : ");
scanf("%d", &s[i].marks);
total =total+s[i].marks;
} // end of for loop
avg = total/num;
printf("\nThe average marks for the class is : %f\n", avg);
for(i=0;i<num;i++)
{
printf("\n**********************************");
printf("\nName\t: %s", s[i].name);
printf("\nUSN\t: %s", s[i].usn);
printf("\nMarks\t: %d", s[i].marks);
if(s[i].marks < avg)
printf("\nThe student has scored below average\n");
else
printf("\nThe student has scored above average\n");
} // for loop ends here
getch();
}
253
Program on Union
/* 7. Program to illustrate the use of union.*/
#include<stdio.h>
#include<conio.h>
void main()
{
union point
{
int x;
int y;
};
union point P;
clrscr();
P.x=3;
P.y=2;
printf("x=%d\n",P.x);
printf("y=%d\n",P.y);
getch();
}
254
/* Lab Program 12 : Write a C program to copy a text file to another, read
both the input file name and target file name. */
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void main()
{
FILE *fp1, *fp2;
char filename[100], c;
clrscr();
printf("Enter the filename to open for reading ");
scanf("%s",filename);
255
fp2 = fopen(filename, "w");
if (fp2 == NULL)
{
printf("Cannot open file %s ", filename);
exit(0);
}
256
enumerated data type in C:
• The enum in C is also known as the enumerated type.
• It is a user-defined data type that consists of integer values, and it provides meaningful names to
these values.
• The use of enum in C makes the program easy to understand and maintain
• The enum is defined by using the enum keyword.
Syntax: enum flag{integer_const1, integer_const2,.....integter_constN};
Output:
The value of w is 2
257