0% found this document useful (0 votes)
2 views264 pages

C Programming Notes Module 1 to Module 5 Notes

The document outlines the course 'Principles of Programming using C' which includes an introduction to computers and programming concepts in C. It covers various topics such as the structure of C programs, data handling techniques, and the evolution of computers through different generations. Additionally, it discusses input/output devices, system units, and the functionalities of the Central Processing Unit (CPU).

Uploaded by

luckyuday3777
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views264 pages

C Programming Notes Module 1 to Module 5 Notes

The document outlines the course 'Principles of Programming using C' which includes an introduction to computers and programming concepts in C. It covers various topics such as the structure of C programs, data handling techniques, and the evolution of computers through different generations. Additionally, it discusses input/output devices, system units, and the functionalities of the Central Processing Unit (CPU).

Uploaded by

luckyuday3777
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Course Title Principles of Programming using C

Course Code 22POP13

Semester I
Module 1: Introduction to C
Introduction to Computers:

• Input and output devices

• Designing efficient programs

Introduction to C:

• Structure of C program

• Files used in a C program

• Compilers

• Compiling and executing C programs

• Variables

• Constants

• Input/output statements in C
Module 1 : Introduction to Computers

Computers are being used everywhere .


In Homes
In Offices
In Schools
In Colleges A Computer is an electronic machine that is used to
In Automobiles etc. Accept the data
Process or manipulate the data
Output the result in the form suitable for human
understanding
Stores the input data, instructions & results.

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.

Reliability : Versatility (Adaptability) :


Computers does variety of jobs based on the instructions given to
them.
Computers gives correct & consistent results always.
They can be used in colleges, hospitals, schools, for reserving
All errors are caused by humans, not by computers.
flight & railway tickets etc.

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.

Each generation of computer is designed based on a new


technological development, resulting in better, cheaper
and smaller computers that are more powerful, faster and
efficient than their predecessors.

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.

They were often enormous and taking up entire room.

First generation computers relied on machine language.

They were very expensive to operate and in addition to using a great


deal of electricity, generated a lot of heat, which was often the cause
of malfunctions(defect or breakdown).

Examples : UNIVAC and ENIAC

17 18

Advantages : Transistors replaced vacuum tubes in the second generation of


It was only electronic device computers.
First device to hold memory
Second-generation computers moved from
cryptic binary machine language to symbolic.
Disadvantages :
Too bulky i.e large in size High-level programming languages were also being developed
Vacuum tubes burn frequently at this time, such as early versions of COBOL and FORTRAN.
They were producing heat
Maintenance problems These were also the first computers that stored their
instructions in their memory.

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

The microprocessor brought the fourth generation of


Advantages: computers, as thousands of integrated circuits were built onto
a single silicon chip.
ICs are very small in size
Improved performance The Intel 4004 chip, developed in 1971, located all the
components of the computer.
Production cost cheap
From the central processing unit and memory to input/output
controls on a single chip.
Disadvantages:
Fourth generation computers also saw the development
ICs are sophisticated of GUIs, the mouse and handheld devices.

23 24

6
Fifth generation computing devices, based on artificial
intelligence.

It is still in development, though there are some applications,


such as voice recognition.

The use of parallel processing and superconductors is helping


to make artificial intelligence a reality.

The goal of fifth-generation computing is to develop devices


that respond to natural language input and are capable of
learning and self-organization.

25 26

IBM PC (International Business Machine) :

This is the first personal


computer developed in
the year of 1981.
Less amount of space.
Power consumption is very less.
Faster.
Input the data from keyboard.
Display result on monitor.
Today's desktop computers

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

Output devices : Storage devices :


Used to display(output) the information generated by the Data, information & instructions given to the computer are
computer in human understandable form. permanently stored in these devices.
Monitor, printer, speaker etc are various output devices. Floppy disk, compact disc(CD), digital video disc(DVD) etc are
some of the storage devices.

Fig : Storage devices


Fig : Output devices

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

Visibility inside the system unit

Motherboard
Central Processing Unit (CPU)
Basic Input Output System (BIOS)
Memory
Secondary memory
Cards
Switch Mode Power Supply (SMPS)

Visibility inside the system unit


39 40

10
Processor Random Access Memory (RAM)

Expansion card

Fig : Motherboard

41 42

A Computer is an electronic machine that is used to


Accept the data
Input Output
Process or manipulate the data Memory unit
oo
unit
Output the result in the form suitable for human
understanding
Stores the input data, instructions & results.

The above activities are done by various units in the computer


Represents Data or
system. Instructions
CU ALU

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

Central Processing unit(CPU) :


Arithmetic logic unit(ALU) :

CPU is the of computer which executes instructions with


help of Control unit(CU) & Arithmetic Logic unit(ALU). It is place where actual operations are carried out under the
supervision of ALU.
Control unit(CU) : It performs 4 basic arithmetic operations: Addition, Subtraction,
Multiplication & Division & also logical operations.
It controls & co-ordinates the activities of all units by issuing So it is named ALU.
proper commands.
CU is responsible :
To Fetch the next instruction to be executed.
To Decode the instruction(identify what action to be taken).
To Execute the instruction.

47 48

12
Data Handling Technique
(Technology)
Data Handling Technique (Technology)

Types of Computers for Individuals


computers

Analog Digital Hybrid


Computers for Organizations Eg. Thermometer Eg. Personal Computer [Link]

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

Digital Computers : Hybrid Computers :

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

Workstations It is used by a single person


Also called as Micro computers or Personal computers
It is small, low cost digital computer
Computers for Notebook Computers(Laptops) Used at schools, colleges, homes etc
Individuals
Desktop Computers
Tablet Computers
An independent computer small enough to place on a desk in an
office or home
Most commonly used as they are most affordable.

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)

Quality of picture is very good Small mobile PC weighing from 1 to 3 kgs


Huge memory. Flat screen display unit, keyboard & pointing devices(mouse) in
an single light weight unit
Disadvantages : Can run on batteries or by AC power.

Costly Advantages :
Not portable Portable
Integrated unit
Less space
Power

61 62

Disadvantages : Tablet Computers


A Tablet Computer looks like a standard slate
Costlier & expensive to repair It can be folded over a keyboard
Laptops can be easily misplaced or stolen Display system can be rotated by 180 degrees
Difficult to upgrade to higher versions Has all features of notebook/laptop computers
Very small keyboard with missing keys. Allows user to write on a screen using digital pen called stylus
Stylus can also be used to tap on icon (to select it).

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

Various software applications such as email, sms, voice


recognition, picture capture etc are available on Smart phones
Has PC compatibility Mini Computers
Internet access.
Computers for
Disadvantages :
Organizations Mainframe Computers

More expensive
Larger than standard handsets
High replacement cost. Super Computers

69 70

Computers for Organization Network Servers


Network : A Powerful Personal Computer (PC) for which many or
An interconnection of two or more computers using a peripheral devices such as scanners, printers etc are connected.
communication media is called networking of computers or This Powerful PC acts as a central storage unit which can be
computer network. shared by various connected to it.
Two or more computers are said to be networked or connected if Frequently accessed data & programs can be stored in network
they can exchange information. server & can be accessed from any other PC connected to it.
Networking allows : A Network Server resembles an ordinary PC but more powerful in
Resources to be shared all aspects & enables the users to share data, files & other
Exchange of information. hardware devices.

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.

Thousands of minicomputers & microcomputers an be connected


to 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

Output unit : Storage devices Memory


Devices using which processed data or information can be Storage capacity is more. It is Storage capacity is less. It is order
presented to user in understandable manner. order of 100 of Giga bytes or of few Giga bytes.
The processing unit with help of output unit outputs the result or more.
data into a form suitable for human understanding. Contents of storage devices are Data or programs stored in
retained when the computer is memory disappear when we shut
Example : Monitor, Printer Speaker etc.
turned OFF. down the computer.
Accessing data or programs from
Accessing data or programs from
Storage devices : storage devices is very slow.
memory is fast.
Computer needs a place to keep program files & related data when Plugged into motherboard, so not
Inserted in slots provided, so easy possible to carry from one place
they are not in use. to carry from one place to another. to another.
Purpose of storage devices is to hold data permanently even when Less expensive. More expensive.
computer is turned OFF.
Example : floppy disk, hard disc, CD, DVD etc. Differences between Storage devices & Memory

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

Application Software (AS)

89 90

System Software (SS) Application Software


Application Software (AS) :
Set of Programs which are developed only for specific needs from Collection of Programs that helps Collection of programs written for a
customer are called Application Software. user to interact with hardware specific application such as
components efficiently. banking, reservation of tickets etc.
Example : Ticket Reservation software, Payroll software, It controls & manages hardware. AS uses service of SS to interact
MS-WORD, Microsoft Excel etc. with the hardware components.
To write SS, programmer needs to To write AS, programmer need not
understand architecture & hardware worry about architecture &
details & hence are machine hardware details & are machine
dependent. independent.
Directly interacts with the hardware. AS will not interact with hardware
Development of System Software is directly.
a complex task. Development of Application
Compiler, Assembler, OS etc are Software is relatively easier.
examples of SS. Payroll, Banking software,
MS-WORD, Turbo C etc are
examples of AS.

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

Mouse Track ball Track pad Pointers in


Pointing the
devices keyboard
Input (Joystick)
devices Handheld
Devices Handheld devices

Optical
devices Pen Touch Screen Game Controllers

Audio Visual
Input devices

Optical devices Keyboard is a primary input device used in all


computers.

Using the keyboard, the user can type data or


Barcode Readers Scanners & OCR commands.

Audio Visual Normally the keyboard has 101 keys.


Input devices
Most commonly used keyboard layout is called
QWERTY layout since the first 6 alphabetical characters
form left to right are Q, W, E, R, T & Y.
Microphone Video Input Digital Camera

24
Alphanumeric & Character
keys

Numeric keypad

Types of Modifier keys


keys
Cursor movement keys

Function keys

Fig : Standard Keyboard Layout (QWERTY) Special purpose keys

Alphanumeric & Character keys : Numeric keypad :

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.

Page Up : to see previous page. Special purpose keys :


START KEY(WINDOWS KEY) : same as start key.
Page Down : to see next page. Short cut key : similar to right click button on mouse.
ESC : used to cancel the selected option.
Insert : to enter a character between two existing keys. Print screen : used to capture the image on the
screen.
Delete : to delete a character at the cursor position.

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.

Functions/Services of Operating System are as follows:

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

ANST'C suppoxts theee clases o cdata tpe


Furdamental olata type
o
(
] dened cata
3 ule dalinud olata ype
np achastacton (chai)
tnteqy cnt
Aoafing pofnt Hloat)
gat ype doubledouble
Jong
Vold oT

*haacten Ccha:- ASngle ge (& b14) apable


e hodding ene chaact e én doal chaacte
bet
&x- chat C='A';
The 8iy o Chasacter is 1bgte (8 btb)
memoy the chasact ee ae toud
using ASCIT (Odes (Ameian Stoandasd code
45 JendoHrnal'on itnchang)
chang)
The AsCII Vale ol A -65 ' a ' - 97
B'-6 'b' -98
3n Memos9y n' as not sosud but i oinase
humbes otmat value 6s) Btowd as
Shon Jselow
Lelloolooo
used o 8ignud chay act et
+

Chaact e (an Je stgnad o nsig nad


The stange yon dignud chatacty us
s -la8 to l21
The ang
to SS
* Integun (cint
These ae the numbes wthowt a
paut t9actiona
ÉXample 35 R
A Snteg tptally ayueta the natutal siy
o a intqs nLon the host machine
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 +

oafng pount Gloat) :- These ae numbey w


declmalo 9actPonal past
x 1 1.23
uses IEEE mat (ynsttit a
toatng pount
ele ctiCal and ElctioniG ungeesng to
epesert manttla and expo ner

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 &

Longobytes8obib3.4E- 493a to [Link] t


double

loat s
Sngle psucdslon loat ng potnt
doubie is double pu cia?on qloaling poirt.
Jong double s lttendud
tehate Po cision pofrt .

loat toum; olno


double aa, rad?u;dqroo)
Jong doubit numjonoeo
, tS
vold data type holds no vaue
@mpty dat a type
putnady yodoung (aled

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

• Type conversion and typecasting.

Decision control and Looping statements:

• Introduction to decision control statements

• Conditional branching statements

• Iterative statements

• Nested loops

• break and continue statements

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

Precedence chart is as shown below:

74
75
Sample Programs

/*Program to demonstrate working of bitwise not operator */


#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“Output = %d\n”, ~35);
printf(“Output = %d\n”,~-12);
getch();
}

/*Program to demonstrate working of bitwise OR operator */


#include<stdio.h>
#include<conio.h>
void main()
{

int a = 12, b = 25;


clrscr();
printf(“Output = %d”, a | b);
getch();
}

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

/*Program to demonstrate working of bitwise AND 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”);

scanf(“ %d %d %d ”, &x, &y, &z);

--x;
--y;
--z;

printf(“ \n The updated value of the X: %d ”, x);

printf(“ \n The updated value of the Y: %d ”, y);

printf(“ \n The updated value of the Z: %d ”, z);

getch();
}

79
/* Program to demonstrate implicit type conversion */
#include<stdio.h>
#include<conio.h>void
main()
{

int x = 10; // integer x char


y = ‘a’; // character cfloat z;
clrscr();
// y implicitly converted to int ASCII
// value of ‘a’ is 97x =
x + y;
// x is implicitly converted to floatz = x +
1.0;
printf(“x = %d\t, z = %f”, x, z);
getch();
}

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

Canditanat Biending Statnent: [3. ]


he Gonditenal buandtng statiment halp to ne
tout iu fusghaa to't anolku depending wheth o
not'. -uue dees6ion
'Contuol 6tatementt nude :
statenent
. - eke stateent
i -ele
cke - stalemet
butteh statenent

btatuent
uncondionol
longtönal

-cke||-ehe bwi teh

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.

he Test expuessien Volne eiheu stotement


1 1 ou
statemet block 2 wll be executd, but not both
bloclk a e execute ol at rnce.

-ese sament:

(tet capuesion)
Stotenent bock ;
elie

stateent blek 2

Stotement x; Fas sE
Test
Cpuession

Stalzment block 1 SIaltent bleck 2

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 *

# nclude (staio -h)


# nchude <[Link]

Veld Moin
mMaln ()

int

icluscu ():
uinty ( eata nti
4num);
(n um >o)

eiteved nun posilie");


che

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 */

# nclude <stdis -u)


# tnclude <Conio-h)

Void noin C)
int
clus Cu( );

bcan ("%d y.d" ruM, num);

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 -

sta leinent in neeled


6honon be low

Ypueasion 1)

bto tt nent 1;

ese

6tole me nt;

ese

stalement 3;

evauala feut. capuesten 1 tkue then


eopsibn Stalenment 1
epuesion % evolnatd
2 expuesisn
be sill be exeteo , incase expueeas n taen statemet
eceuled
Ihen statement 3 is erecuteol
faise
1

FAkSE
eUE Cprion

blalcnent 1 Slafenent blalenct 3

94
to Conpaur tioe numbu /

# clude < Conio " h

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

puintye, lsu than naM2);

1. Entu an tre nnbus


any
Lm 1 Hcolas lhan num
2. to nwnbns

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

nt num 1, nwm, wm3 ;


Clusu();
puint (" entau any 3 Mwnbes n):
(numi> num2 numI>num3)
ese
lasqet ");
num2>nu 3)
else
funty (*aun lauet);
pninty ("AuN3 lauqt");
qeteh ();

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 :

Caue t: þutnt e'sunday)


bueok's
default: fuat("
/end
Ivalid iapt");
Switeh.
qcteh ();
100
Gutpat:
enteu
3

2 Cntu dneday numbu


4
Tans da
3 ente any nunnbeu

4 entu any numbu

batuday
en tu numbu fuom 1 to

bunday ahy
entua nunbeu 1 to
1

Monday nunibu 1 tof


2 any
8 Ties day
cntu any nmben fom 1 to

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)

»P-td loepi Inca fe tat lap the CondtEon 2 chucked


ust, i Cendito n
Conitiou s lale then the
fahe
body CaecutedIacase
beoly'& not eecuttd Hene Ce
itmm numbu q întutien so?ble ik
and ale loop tt

pst tt loop: Incase 1 Bat tat loop be body Cxe cute dd


and then the cende tten
felet and leted las the name
bost tes t). ene ttette iniun uebu
tbl, s

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

Fou loop fuovides MeehaAKn bu wsich


wepeat 6et nslnetiu aqain and
Lnslhnclin nt Condi ha
(9he Condtten yarls ELeutle
tacku flace.
Foa loop pue tat
MEniu LuMbu
Fou leop ik ued fo Coustu lontaled loop
Conntes Contuolled lo sp:
We
advonce tractly ow Mony
tiner will be executid
se Countu onholed':
103
Syutax :
}on eapuestou 1 ; txpucion d; cnpueaion 3)
Stoteent 1;
Statenent 2;
/Body
the
loopP

tnithaligaon
Cupuion

Fleo chaut: cnlay


C p r s i s

Cxpueoson 1
Cp ueson 2

TKe
False

6tatement

Cit.
104
/s pueqam oto daplay num b

ne lude cenio .h>

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

H inelnde (con to .hs

Veld Main ()

int i, n
Khueul );
entu tte Valne fou nln)
Scany %d", n);
wile ?=n) / Condi Eou

pulnt| (%4 \n", );


L

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

or (init; Condilie ; incuement)

(init LnCHe Ment)

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)

bueak; hop ang byeak 6ta lenyent /


3

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

tu onttnue state nent k encounteuel


Conlirue; to 4 *

eint "%d". j): /eeeute


a fuiat Statemot would nt
lou Tue lou tle hep tuation whuc
Hetun (o): betase n Fuat Covse
3 Ktatement weuld be

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

fuu neet ttuatton, skippnq t Sotementi ou Cuu ent


"ituaen hati tu Heoson didnt exe cut when
1qual tot 4)
114
and label
bobel statenent
The gets Blole nent Contaol
t anothu aut
shene poutela label
[Link]
golo stotene nt % ddkco ueonged
tueqsamContao!
ing longg becaue makes

got label ;

label : statemet;

Nheue, qeto keyrod


identr,
115 enday i th a Colon:)
Vsid ain ()

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;

printf("Enter the number of rows: ");

scanf("%d",&rows);

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

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

printf("* ");

printf("\n");

return 0;

117
/* Lab Program 1 : Program to implement a simple calculator using switch
statement */
#include<stdio.h>

int main()

int operand1, operand2;

char coperator;

printf("\nEnter the arithmetic expression\n");

scanf("%d%c%d", &operand1, &coperator, &operand2);

switch(coperator)

case '+': printf("\nResult = %d", operand1 + operand2);

break;

case '-': printf("\nResult = %d", operand1 - operand2);

break;

case '*': printf("\nResult = %d", operand1 * operand2);

break;

case '/': printf("\nResult = %f", (float) operand1 / operand2);

break;

case '%': printf("\nResult = %d", operand1 % operand2);

break;

default : printf("Invalid Arithmetic Expression");

return 0;

118
/* Program to print day of a week using switch statement*/
#include <stdio.h>

int main()

int day;

printf(" Enter any number from 1 to 7\n");

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;

default : printf(" Number out of range");

return 0;

// Program to print whether a given integer is even or odd


#include <stdio.h>

int main()

int num;

printf("enter any number\n");

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;

printf("Enter any two integers\n");

scanf("%d%d",&n1,&n2);

if(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:

for the first 200 units 80 paise per unit:

for the next 100 units 90 paise per unit:

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

and print out the charges.

*/

#include<stdio.h>

#include<conio.h>

void main()

char name[10];

float unit, charge=100;

clrscr();

printf("Enter your name and unit Consumed:\n");

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

/* Program to print numbers from 1 to n (natural numbers) using for loop */


#include<stdio.h>
#include<conio.h>
void main()
{
int num,i;
clrscr();
printf("Enter any value for num\n");
scanf("%d",&num);
for(i=1; i<=num; i++) //for(initialization;condition;updation)
{ //braces are optional for simple statement
printf("%d\n",i);
}
getch();
}

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

Volume o data in tios xtading puouuing and fuling


Jo uous suh amout data , e nezd a foueng

tht nsoutd puthat oint stouing acuing


manifulolon a data tims
Knoun as an Jhat

Can de sed ten uh afaialios

Road Siz `equented colleion the


tlmnt Homiagnous lkinilas data tye tlemut. 3n t t
an aoay an de wed to sehwnt a dit
umbeu, nams.
the
nane

loobs maks t to handle the avayt


ae slome aampus wh the conapt Some
138
atays Can e used i
Month
timpealuwus sutoodad wnyheusn na days
in an ganisalion
3)
) Wtt ooducta and thein ott ud y thin itou
) Jntonal maks o student ite.
ExamPLE:
cn aray name Aalasy ds ud to aehseit a ut
balasis uan

Tt
Jt an be lustotd as below

salay ’nde on subsoit3.

.",hes o, 1,2..... 9 aoe called


subuonit

make t to handle the


NOTe: loohs
139
(omnony
* ONE TMENSIONAL ARRAy (1D):
us a f'xed - siz sauunced colhJion o
tlemuita q homagovous | stilan dataty
tes lan de quen One vasiabe nane
Yauabe
One subsit and such a Yasuall callhd inge
s s called
Vasabe ot 1D'
ExAMPLE :
Numben [s];
Nunbe

(o)
Numbor [o

lumben [2)
Nunben (3)
Nlumben

toage Joalons as dhaun alove


Jhe Aombton 9usowes 5 storage
Jhe values to tie csas dnisto an de autgnud as tollaus.
Ex Numben (o]= 4;
Nunben 3 + ;
Numb [Q 8;

140 Alumbes [4) = 0;


Jhis would cause the avay unben to ito the als
as shoun leleww.

Alurnbu [a &
Neumbu C8)

Delanatien one dimenioyal asayß.


ohu vasiable, asoays mut e deelaned
dike
ay
ae wsed so that Be combin can allocats
spae ton ninn
data tye asoay- vame si ;
type the elemt hat
Jhe data tyte speiu the asays and the st indiiatis
hill de contained n the
the moniun no elerets that can le stohed inside
the
tnt madks 5]:

141 (5)
* Mauks is the aay name wieh can hold a maimum

to the aays otde the declaed


* Not hat any aune
eOA u t wt
Jit uould nst nesonily Cause an may
gie unhnedkctable usutt
the Siz should e ethes a umwic lonstr
*

alunys smboli Constat


52
Ex: (1) # dine tous

int maks [souw}: lvalid


um i not a constart

5TORING VaLUES Iv ARRAYS.

the elemet
Snput
)9 design valu to the elmuiti
Snitialie tte eleunt

data tje oay


142
) Basic aintial:zation
uit mks [6)-1o, 90, 30,95, J54;
mahs loJO3oN5 15

Paotal ilaligalon
int manks (5]- o, o03;
mauks ooo

int manks [ J= fi0, 30, 50, 60, 90


maks io205060

Trttialiplion to all goos


int mahs [ioo0] =fo3;
mauhs

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),:;

tor Cizo; le5; it+)


San ad",&manks );

ARsign Values to the lemt


Jhe thisd way to ahign Vales to ndiutdual elemut
the atigmuit opuatia
Value that wluais to an apxopuiat data tiytoe "that
the Can be to the idiutdual aoat
element. A Stntle avmigrneit statmit Can be wilen as,
mauhs [3] = (00;
Hee, 100 s aulgnud to the touth eemnt theavay
as maks [3)
144
/x Psoqam do
to e-tnitiali'z the durmuint of asaay
Confile ime and to oit the demurita oaay dusing
'on to he.
Souen x .

# incude <stdio.h>
+ nde <conio. h>
void main l )
Ilauate irittalizalin
int i, aw [9) -{5,9,3,2,100,-2,145;

code to auint anay tlmeit */


k
print (" The elemiti q aoay ae :ln";
foa (i-o,ic4;++)

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

San l"d", o);


ie code to sead elernta aray

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>

int a5]-f20, l0, 5, 3, 3, t:i; llcompile tine


coscnc :
pait C"emits along with thiin Ssuanes ae:ln:
toa (i-0; i<5; i++)
Doint) (" d1t %.d \n",aC1J,aCi)*al):

eumet along with thun Squasae


LO0

95
5
3

148
* fogam to ind Sum and mean d all thu eemit stoude
asay
loclu cstdio.h>
#indude< Conio. h >
Void maio( )

an [50J, sum=, mean i

Stan Cd",n):
tor (izI; i<=n;t+)
Stan (" d', amc));

fes (i=l; i<=n;i++)

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

1. Seauential Seanch (Linan Seanch)


2. Binasy Searek.
1. LINEAR SEnRCH
uneas Seanch is a vy inhle and baic Seanl
dlgontthm.
* Bn this techniue, uny dem dsis checkd and il a
matd is teund thun the pasticulan uinder a szted.
othurwise the Seaneh condtnues til the end a! tte data
calhtion Casoay).
* n Case, elbmeit
the
Kuy is pusent in tde t
data ten the Seanc is Suasl, otheuise Seanch is
unsuauakl.
Lintas Seah
’ Sths
STEP 1: Stat
151
STEP 2: Rad n and untiallze 7ag 0
STEP 3: Read asay elmenta n
SreP
ZrEP 4: Read the Key ilem to e Seached
SrEP5: fon i1 tl n

then poit slmnt eund at indei


=1

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

Ihe fint eumnt is 5 t undex 1 and is dombaud


152
tlemeit is t. Bince 5 a nt tqual to t, he Seaneh
Corlins ith e Second sleuit h aay
Again Setond elemeit is 8, ohich Ky
lemet a, as lustth elumust ae not Same tu Seasching
oous oiu wtt the Kuy tlemit s taund.
tinally the tend t position 5, and
as sheun llow

(2) (3) [w) (5)


|5 8 l2

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)

int alo), kuy t ,num,tag -0;

Stany %d, `nu;


poirt ("bnt dnumbes ln", num):
for (i=,ic=mms it+)

oint " btu tte nwnben to Seat ;

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

Binasy Seasdh technigue s a fait Seasdh algorithn


and onhs on the incible e david ard Congs
whis ithni·u dooks ton a oaxtadan damut (kuy lemt)
a

day lompaing the middle mot anot o th coletion.


a mth dws, then the unde d itm is nted
the middle elemeit denent,
kuy
then te
Kuy elemt s Staehad in the Sub-aa to the
dagt o dhe middle element
* otheuie , the Key lemat is Seasched o cin the
Sub-asray to the uight the middle elemet
This sotuus contirus on the Sub-oasay as wel wtil
the Sie a the Sub-avay sudus to gio.
TRACING
aimnplamnt einary Sunh on gollauing it o
clumuta to ind the Ky tlemit.

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)

Key tlemest to de Beachud f


’ 3ntalize Jaus1 and high 5
ho 1<=5 u)

Aompit mid, mid =(lawt igh )/2


mid (1+5) |2
mid 3

’ Comnfave Kuy tlamuit with, middle elait (amt)


Kuy is and amid) is , do Seasch is
sutaun poilion Kuy elmt as 3. Sua7ud,

35+|8 10
O 2) 3) (4) (5)

4ae 2: ky slumet to be Seaschad -3.


Srikalige
uo 1<=5 (tue)
’compute mid , mid -(law t high)2
mid (1t5)|
mid-3

tomfau Kuy Elmeit wth middle tlament latmid))


Kuy is 3 and almidJ t, uso Kyeeit is Smalls
157 Hhan tte midlle elmst
a 35810

Smallu than the midslle element


’Kine Kuy Elmnt to te de<t of the
Stach the kuy tlemot in te sib- say
midslle slmt Cutdit hi_h - mid-1).
nleus louw =1 and Jigh - mid-1,high 2
ohile (lowc= heh) So 1<=2 (tue)
Computa mid ,mid =(louo+ high)h
’ mid -(1 +a)/2
mid =1

35+ 8 10

Cose 3: Ky Elemet to e Searched 10


Snitalize oo-1 and high-5

’ Combit mid,mid - louo+ high)2


mid - (1+5)b
mid = 3.

’ comfane Ky Elmut with middle tlemut (almid)


Kuy
y thon thu nddl murt
y
’ sine Ky Elenet
158 greata than the middlle tlemest
fah te Kuy gluut n tu
eanh the Sub-auas to the stight
the midde tlemt (ubdati low Mid +1).
Now los id t1, los- 4 and high 5
ohile (lew c= high ) So 4c=5 the)
compiti mid , mid -(lao +high)l2
mid -[4+5)2

159
Psa tanm to imjlemt hiany Ftanch on diut
tlemeta x).
tncude <Stio. h>
nude < Corio.h>
int main ()

int aio), Jou, high,md,I,n ,ky, ag-0, as


clnst);
San (%d", &n);
to */.
lx Code to Dnsvt slumet
In);
for (i=l; ic=n; i++)
Stan "%d, fali);
Elenut to le Seachud )
print " ent the ky Elemut to be Seanchd \n;

Code to Seasch the Kuy Bamuit (linuan Seasch) )


A
louw - 1 ; |nitialie louo1

high =n i Il3nhialize high n.


hese
thile (lauoc -high)
160 mid-(law t huth)l2; ll ompzb mid
middle tlril x/
pos =mid:
1; Ix tag- 1 irdiau suauht Stasch,
Kuy leuit geund'a)
Break ;

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 *}

I| check or lage value


Search

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

bu glvn an input to many othuu hurncttons .


Junclton Juminology: uncton Terminoloqy
Jhe functon j) that wsu ano then unctian gl) is lanown
calling unution and dunction q) is
is called Called
Call sunetion.
lw known as
Jhe nputa that the hunction take aue
163 augumnt/ Pauancus.
hen a calle d Sunctlon etuunA Aome aeault bak to. lhe Calliag
Yunction t ia daid to aetuun thal wesult.
In oudeu tomake ue of a useu- dehined junctton , we nud to
tAta bliah thue demunts that aue uclated to huntion.
hunton ;-Elemnty o uen degine d jun tion
Elemanta o) dehinud
Funetion Dechmation /Function psuatatype: Func fion declauation
iA a dtatmtnt that tduntijies a functton ulith ita name, aliat
o} auqumnt that if auupta and fhe typ of data i aituuny
C puoguam sit should bedclaucd busoue they
Cuuy unction in
aue uad in a b0quam.
C

functon deelauation ea done by a function puototyp Natement


Syntax
etuun- type unction- name (toumal pauamta liat )
’h funetion dclauaton,oumal paametui opttonal'
-A humiolon ta must af the end of funtion dlauation.
int add int numl, int num)
164
Q. unclion call / Calling unctton A un| ton iA caled by
Apiyiny
in
ilh nomt jolourd bya tat oh augumnnlu tncloard
pauanthtAi4 and Atypeualtd by a comma.
Jhe hunetion call statiment fnvolvea the function. ulhen a
Buncton ia inuolved , the Compileu jump tó the called hunction
to tvecute the Atatementy that aue paut op aa called funt hion.
A7tu the callud KuncHion iA exeuted, th puoquam comtuol
Pasu bauk to the calling unctton.
Syntar : unction - name Vauiable l, lauiable a);

add (ni, n) cOR)


Actual pauametu Cn1,n)

Note Jhe pauamtus uad in unetton deelauation (functton


one Calld
Pauamtuu) anc called Houmal pauamutuu and the pauamitus
Hhat uAd in junctton Call aue called actual paameteus.
3. Junedan dejoition Called junctton i-A funchion dej tnition
Contains the code þou puoguamminq to pujom a spuihic tak
A6unction in dejind outaide the main hunction4, tt
eitheu befove ou aj toa main Sunetion.
Can be
d-gnd
Afunetion deginition Compuins oj two pauts:
Juntion headey
165
Q. Junction body.
Oyntar :
aetuun- type hunction- name (foumal pauameteu liat)i
function heada
local declauatton
S tatemun Junctton body.
e4etuunj
Junton adeu;It is hame as that of sun ction puoto type.
but a guncton hount nof end with a hemicolon. .

Junetion body -Thta consiats of local deelauation, Othen


Btatement and 4e tuun statuments.
A sunction body Conaia ts of Atafumunta that dos aspuif
tank

Jhe qautaun statement is the loqleal end of afunctfon. fhe


last statemunt to be exeCu ted in 7unction.,
int add(int numl, int
num)’funetton htadin
înt bum
Jum = um num 22
4utuun (Sum); |aetuun (aumi+num);
3
NoTE: Vhe Btatumunt hctuun (sum): Can ala ob
166
as 4tuun sum wuitn
APuoguam to add anumbes Uaing Junetlona +/
tinlude< std to.h>
t include<conio.h>

int add ( int numl, tnt num). # func lion dclanalion t/


int mainC)

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 )

4etuun (num * 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

Puint{ l" XValue is 7. d, x):


aetuun lo);
170
Void gun (int num)

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

Jhe puappinq is not done becaunt the pass by value teehnique


puotuts th daBas any change in foumal pauemutuu Cn, n2)
with not lead any chang in áctual pauametun la, b)
60, as* and b: 32, famu aftu hdappin

a call by Reaunce (on) Pou by aujuana;


n call by aujenea, the calling funuhiona tuanahu
adduess of autual paamefus to the houmal pauamtu in
the Called hunction.
.Th Joumal panametus Contarn the adt ueu oj actual paMamut
Thuue foue any ehange inthe þoun
þoumal pauamtu I4 actually a
in actual pauameteu in
172chang' calling huntion
pauametuy. actual 173
chang atualya pauamufu
is foamal change
in Bcaue
|lool num
put Out12
aetuun;
num t num
num) (nt¥ main Uoid
}
coj4utuun
)
); , d ia
value ("x Puint
þunlGx);
S; inxt
C)main int
num] in4t funl Woid
conio.h Tindude<
tinude<stdio.h>
ueftuance
/ by
call / ¬xompl;
Aþuntion, dup1nding on uhethen angumeni. foto
ot and uwhuthea a Ualue is 4etuuned 0u not, may bulong
One of the foloaing Cakugoulta -
i.. Functon ul:th no auqumen fs and no aetuun "ypu.
. funchton uith auqumsts and no aeluun ahues
3. function wtth augumuntA Cnd ot th qyetuun Valus
A. funetion with no Ququment, but with aetuun Vauy.

unetiar uleth no amqumenfa and no Mehen ypy i


lhis typ oß hunction ill not have any pauamteu and
thuy wi not aetuun wahe to calling sunefion.
The i no data tuani fu bulwun Caling unctton and
Ualue
Called functon, 6o calling huncton Cannot hund any
and hene caled Sunctlon do not eceive any d ata.

3Puoguam to multiply &numbeus /


tt inelude <Stdio.h
ttinclude <Conio. h >
Uotd multiply C) Z funetton dulauatton
Woid main C)

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.

a Junt'on otfh, anquoment and no yun vabus5


in this case, thuue ts a data Iuanshuu om caling unction
to called junction but thue ia no data tuana fuu huom
Calld yunc tlon to calling bonctien:
Jhe caled funchon wtll have pauameteua but no actuun

Hinclude < st dio. h>


t include<Conio.h >
175
Void multiply CIntni, intn);
(oid main c)

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

8. Functon wtth auqumants and uwith yolun typ :


Thue ta a data fuanifu huom calling uncton to called
cton and vie Ueua.
176
alhn pauameleu! aue paáted the called untton
aeiye valued fuom calling Suntton, llhin the functton
attuuni a value the Calling hunution Can 4eccive a
Value om the calle d$unetto n.

/* Progaam to multiply a rumbas#|


#inchude < Atdlo. h>
include<conio.h >
Int multply Cint nl, înt n);
Loid main C)

int nl, n2;


cluseuc);
puintf (" Entu any too numbeusln);
Scun C" dyd n4n)
9utehc;
int mutipy (in tnl, intn)

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

178 Puult is &u.


Becuusion
Kecuusion fa a aupititve Duoesa in uhich a juntton Cali ttt
Aauuuaive Sunction ta dujind a a huncton tha calls itaet
to 6olve a smalleu veusion od ita task until a inal Call iú
made which dos not hequie a call to ifaj.
Exomple: Factoutal a numbeh.
fact n) .
n jaut Cn-1)
factoual of 3 can bu found aecustvuly au folloud, .
fact C3) 3 * fact (a)
fact Ca)
(o) - J+

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.

elmy Reuuhive Juneton must have a buc Case


Note that
179
Dfnd jactoulad of a numbu

/xPuoguam to þind faclaid oj a numbey using Re unilon


tinlude <stdio. h>
#tnude< Conio. hy
int hact (int num);
int main C)

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

ji'b(n): fib(n-)* yibln-2)


ineo? Bae cale
ib (n-) t $ib(n-2) ngentual Cue

s Paçguam fo ditplay Flbonact Suis uaing Recuesion¥


tinlude <stdio.h >
nclude< contoh>
int sibL int num)
Vbid matn
in t n, i: 0;
Amaincs bugin, hene
cluscuc);
Puintf (" Cntu the ualuu bou n\n);
Scan (1d', 4n);
oH (Celj C<ny Ct)

painlf ("7. d\t ttb li)); / Functton call

Qetchl):

int hibin t num)

iß(num e z 0!!| num !)


4cfuun numj
ele
4ctuun ( sb ( num-) pib (num-2));
181
Out puti
Cntu the Value Don n
5

Ftbonati Stutu id

Auuays and Junctiona:


demonstuat pasing of fndiyidual elemsts of
Piagpamg to
an amay fo
to afunctien #/
#inude Kstdro.h
void display Ctntn); /lawiabk nof auuay.
Woid main C)

int a[s] s,o, I 2, 3}j


cluscu c;
tou Cie0; i<s, itt) /Fou lop n main untion,
diuplay(a() / Funcilon call
gutch ();
Uoid desplay Cintm)
punf Cd\t", m);

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)

tnt a [s) - fS,o, l, 2; 3


-

display (a): /uctional call.

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

puint (" EnCn hunctton I, Coun -d \n', count).

lord hun 2 )

2int ( in functon d, tount - d \n', count):


ìnt main C)

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 }

lcode to dumonsfaate stattc vautablu.


ttineudeK Atdro.h
#incudecconto. ho
Lord fun C)
H localauiable
Static tnt n : /statie Vaniable

ntt)

Quetuun

3
Vord Mamn C)
tun C))
tunC),
fun C) j
186
Qutput

Atouage unra inaide the míuo pus euoM, AJ


due paut of mitnopuo wMou, bo the data sfoesd
tn these aequteeu can be cacceked Vey sut.
Rqisteu Vauiablu aue declaucd by wing fhe key woud
Example Qegata in tn'y
:

The above dclauation inh luuets the compilen that


Vauiable m is to be Bfoued in one fhe augin teuy but not in
maln memow

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 ',

~ ~ ~ t- t1 ==- ~" H ~ '' 9 If~


' ~
·•
~~ - ~l
J.. , ~h ,_ il, c ,;A i,;
'~ .,. - ---o,J ,', ,~ ~ .,t&- ~- . 0 . . ~ . _
l) Q, ~ O,J:, ~
~ ~ {G ]; ..
~ ~ ~ ~etto" ; J l /\A l~- ~~
~~~
~ ~~ N,

~ ~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 '

· ~ ~ voJw, ~ .,a- ,\/Y\ct:~ ~ ~ ~


:::o- o
,ot?wl' 9
~11-- Ab
0

/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

L . ____ ---"' ~ ---- ~ ---


~-
0

193
~~
.0 /~ 11 \M ~~ V 'I \.

\. i i t ~ ~ < ~ l ~ " ° .\.\;,


.l ,o G4-W\,~ ot,°"v,J,c ~ l)
( ') rCWL
\} ) .AM ~ <.. [Link]\M? \ v,>

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)

~ tl " ~ q I 2, ~ , ;J.._ WU , he< ,vvU , '\_v-,' )',

~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 )~

~ ( i =- 0 '1 $.,(,c.i rn !z '/ o' ; {-t -t)


1
~ 2 (-t] = ~1 fi] ')

S--¾~ I ·t] = '\o ) 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);

pAvvv~ (~W,, ;: ~ I : '');


~ - (~.i )j

~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:

datalyp *ponlova a tvar ;


dataly
pon Va var;
EXAMPLE :
to cmonabati foit lorat4 iilaliyot
delaat4
#incude<sloio.h) Vaiable Vaue addss
#incwde<cnio b TRACE: i o 2004
vod mainC)
pi 20o

|iny ("d", t); lo


20 O
iny ("/ d" *pto)
geteh;

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

unt v =5o, *pGi ;

pouny (" Jhe orlent in var is = }d\n" van) ;


pung(" dhe conlent in van
punn is fd \n *pn);

pun(he a d c s o von,is d\n", 4van);

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.

A pon vaiable has


has its o n odde 20 41 but
203
poitU aneAays [5.4)
Cosidy wo:int au[4]
Lhe aove cocle can be Lcterucolly spwsnto
1004 l008 I02 1016
20 30 40 50
[2]
Jhe nane he a a y octualy
ponlo upnting the odds o memey lacation o
turst lement o an - v
Hue thu name
me o the a holo the addes
st lemnt aLo]. ,e a = &aTo] =o00. Hece,
fao] is eqivalent to a
Value in oddsess Lo] s OUo] and vaue
* a . Hence, avUi[o] s e q i valent
to a.

v lemunt sng
paint netaion is as toleus
* (aayame+ poaiton)

notatiens : ati ita


You can delae an pointin
hu dala
Example i #incude.<ldio. b)
main C
unt a 5,i ;
Rouny(" Enl
te i0,<5;tti)
demets");
scany ("d"; o t i )
pon (" Yeu entuud ")i
to(ieo j i<5 ;++i)
204
pount(f.d", * (an +i)) ;
[5. l0)
while paming amtor snq hy addus
he oetal d m o the
Vawaltes to Uhe
caled tunehon
n he caLled tunclon Aehe 4omal paraisasahold
tee tnclon
the

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

int mun2= 5, uem2 O;


Surap ( 4rum 1,4m2);
finy (" Numbn 1 > hd"um 1);

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.

Actual argments iu At eolion to actual

umain saye, Ihy cont be angmento is fersi ble


mocitied cciclentay aithin tom called tunel,
the code mst handle
angumnts
4ou g
catuy
ne
cls
pecteed

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

Peuntos hulp s to buld complex olata


b e e s ike nk iat, stack , quees gbes

Paints alew s to si the dynamieoly


aecad memey ock.
Adds oajct car
|5. 13|

Uniliaiged einlns igh stgmentalion


tat.
-alacatd block neds to b
ynanicay
e plieitly. ethwise, t woud
ad to memory
than n e a l
ak. PoinGs a u slowe
Vasuates

with ceuct
Values, t might ead to memey
dad
207
coupiori
Different types of pointers in C:

There are majorly four types of pointers, they are:


• Null Pointer
• Void Pointer
• Wild Pointer
• Dangling Pointer
1. Null pointer:
The Null Pointers are those pointers that do not point to any memory location. They can be created by
assigning a NULL value to the pointer. A pointer of any type can be assigned the NULL value.
Syntax:

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

char string1[10]= "computer"; // string1 is initialized- basic initialization

char string2[10]; // string2 is not initialized

int len;

printf("***** performing string copy******\n");

strcpy(string2,string1); // strcpy() function copies string1 to string2

printf(" After strcpy()");

printf(" string1 is %s\t string2 is %s \n", string1,string2); // both sting1 and string2 are same

printf("***** performing string length******\n");

len = strlen(string1); // strlen() computes length of string1 which returns 8

printf(" After strlen()");

printf("the string length of %s is %d\n\n",string1, len);

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

char string3[10]; // for string compare

int result;

printf("enter string 1\n");

scanf("%s", string1);

printf("enter string 2\n");

scanf("%s", string2);

printf(" Before String concatination\n");

printf(" string1 is %s\t string2 is %s\n", string1,string2);

strcat(string1,string2); // strcat() function concatenates string2 to string1

printf("After String concatination\n");

printf(" string1 is %s\t string2 is %s\n", string1,string2);

printf(" *********String Comparison strcmp()********\n");

printf("enter any string to compare with string2\n");

211
scanf("%s", string3);

printf(" After strcmp()\n");

result = strcmp(string2, string3);

if( result == 0 ) // strcmp() returns 0 if both strings are same

printf("String 2 and string 3 is same");

else if(result > 0) // strcmp() returns value greater than 0 if string2 > string3

printf("String 2 is greater than string 3 ");

else // strcmp() returns value smaller than 0 if string2 < string3

printf("String 2 is smaller than string 3 ");

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);

/* code to find the length of string*/

while(str[i]!= '\0')

i++;

printf("\n Input String is %s\n",str);

printf("Length of Input String =%d\n",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);

// code to compare two strings

while(str1[i] != '\0' && str1[i] == str2[i])

i++;

if(str1[i] == str2[i])

printf("Entered strings are equal");

else if(str1[i] > str2[i])

printf("string1 is greater than string 2");

else

printf("string1 is smaller than string 2");

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);

// code to concatenate two strings

for(j=0;s2[j]!='\0';i++,j++)

s1[i]=s2[j];

s1[i]='\0';

printf("Concatenated string is %s",s1);

return(0);

215
// C program to copy one String to another Without Using strcpy()

#include <stdio.h>

int main()

char s1[100], s2[100], i;

printf("Enter string s1: ");

scanf("%s",s1);

// code to copy one string to another

for(i = 0; s1[i] != '\0'; ++i)

s2[i] = s1[i];

s2[i] = '\0';

printf("String s1: %s\n", s1);

printf("String s2: %s", s2);

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-, ·

~-r ~ ~ , OU ~ -to ~~~ ~ o n ~_ , _ . . -+ ...0. ~


~ -l , e ..h.u r'\.O..rn e , us n , te-v., -p..a.i..d , ~ J.L: t6"' .:tJu.6 -a

-[Link]:t vi ~ "tu J b..,_ -c:e..Lt..r..[Link] "1 ~ ~n

~~ ...o, ~ n.o..rne -0/l --a,U .:th,l/2 ~ "'-4


~ :to ~ ~ •
=
I

. '. "1h..w ~ ...u.✓.i .::{_o ~ ~

~ ~ ;

l;
220
I
I

~ vi/2 ~ e'1.0.Y'Y1e . 't



NOTE
• I

.~ ~ - l-~ --- ---


' I
0 01 fl c:::,4=1,
_____

_,, ~ h li Jsi •



[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_ ;

1 o2. · TY PE: DE J: IN ED ST RU c TUR E : (__ i:-'::l r'Ji )

~ • A ru,-0 u.,, ~ 1 ~ -o- ~ v~

~ ½ ½-e_d1 4 ~ ..tA .a. ~ -

-Lr\t ~ o ;
~ ~;
~ r'Y),a.n,R/4 ;

l STD;
~TD '6Xd i , ~ ·,
~

~• JJu _ VCl.>U..a..bl.(_ ~ ...a.r\d 4Xd2. ..o.,, e.. V~ 1~


STD .
222
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

~ ~ ~ V O J L "' l lik t °t vcuu.a..b-t.w} ; •


' (

4~~:
. ~ ~

t
~ IL.() ..yy) e. [ '0J ;
--l/\.1" ~ () )-

~ ~uu ~ J l cLl. =- ~ tt.-0. .IY\.. .Cl..) , 'I, 0 5 , 4- 5 0 0 0' :> 0 1

223
~~ ~ ,__ --- 4 c~~-~
~~
~ t~ ~ ~e ~ G~
~
J:'~ ~ e Xo 6.
~ -t., -f:>-..c\.½ ~ .:to ~ --a.n. .oL

"1h..vt e. e. ~ ' - ' 1 . <:.n.:t- Uv~ .:to 1" ~ ~


~ ~
~trr, . --0.>1

~~ e'J l"Yl...L rn..1:,-. ,.Yl/S 1 ..,a__ ~ .....a./2

U-to ca. ~ ~ ...Q/2 ~ .

~ 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_

~ 02. . PAgglNG THE ENTIRE STRUCTURE

~ 03.
\J' PAf glN G THE ADDREg~ OP STRUCTURE
~

.) 4 PAS~lNG IND I\/ID UA L MEMBERS' o~ A


~
J)
3TR\J CTLJ RE. .

~ • "1h..w ~ e ..U. ~ -to ~ o..."-'-d


~~ ~ \I~ --1_: e ~ ~~
.i_n

~ 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

( • ~ M '/-d. \.:t- .V.. f·d\ri •: .,l~,

~);

~ ~ 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)

~ ~ ( ,, k _ -/-d \ ;t- ~ -W ·/ ·& \ n ., • s . ...I ' .s. b) j

·- - ~ :

~ ~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:

~ ...iA LO ~.l/2 .20

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_

' ..u.,e_ J I <)-<. --0.. . : : / : - ~ ;b,

~ _,th t ~ 1 ~ ~ V .

~ E~ e : 1n ~~ ...o-. ~ YY)[Link]... 0--W-ru.ru_d ½ --0. .

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

i ~ ...a.n..-d.. ~ ~ ..a...U. .:the ~ ..o/2

'. ~ ~ \ ; ~ . .

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"

t1 [ gTRUCTURE WITHIN gTRUcTURE] [s. ,]


~ ~ ~c' -O- ~~ -eo.n ..k ~
r ~ ~ ~ , -Vu/2 --W ~ -..Q./2

µ ~ 1 ~ ..£. e --a. ~ -0 -O..

I,) ~ "1 ~~ ~ .
y

.> ~ --O..>t.e. ~ Io -d..t..cl...a.. e


-=tu.,
0 -a. ~
J ~ ~ ~ ~ ...a..,-u __ --0--i ~ :

w)

~ ,,,,....

:, 0 2.. . :Lu., 0 ~ ~ -~~ -~"-"V

229
JNIN
Unieni
Sinilag to stauny olletion
Vaiates

Lnien Can stose


tme
nfmatron in ene

at an Bne

3his me
means the LJnion rnenbeis, all eha
he Same memat
membey eah as t loctfon.
enions

iavolre multel enby she alues ne


all nenbes at
t be Hme.
he
asyed

Note: The sge


Equt to the
menL
lasget

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

he declanton el union Vaaiabeg.


Sinp
sg- the non Ls the sige l
) Jhelagest to e' sticiet
numb

unien can be ela


Vancalte a
ehasn belos
Lnion Stue
unin studet
t oll-o,
chh iSAeJ;
char sN[e-, chan Namalisl;
cha lameLi3

Lnien studet etuQ

Vanlae unin sthat


ohene &tud
231
Acceshg the memb LSnien

Siila t 8tou du , th menb


uniion Con be aceu
That acces h
ue the ot ) opota,
Lnin Vaiae naoe menbenarne

ohae Jet qnato

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

PoiNT PI= C2,3)',


1lgal ith onion;
PoINT
P2.

233
too1dinat q P
7.d, p. x,Pl))
ond
coeadinátis 2P2 ae V.d

7d", P2. X P240;

The coeadinats Pl e 2 and 3


5 and 5
the co0ndlinty P2

code,PoTNT| aa uitin and


sn thke abore
the declaation
ale
a union. Both
Meyweds, Notiee the
almost Sane eycept thL
cannof be

main() untion. he fields g


atpit
inttiali2ed Once. Conuds the output. he
but fo he union
anse dotsnot Ceem to be cOMLt
vaiablo the
Unuon
Lindtnd the concept
l6
ode

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

beLaese vuattng the


not diipay
qiulds -the progiams ay
aceurttt ncells

Unon PoTNT

tikt X

nt
PoTNT points C3;
poirtC. : 2;

236 poists []. X - 2)


qeqoad JOId
pointa[23.y- 33
or(=0 i 3 3 i++)
" In the tocadi natis q point (d) au
point
7d and d" i poirits CiJ. ×, poiny);

Output
Coondinats point[)
Lo a 33 and 3.

Coondinatis q pointCoJ are 5 and 5


Coordinatts
237
Difference between Structures and Unions:

Sl. Structure Union


No.
1. The keyword struct is used to define The keyword union is used to define a
a structure union.
2. When a variable is associated with When a variable is associated with a
a structure, the compiler allocates the union, the compiler allocates the
memory for each member. The size memory by considering the size of the
of structures greater than or equal to the largest memory. So, size of union is
sum of sizes of its members. The smaller equal to the size of largest member.
members may end with unused slack
bytes.
3. Each member within a structure is Memory allocated is shared
assigned unique storage area of location. by individual members of union.
4. Altering the value of a member will not Altering the value of any of the member
affect other members of the structure. will alter other member values.
5. Individual member can be accessed at a Only one member can be accessed at a
time time.
6. Several members of a structure can Only the first member of a union can be
initialize at once. initialized.

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

) Lend and dirlay laug aMount datoa


have Cuealeol nd save a tu data Valuee
'feunaneotly stued on tu dc
Oe

an foss Sne Vaue


Many
aput ts
We Cah bas bane volue
v) ale us as te
Can be e
aput anothes
tat hat
Neceuaynake buwe tuouequatue m many difaent stot g data Valuee
wouke n all cales

Dak
Cbuoguam
File 'pohta has data tipe :
Ele (yeam,foiatu t
Fele i deficd fle).
lettae

) dec lelalon

a) input/output opualion on fle


) osing le.
) Dealoy atan/aeathg fl fabnta
fle honleu;

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

wing nst tt,


rnane

open chq fele done by wáng tepen funfen
Joum
name, Mode);

3Medes

topea tale to augunaentt;


(9) FEle name Both 9 wich
(a) yo de e

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)

topen [ le a. dat", w") 66

= fepen (" E:le 3- dat", a');

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):

ile hos been sed, it nust be elused.


TKe dene 'by close unclon

Ex:tclae (fP1);
tclose (+P-):
felosc (+P3)

NeTE: C docs fas auto nateally on


shen puoquan teanairata but
ale
good
Input

Bcan: unelion 4eads std in


(eyboaud)
eaa' funan cods feom eahu keyb and
243 a (ile
Vauiable):
foumat satnq
Sounce 4fle: It 2 6Bdin
been opened
was
aluuody
|(a) Reading fom tdh: TH koybsand
Ex : |focan (&tdin, 66

Tn Case fuat fauaneta Std in (o

fnum);
abar leads and soue num
enomple
(B)
Recietnq Cos e

Ex;
inile

ingle fopn ("Ltau . dat, "u):


Tt Heads data (lettu . dat ad Sloes nun'

NoTe : vtwene Eof t allempt t Hend end-4


9then wise Hctwan tu' end--fle

: bend. 8ntputnt bnly


enly tts stdout (Montlau)
244 bunds sutput to
(6ucen, pintu, fles on the dak)

Geeal founm;
fp (detglil, "" fum at diy
slking" )

it Vauiable):

ta skdout (monitau )Gile poinu hoich hs


alurady ken, opened
to) Sending Qutput to a standaud Qatt (upnitia):
t Case fiut pauameta tdout:
Ex: fpat| (stdout, " %a\n Num);
In ta

puint| (" %dln, nu):


(B bendinq Dutput to a fple:

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);

dees not exit);


extt (1);

tsany lfP, %4" -no);


66

felose (ff); jels etff) ;


qetch ();

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

/*2. Write a program using structures to read and display the


information about a student */
#include<stdio.h>
#include<conio.h>
int main()
{
struct student
{
int roll_no;
char name[80];
float fees;

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;
}

/*3. Write a program to read and display information of a student,


using a structure within a structure */
#include<stdio.h>
#include<conio.h>
int main()
{
struct DOB
{
int day;
int month;
int year;

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

void display(int a, int b)


{
printf("x=%d\n",a);
printf("y=%d\n",b);
}

// 5. Program to pass structure variable (entire structure) to a function


#include<stdio.h>
#include<conio.h>
void display(struct point P);
struct point
{
int x;
int y;

250
};

void main()
{
struct point P={2,3};
clrscr();
display(P); // function call
getch();
}

void display(struct point P)


{
printf("x=%d\n",P.x);
printf("y=%d\n",P.y);
}

/*6. Program to Pass address of a structure to function */


#include<stdio.h>
#include<conio.h>
void display(struct point *P);
struct point
{
int x;
int y;
};

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

/* Lab Program 10: Implement structures to read, write and compute


average- marks and the students scoring above and below the average
marks for a class of N students */

#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);

// Open one file for reading


fp1 = fopen(filename, "r");
if (fp1 == NULL)
{
printf("Cannot open file %s ", filename);
exit(0);
}
printf("Enter the filename to open for writing ");
scanf("%s", filename);

// Open another file for writing

255
fp2 = fopen(filename, "w");
if (fp2 == NULL)
{
printf("Cannot open file %s ", filename);
exit(0);
}

// Read contents from file


c = fgetc(fp1);
while (c != EOF)
{
fputc(c, fp2);
c = fgetc(fp1);
}
printf("Contents copied to %s", filename);
fclose(fp1);
fclose(fp2);
getch();
}

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};

// Program to demonstrate enumerated type


#include <stdio.h>
enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main()
{
enum weekdays w; // variable declaration of weekdays type
w=Monday; // assigning value of Monday to w.
printf("The value of w is %d",w);
return 0;
}

Output:
The value of w is 2

257

You might also like