Introduction To Computers: Unit 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 401

F -X C h a n ge F -X C h a n ge

PD PD

!
W

W
O

O
N

N
y
i

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr e tr re
ar
.

.
ac ac
k e r- s o ft w k e r- s o ft w a

Introduction to Computers …1 2 … A Complete Refresh Manual of C Programming


Software
Unit 1 A set of instructions given to the computer in machine code
Introduction to Computers Ans: Hardware
All the physical component of computer which we can touch
and feel are called hardware A physical component may be electronic,
electrical, mechanical or optical used to perform various functions in
1.1 Historical Development and Generation of Computers the computer. Same hardware devices are used for different types of
operation, so we can say that hardware is multipurpose. Examples:-
1. What is a computer? What are the advantages and disadvantages of Keyboard, Mouse, CPU, RAM etc.
computer?
Ans: The word “Computer” is derived from the Latin word “Computare”
which means to calculate. Hence, Computer is normally considered as
a calculating device, which performs the entire task at very fast rate.
A computer is an electronic machine that accepts data and
instruction, stores it until the data is needed, processes large amount of
data according to the instructions provided by the user, and finally
returns the results to the user.
Advantages of Computer
a. Computer is a very fast machine.
b. Computers operate with almost 100% accurate.
c. Computer is capable of doing required task again and again
without any difficulty.
d. Computers have capability of storing huge amount of data.
e. Computers can perform variety of jobs.
Disadvantages of Computer
a. Computer is an automatic device, even it requires operator to
operate the computer.
b. Computer is very expensive in comparison to other electronic
devices, so every people can not afford it.
c. Computer can not think itself to give decisions.
d. Computer requires technical person for maintenance if it does not
work properly.
2. What do you know about hardware, software and firmware?
Explain.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
that tells the computer what to do and how to perform the given task scales are devised in such a manner that is suitable alignment of one
of the user is known as computer software. The main objective of scale against the other .Multiplication and division etc may be formed
software is to enhance the performance capability of hardware. by using Slide Rule.
Generally software is deigned to perform only one task or a few
similar task. Example:-Windows XP, MS Word, MS Excel etc.
Firmware
The program stored in ROM is called firmware and hardware is
used to write a program in the ROM. Many computer manufacturer
company make essential software, required to start up of the computer
and available in read only memory chips.
3. Discuss briefly about the history of computing and computers.
[Pokahara University 2008]
Ans: The development of personal computer has taken a long period of time
to extend the use of computer at present days. There were not the
advanced technologies in the ancient days. So, it passed through a
several phases to become this phase at present days. The development
of computer from ancient days to present days is as follows:
A. Calculating Devices
a. Abacus
Abacus is a counting machine, which consists of beads divided
into two parts, which are movable on the rods or wires of two parts.
The upper part is called heaven and each bead has a value equal to 5.
The lower part is called earth and each bead has a value equal to 1.
While calculating, the beads are brought near to the mid-bar. Its exact
origin is unknown. It may have originated in china, Egypt or Greece.
The abacus is still used in some parts of the world today.
b. Napier’s Bone
In 1614, a Scottish mathematician John Napier first published
the table of logarithms, i.e. the tabular arrangement of number in such
a way that we could do multiplication and other calculations.
In 1617, Napier also developed a set of numbered rods for
multiplication, division and extraction of roots. These rods were made
up of strips of bones on which numbers were carved and painted,
which is often called Napier bones.
c. Slide Rule
William oughtred, an English mathematician invented slide
rule in 1620 and was based on the principle of logarithms. It consists
of two movable marked scales, one of which slides over the other. The
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …3 4 … A Complete Refresh Manual of C Programming


analytical engine and modern day computer are similar in their
B. Mechanical Calculating Device
a. Pascaline Machine structure.
In 1642, a French mathematician Blaise Pascal invented the e. Lady Augusta Ada Lovelace
first real calculating machine that could add and subtract numbers After the death of Babbage, an English mathematician, Ada
quickly, was named as Pascal’s adding machine. It consists of Lovelace, a long-time supporter of Babbage was successful in
numbered toothed wheels, each wheel having numbers from 0 to 9. A discovering some of the key elements of programming and program
complete turning of first wheel causes the 2nd wheel to move the next design. She found that the same set of punched cards could be reused
number. The disadvantage of this machine was that it could not carry
out multiplication and divisions.
b. Leibnitz’s Calculator
In 1671, a German mathematician Gottfried Leibnitz, improved
an adding machine and constructed a new machine, called Stepped
Reckoner, which was able to perform multiplication and division as
well. This machine performed multiplication through repeated
addition of numbers.
c. Jacquard’s Loom
At the beginning of the 19th century, i.e. in 1801, Joseph Marie
Jacquard of France invented a punched card as an accessory (helper)
to the loom. Punched cards controlled its operations. Needles could
pull threads through cards where there were holes. Thus, Jacquard
could control the weaving loom through the set of holes in a card,
which could store the instruction for the loom.
d. Babbage’s Difference and Analytical Engine
In 1822, a professor of mathematics, Charles Babbage
developed a machine called “Difference Engine” in Cambridge
university. It was made to calculate various mathematical function and
logarithmic tables. Difference machine was intended to be steam
powered, fully automatic, even to the printing of the resulting tables
and commanded by a fixed instruction program.
While working on the difference table, in 1833, he developed
the new idea to build an “ Analytical engine “ which was to become a
real ancestor of the modern day computer. That’s why he is famous as
a “father of computer”. The analytical machine would operate on
words of 50 digits and was able to store 1000 such numbers. The
instructions for the machine were to be stored on punched cards like
on Jacquard Loom. He wanted to input data with the help of punched
card and output (result) to be printed on copper plates. Babbage’s
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Hungarian mathematician, John Von Neumann gave two ideas:
to repeat certain instructions. So, she got the idea of loop in the
program. To honor her contribution, the programming language used • Binary number system (instead of decimal number system)
in American defense was named as ‘ADA’. can be used in building computers.
f. Hollerith’s Tabulator • Computer instruction as well as the data being manipulated
In 1887, an American statistician, Herman Hollerith could be stored internally in the machine (Store Program
constructed a tabulating machine to compute the statistics of 1890 US Concept)
census. He used the punched cards to store data, with the holes
representing data values. This machine can read 200 punched cards
per minute. In 1896, he established the Tabulating Machine Company
to make and sell his invention. Later in 1923, this firm merged with
other companies to form the IBM Corporation, which is the most
popular and biggest company in computer manufacturing.
C. Electromechanical Computers
a. Mark–I
In 1937, Harvard professor, Howard H. Aiken, constructed an
electromechanical computer named mark-I, which was the first
machine that could perform according to pre-programmed instruction
automatically.
It was 51 ft. long, 8 ft. height and 3ft. wide using 18,000
vacuum tube with 7 lakhs 50 thousands parts and weighed approx. 32
tons. Being a huge machine, it takes more time in calculation.
b. Atanasoff Berry Computer (ABC)
In 1938, John Atanasoff and his student Clifford Berry
designed Atanasoff Berry Computer (ABC) for solving systems of
simultaneous equation. It had a memory consisting 45 vacuum tubes.
D. Electronic Computers
a. Electronic Numerical Integrator and Calculator (ENIAC)
In 1946, John Presper Eckert and John W. Mauchly developed
ENIAC. It was the first electronic computers.This machine was built
to meet the needs of US armed forces to use in world war II. It was
300 times faster than any other device of these days. It was huge in
size with 18,000 vacuum tubes, produced more heat as it consumed
180 kilowatts of power and needed to be cooling system.
b. Electronic Discrete Variable Automatic Computer
(EDVAC)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …5 6 … A Complete Refresh Manual of C Programming


(c) They had limited programming capability.
In 1947, John Von Neumann proposed his store program
concept for EDVAC. In 1952, Neumann and ballistics research (d) The system cost and working cost were
laboratory of US army completed EDVAC, which was based on store very high. (e) They were restricted to
program concept. This machine would read instructions from commercial applications.
computer storage for switching a new program. B. Second Generation Computer (1955-1965):
c. Electronic Delay Storage Automatic Computer (EDSAC) Transistor
In 1949, Maurice V. Wilkes at Cambridge University built a The main features of Second Generation Computers are:
computer named EDSAC, which was based on assembly language a. There was an overall, reduction in system and
operating costs.
(symbolic form language). It also used store program concept of John
Von Neumann.
d. Universal Automatic Computer (UNIVAC)
In 1951, J. P. Eckert and J. W. Mauchly built UNIVAC for the
census bureau. It was the first computer designed for commercial use.
It used magnetic tape for entering information and permanent storage
of data.
4. What do you understand by computer generation?List salient
feature of each generation [T.U. 2058 Poush]
OR,
Describe major characteristics of different generations of computer.
[T.U. 2059 Chaitra]
Ans: Computer generation's classification is mainly based on basic devices
used, architecture, languages, modes of operation etc. The functions
performed by computer, and speed of their operations has been
changing since olden days to most modern computers. There have
been great variation in size, cost,speed, storage capacity etc. The
phases are called generation of computer.
Each generation of computer is characterized by a major
technological development that fundamentally changed the way
computers operate, resulting in increasingly smaller, cheaper, more
powerful and more efficient and reliable devices.
The different generations of computers are:-
A. First Generation Computer (1945-1955): Vacuum Tubes
The features of first generation computers are:
(a) They were extremely large and occupied a very large
space.
(b) The operating speed was limited to milliseconds.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
E. Fifth Generation Computer(Present-Beyond): AI
b. They were more reliable and accurate than the first
The features of fifth generation computers are:
generation computer.
c. Punched cards and magnetic tape were used for input (a) The development of the fifth generation of computer
while punched cards and paper constituted the output. system is characterized mainly by the acceptable of
d. They had faster and larger primary and secondary parallel processing.
storage in comparison to first generation computers.
e. They required less electricity and emitted less heat.
f. They were much easier to program and use than first
generation computer. Hence, they had wider commercial
use.
C. Third Generation Computer (1965-1975): Integrated
Circuits
The main features of third generation computers are:
(a) They were much smaller than second generation
computer. So, it requires smaller space.
(b) They had faster primary and auxiliary memory as
compared to second generation computers.
(c) They consumed much less power than second
generation computers.
(d) The operating speed of computer was nanoseconds.
(e) They were reliable, better performance and had larger
storage capacity.
(f) The size of computer became much smaller.
(g) They were used for both scientific and commercial applications.
D. Fourth Generation Computer (1975-present):
Microprocessor
The main features of fourth generation computers are:
(a) The computers were smaller, cheaper, highly reliable and
accurate.
(b) The operating speed was in Picoseconds. (c)
They were used for general purposes.
(d) Magnetic disks became common source of internal
storage.
(e) Micro computers were introduced.
(f) Application software for microcomputer became more
popular.
(g) Further refinement of input/output devices took place.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …7 8 … A Complete Refresh Manual of C Programming


and instructions were fed into system using punch cards.
(b) These computers will use super conductor technology.
Second-generation computer replaced machine
The two future devices are Gallium Arsenide and
language with
Biochips. assembly language to replace long difficult binary codes for
(c) These machines will incorporate Ultra Large Scale giving instructions. Due to availability of large memories, some
Integration (ULSI). high level languages such as COBOL (Common Business
(d) The cost of hardware and software will decrease. Oriented Language) and FORTRAN (Formula Translator) came
(e) These computers will have artificial intelligence. in common use during this time.
5. Explain different generation of computer along with technologies
used in each generation.
Or, Explain about the generation of computer.
[T.U. 2061 Baisakh,2062 Baisakh]
Ans: The generation of computer means changes in size,cost,devices
used,languages used from olden days to most modern days.
a. First generation computer (1945-1955):Vacuum Tubes
The computer, using vacuum tubes as the electronic devices are
called first generation computers. Vacuum tubes were developed by
Lee Deforest in 1908.
Vacuum tubes were used as CPU components, acoustic delay
lines for main memory, magnetic tape and magnetic drum for
secondary memory. Data and instructions were fed into system using
punch card. The instructions were written in machine level language.
Examples: ENIAC, EDVAC, EDSAC, IBM series-IBM 701, IBM
704, IBM 709 etc.
The first generation computers were mainly used for scientific
computations.
Limitations: The storage capacity of computer was limited. It had low
operating speed (milliseconds, i.e. 10-3 sec). They had limited
programming capability. They had heat and maintenance problem. The
system cost and working cost were very high. They were restricted to
commercial applications.
b. Second generation computer (1955-1965):Transistors
Second generation computer started after the invention of
transistors by Trio group (John Braden, William Shockley and
Walter Brattain) in 1947 at Bell laboratories in US.
Transistors were used as CPU component, magnetic core for
main memory, magnetic tape and disk for secondary memory. Data
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
computer, is a semiconductor device consisting of electronic
The operating speed was increased up to the microsecond range (10-6
logic circuits manufactured by using VLSI technique. Then in 1971,
sec).They were more reliable and accurate than first generation computers.
American Intel Corporation developed first microprocessor
They had larger, faster primary and secondary storage as compared to first
generation computer. There was an overall reduction in system and operating
costs.
Second generation computers were used in payroll, inventory control,
marketing and production planning. Examples:-IBM 7090, IBM 7094I
IBM 7094II, CDC 1604, IBM 1620, IBM 1401, Honey well 400 etc
c. Third generation computer (1965 – 1975) : ICs
The third generation computers replaced transistors with “Integrated
Circuits (IC)” popularly known as chips.IC was developed by Jack St. Clair
Kilby and Robert Noyce in 1958.
Initially,SSI and MSI could replace transistors, and later on, the
semiconductor memories (i.e. RAM and ROM) replaced the magnetic core
memory as primary storage medium. The magnetic disk was able to replace
magnetic tape as secondary storage medium, keyboards and video display
terminals were introduced. Cache memory was also introduced.
Multiprocessing, multiprogramming, multi-user system were introduced. The
concept of virtual memory was introduced.
The operating speed was increased to nanoseconds, 10-9 sec.
Less manpower was required at assembly stage. They were smaller in size but
had high memory capacity.ANSI FORTRAN and ANSI COBOL and time
sharing operating system was used.PL/1, PASCAL, BASIC were notable high
level language of the 3rd generation. Examples:-IBM system/360, ICL 1900,
IBM 370 series, Honeywell
2200 series, CDC 7600, STAR-100 etc
d. Fourth generation computer (1975-Present) :
Microprocessor
The fourth generation computer used LSI (Large Scale Integration)
and VLSI (Very Large Scale Integration) circuits for internal operations.
A single silicon chip of LSI or VLSI has thousands of ICs built on it.
This chip reduced the physical size of the computer and increased their
power, efficiency and reliability. The speed of operation is measured in
pico-seconds (10-12 sec). Because of the VLSI technology, it becomes possible
to build many computing functions on a single chip.
The microprocessor, which is the main component of fourth generation
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …9 10 … A Complete Refresh Manual of C Programming


translate foreign languages also.There are different programs under way to
(microchip) called 4004 microprocessor. Today, such a
microprocessor contains millions of transistors. It is capable of develop fifth generation computer.
performing various computing functions and making decisions to • ICOT program in Japan.
change the sequence of program execution. Since 1973, many • MCC and DARPA project of USA.
American companies started to manufacture microcomputers. For
• Alvey project of UK.
examples, IBM PC, Apple/ Macintosh etc. ICL 2950/10 (International
Computer Limited Company) was brought in Nepal for census The famous 5th generation computer is fictional HAL 9000.
2038 B.S.
The semiconductor memories (RAM and ROM) are used as
primary storage and magnetic disk (floppy disk, hard disk), optical
disk (CD-ROM, CD-R/W, CD-R, DVD-R/W) and flash memory are
used as secondary storage.
The fourth generation computers are user-friendly, due to
development of operating system and application software. As smaller
computers but more powerful, they could be linked together, or
network, to share memory space, software, information and
communicate with each other. So, these computers are mostly used in
offices, home, teaching and other organizations.
e. Fifth generation computer (coming generation) : AI
The fifth generation computers are under development stage.
They will use super- conductor technology. The two future devices are
Gallium Arsenide (GaAs) and bio- chips.These machines incorporate
Ultra Large Scale Integration (ULSI) and contain millions of
components into a single IC. The development of super conductors
was declared by Japan in 1978. They will increase the capacity of
computer with millions of times.
The computers using bio-chips will be able to understand
natural language, speak command, capacity to see their surrounding
and will have thinking power called Artificial Intelligence (AI). In
contrast to present DIPS (Data Information Processing System), the 5 th
generation computers will have KIPS (knowledge Information
Processing System) and Prolog is expected to play an important role
for this. The computers will understand natural languages and
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

6. Differentiate between third and fourth generation of computer.


[Pokhara
University 2011] Ans: Differences between third and fourth
generation computer: Third Generation Computer Fourth Generation Computer
a. Duration = 1965 to 1975 a. Duration =1975 to present
b. IC chips with SSI (Small b. Initially, IC chips with LSI
Scale Integration) and MSI (Large Scale Integration) and
(Medium Scale Integration) VLSI (Very Large Scale
were used as CPU Integration) were used as CPU
components in this components in this generation.
generation. But, later on microprocessors
were used.
c. Magnetic disks were used for c. Magnetic disks became the
auxiliary memory. common source of external
storage media.
d. The operating speed of d. The operating speed of
computers was in computers was in Picoseconds.
nanoseconds.
e. Time sharing operating e. Graphic user interface
system, Cache memory and Operating System, optical
virtual memory were memory and flash memory
introduced. were introduced.
f. High level language like f. 4th generation languages and
PL/1, PASCAL, BASIC, etc application software for
was introduced. microcomputers became more
popular.
g. Initially, Magnetic core g. Semiconductor memories were
memories were used for used for main memory.
main memory but, later on,
semiconductor memories
were used for main
memory.
h. Flexible input and output h. More advanced devices, i.e.
devices, i.e. Keyboard and Multimedia keyboard, optical
monitor were developed. mouse or wireless keyboard,
and Mouse and LCD or Plasma
screen were developed for input
and output.
i. Examples: ICL 1900, IBM i. Examples: IBM PC, Apple
370 series, Honeywell 2200 Macintosh, IBM 3033, HP 300
series, CDC 7600, STAR- etc.
100 etc.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …11 12 … A Complete Refresh Manual of C Programming


7. What do you know about vacuum tubes,Transistors and IC? silicon chip, eliminating wired interconnection between components.
Explain. IC chips are much smaller in size, faster in operation, consumed much
Ans: Vacuum Tubes less power, high performance and more reliable than transistor and
The vacuum tubes were a glass device, which used filaments as vacuum tubes. Initially, the integrated circuits contained only up to
a source of electronics,could control and amplify electronic signals. It 100 components and the technology named as SSI. Later, with the
was the only high-speed electronic switching device available in those advancement in technology for manufacturing ICs, it became possible
days. The vacuum tubes required great amount of energy and to integrate from 100 to 3000 components on a single chip and this
generated much heat. Lost of space was required not only for the large technology named as MSI. They function as timers, amplifiers, logic
units, counters, calculators, temperature sensors, and radio receivers.
number of vacuum tubes but also for housing special air-conditioning
The IC was used in third generation computers and was
units to get rid of heat generated by tubes. patented by Jack St. Clair Kilby and Robert Noyce in 1958.
Vacuum tubes were the earliest electronic devices, which were
used in the first generation computer and vacuum tubes were
developed by Lee Deforest in 1908. The early television (TV) set also
used such tubes. It is a device for controlling flow of electrical current.
Transistor
Transistors were made of solid materials principally called
silicon and germanium semiconductor material rather than glass.
Therefore they were cheap to produce. One transistor replaced the
equivalent of 40 vacuum tubes. Transistors were found to conduct
electricity faster and better than vacuum tubes. They were also much
smaller and gave off virtually no heat compared to vacuum tubes.
Their use marked a new beginning for the computer. Transistors were
highly reliable as compared to tubes, since they had no part like
filament, which could burnt out. They were much smaller, less
expensive to produce than tubes. They could switch much faster
(almost ten times faster) than tubes
The transistors were used in second generation of computer and
were developed by John Braden, William Shockley and Walter
Brattain in 1947 at Bell laboratories in US.
It is the basic unit in radio, television and computer circuits. It
is often used to amplify the current flowing from one circuit to
another. Transistor consists three connecting parts: a base, an emitter
and a collector.

C
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
B
Symbol of transistor
E
IC (Integrated Circuit)
An Integrated Circuit (IC), also called a microchip, is an
electronic circuit consisting of a large number of electronic
components like transistors, resistors and capacitors placed on a single
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …13 2. Explain classification of computers based on size and capabilities.
[Pokhara University 2005, Semester-Spring]
1.2 Classification of Computer Ans: Types of computers on the basis of size are:
1. Differentiate between analog and digital computer. Also, draw block a) Super computer
diagram of digital computer. Super computers are the most powerful,largest, fastest and a
[Pokhara University 2009, Semester-fall] single problem oriented machine.Super computers are multi-user,
Ans: Differences between Analog and Digital Computer: multiprocessor very large machine.These computers are capable of
handling huge amounts of calculations that are beyond human
Analog Computer Digital Computer
a. Analog computer is one a. Digital computer works with
which is designed to work on binary digits (0 and 1) or it is a
numerical data represented machine that operates on data
by physical quantity (i.e. expressed in discontinuous
rotation or displacement or signals.
temperature).
b. It is specific or not versatile. b. It is general or versatile
machine.
c. The accuracy of this c. The accuracy of this computer
computer is very low is very high.
d. It has low storage capacity. d. It has high storage capacity.
e. It is costly. e. It is low in cost.
f. Have fewer functions. f. Have large number of functions
g. It is used only in scientific, g. It is mostly used for statistical
industrial and medical fields. data, numerical problems of
business and sciences.
h. Example of analog device is h. Examples: IBM PC, IBM
speedometer of an compatible etc.
automobile.
i. The symbolic representation i. The symbolic representation of
of analog computer is digital computer is

Block diagram of digital computer :Unit 1.3 (1)


F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

14 … A Complete Refresh Manual of C Programming (DEC). Minicomputers are commonly used as servers in network
environment and hundreds of personal computers can be connected to
capabilities. They can perform billions of instructions per second the network with a minicomputer acting as server like mainframes,
(BIPS). Some of the today’s super computers have the computing minicomputers are used as web servers. They have been widely used
capability equal to that of 40,000 microcomputers. A Japanese
as data processing, engineering analysis, industrial application
supercomputer has calculated the value of PI ( ) to 16 million decimal etc.Examples: AS 400, PRIME Series.PDP-11, VAX 7500, HCL,
places. These computers cost in 15 – 20 million-dollar range (most
MAGNUM etc.
expensive). They need large space and temperature controlled room
Super computers are typically used for number crunching
including scientific application, weather forecasting, simulations,
creating computer (animated) graphics, analysis of geological data
(e.g. in petrochemical prospecting), structural analysis, computational
fluid dynamics, electron designing, nuclear energy research and
metrology.
Examples: CRAY–1, CYBER 205, CDC–Star 100, NEC 500,
PARAM and ANURAG etc.
Among them, PARAM and ANURAG are supercomputers
produced by India and are exported to many European countries.
b) Mainframe Computer
Mainframe computer is a large, multi-user, general purpose
computer system and supports wide range of input and output
terminals with a large backing storage capacity. It supports large
number of terminals up to 100. It works on time sharing basis. It
requires an area of 1000 sq. ft.
Mainframes use proprietary operating systems, most of which
are based on UNIX, and a growing number on Linux. Mainframe
computers are generally used in big organization or government for
large scale data processing, credit card processing, bank account
management, generating life-like animation etc.
Example - IBM 4300 series, ICL 39 series, CDC 6600, IBM
1401 and CYBER 170 etc.
c) Mini Computer
Mini Computers are similar to the mainframe computers but
they are general purpose computer which are smaller, less powerful,
and have lower cost than mainframe computers but bigger than micro
computers. So they are called mid-range computer. They can support
50 terminals (i.e. 50 persons can work at the same time with single
minicomputer). They require area of 100 sq. ft. The first minicomputer
was introduced in the mid-1960s by Digital Equipment Corporation
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …15 16 … A Complete Refresh Manual of C Programming


d) Micro Computer any desired level of accuracy can be achieved by considering as many
A micro computer is the smallest general purpose, low cost
digital computer and uses microprocessor. It requires small space, can
be placed on a table or even kept inside a briefcase. It is designed to
use by one user at a time. So, microcomputer is also known as b) Digital
personal computer (PC). These computers have central processing unit Computer
on a single chip. They are mainly used in offices, homes, schools, Digital computer is a computer which stores data in
shops, stores etc. They can be connected to other computer systems in terms of digits (numbers) and proceeds in discrete form from
networking. For examples: IBM PC, Apple / Macintosh etc. The one state to
physical size of microcomputer has reduced very much and found in another. In digital computers, even letters, words and whole
the form of laptops, notebooks, palmtop, PDA (Personal Digital texts are
represented digitally.The main advantage of digital computer
Assistant), pocket computer etc.
is that
3. Classify the computer on the basis of operation,explain each of them
briefly.
Ans: Classification of computer on the basis of operations are:
a) Analog Computer
Analog computer is one which is designed to work on
numerical data represented by physical quantity (i.e. rotation or
displacement), electrical charge (voltage and charge), temperature,
weight etc which varies continuously. It is single problem oriented
machine, offer low cost and ease in programming. Mathematical
principles applied for data processing in analog computer are
logarithm, summation, exponentiation, calculus, multiplication and
division etc.
The main disadvantage of this computer is its low accuracy and
limited storage capacity. It lacks speed of calculation.Example of
analog device is speedometer of an automobile. They are mostly used
in engineering and scientific applications.
• Thermometer represents temperature in terms of a thread of
mercury.
• The speed of a car can be represented by the rotation of wheels.
• The analog computer is used in hospitals to measure the size of
stone in kidney and mental disease diagnostics (CT scan) with
photographs.
The symbolic representation of analog computer is
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
places of decimal as it is necessary. Digital computers are mostly used in the measure heart function, temperature and other signs of patients.
preparation of reports, results, tabulation and graphic representations. Thus, Then these measurements are converted into digital signal and
they help in mathematics, engineering, business, accounting etc. So, fed to the digital computer that monitors the patient’s vital signs.
they are versatile in nature. Most of the computers used in Nepal are
digital.Examples of digital devices are calculators,digital watches, and digital
thermometers etc.Examples of digital computer are: IBM PC, IBM
compatible etc.
The symbolic representation of digital computer is

Digital computers can be categorized into two categories


i. General-purpose digital computer
It is the one that can work on different types of programs input to it
and thus be used in countless application, i.e., these computers are designed
to do wide range of information processing tasks, from scientific to
commercial file processing. It can be used to prepare sales report, banking
system, payroll etc.
ii. Special purpose digital computer
They are designed to perform a specific task. The programs to carry
out the task are permanently stored in the computer memory. These types of
computer work efficiently but such computers are not versatile.
c) Hybrid Computer
A computer, which has a combined feature of both analog and digital
computers, is called hybrid computer. It helps user to process both
continuous and discrete data. It can transfer data from analog to digital and
vice-versa. These computers are generally used in aero planes, scientific
applications, industrial control processes etc. Here are two functional
examples:
• During the launching of rockets, the analog computers measure the
speed of the rocket, temperature and pressure of atmosphere.
These measurements are then converted into digital signals and
supplied to the digital computer to analyze the data for taking
appropriate steps on launching.
• In an Intensive Care Unit (ICU) of hospital, analog devices
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …17 18 … A Complete Refresh Manual of C Programming


4. Describe the types of computer on the basis of brand.
Ans: Classification of computer on the basis of brand are: 1.3 Computer System and Organisation
a) IBM PC 1. Draw the block diagram of computer and explain function of each
IBM PCs are microcomputers produced by IBM Company. block. [T.U. 2059]
These computers are more reliable, durable and have better quality. Or, Draw and explain the building block of computer with necessary
They are more expensive than IBM compatible computers. It was a diagram. [Pokhara University 2010, Semester-Spring]
complete system - with a built-in monitor, keyboard, and data storage Or, Draw the block diagram of digital computer and explain the
.It was specifically designed for professional and scientific problem- function of each block briefly.
solvers, not business users or hobbyists [Pokhara University 2003, Semester-Fall]
b) IBM Compatibles Or, What are functional block diagram of a computer system?
[T.U. 2062 Poush]
IBM Compatible Computers are IBM clones or PC clones; Ans: Computer system is a collection of integrated components (i.e. input,
computers that are internally almost the same as the IBM PC but the processor, memory and output) that have common purpose of
cost are less. The internal architecture of IBM compatible is similar to performing operations itself and the complete set of all the involved
IBM PC. So they are called duplicate computers. They have same components is called as a computer system. The basic elements of the
functional characteristics and principles of IBM PC. All the software computer system are essentially same for almost all the micro
designed for the IBM PC can be used in IBM compatible computers. computer; there are variations in constructions that reflect the differing
ways in which computers are used.
These computers are cheaper than IBM PC and their parts are easily
The major components of a computer system are:
available in the market.
c) Apple/Macintosh CPU
This computer is manufactured by Apple/Macintosh company
with totally different internal architecture from that of IBM. They
ALU Output
have their own softwares. The OS produced by Apple Company for Input
Devices
their Macintosh is called Mac OS. These computers are mostly used in Devices
Register
desktop publishing.

CU

Memory
Primary Memory
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Secondary Memory

Figure: Block diagram of a computer system


A. Input devices
Data and instructions are entered into computer through input
devices. The commonly used input device is keyboard. Several input
devices which do not require typing of information have been
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …19 20 … A Complete Refresh Manual of C Programming


developed i.e. joystick, light pen, mouse, trackballs etc. and these are (a) It carries out arithmetic operations i.e. addition, subtraction
called pointing device. Data and instruction can be entered into multiplication and division and performs certain logical
computer through input device in the form of typing, voice and operations i.e. comparing or testing whether two data items are
picture. Keyboard is used for typing of information, microphone is same or not.
used for voice input and scanner is used for entering data in the form
(b) It selects variables from registers.
of picture.
(c) It returns result to a memory or register.
B. CPU (Central Processing Unit)
It is an electronic brain of a computer. A central processing
unit (CPU) or processor is an electronic circuit that can execute
computer programs. The CPU controls the operation of all other
devices such as memory, input, storage and output devices besides
executing programs. Under its control, programs and data are stored in
the memory and displayed on the screen or printed through printer.
The CPU of small computer has single processor but larger
computers (i.e. Super Computers, Mainframe Computers and Mini
Computers) have a CPU with several linked microchips, called
microprocessors, performing separate tasks. Some newer
microprocessor (i.e. dual core processor) contains multiple chips and
is encased in their own cover which fits into a special socket on the
motherboard.
Functions of CPUs are:
(a) To control the use of primary memory to store data and
instructions.
(b) To control the sequence of all the tasks.
(c) To carry out processing.
(d) To carrying out commands to all parts of the computer system.
Most CPUs have 3 functional sections and these are:
(i) ALU (Arithmetic and Logical Unit)
The function of ALU is to perform arithmetic and logic
operations such as addition, subtraction, multiplication and division;
AND, OR, NOT, NAND, NOR, Exclusive–OR, Exclusive-NOR
operations etc.For example, suppose any two numbers located in the
memory are to be multiplied. They are brought into processor, and
actual multiplication is carried out by ALU.The multiplication may
then be stored in the memory or stored in the processor for immediate
use.
Functions of ALU are:
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
that can be directly accessed by the CPU which constantly interacts
(ii) CU (Control Unit)
with it, retrieves data stored there in, goes through instructions and
It is a component of a CPU which controls all the tasks of
execute them as per the requirement.
computer. It also controls all other devices like input, output devices
Previously William tubes, delay lines or rotating magnetic
and storage connected to the CPU. It maintains order and directs
drums were used as primary memory which was later replaced by
functions of the entire system. It fetches instruction from the memory
magnetic core memory.
and interprets the program instruction to know what tasks are
performed and sends suitable control signals to other components to
perform further necessary steps to execute instruction.
Functions of CU are:
• The computer accepts information in the form of programs and
data through input devices and stores it in memory.
• Information stored in the memory is fetched, under program
control, into an arithmetic and logic unit where it is processed.
• Processed information leaves the computer through output
devices.
• All activities inside the computer are directed by control unit.
(iii) Register
Register is a special purpose temporary storage location in the
CPU that is designed for storing data temporarily during the program
execution. They are quite differing from the locations in main
memory, although they can similar in structure. Register quickly
accept, store and transfer data and instruction that they are used
immediately. The number of registers differs from processor to
processor. The various types of registers available in the market from
previous days to today’s are 8-bit, 16-bit, and 32-bit and 64-bit
registers.
C. Memory
Memory is essential component of a digital computer system. It is the
place where computer stores program and data that help the program
in carrying out its operations.
There are two types of memory and these are:
(a) Primary Memory
The primary memory is a fast, compact and lighter memory
which stores programs along with data that are required to execute
user's program. When we launch our program, it is loaded into and run
main memory. If we enter new data, it is also stored in the main
memory. It is a temporary memory and consists of some chips either
on motherboard or on a small circuit board attached to the
motherboard of a computer system. Primary memory is the memory
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y f. Primary memory is not used f. Secondary memory is used as

y
bu

bu
to

to
as backup storage.
ww

ww
om

om
backup storage for present and
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
future use.
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …21 22 … A g.


Complete
PrimaryRefresh
memory Manual of C Programming
is volatile; g. Secondary memory is non-
when the computer is volatile memory.
b. Secondary Memory
The storage device is used for storing huge amount of data, switched off all the contents
programs and other information. It has much larger storage capacity of memory are lost.
than main memory. Storage device is also known as auxiliary h. RAMs and ROMs are used h. Hard disks, Floppy disks,
memory. The storage device is normally used to hold the program as primary memory. magnetic tapes etc. are used as
instructions, data and information of those jobs, on which the secondary memory.
computer system is not working on currently and transferred to the i. Primary memory can not be i. Secondary memory can be
primary storage as and when required .Secondary memory is much used as virtual memory. used as virtual memory.
cheaper than main memory but also slower than main memory. j. Primary memory is directly j. Secondary memory can be
Magnetic tape, Hard disk, floppy disks, pen drive, CD, Zip drives etc placed on the system board. placed in and out of using but
are used as secondary memory. Storage device can also be used as data cable is connected
backup memory. between secondary memory
and system board.
D. Output Devices
The output device receives the information from the computer
in the binary form and it converts that binary information into a
suitable form, which a user can understand easily. For example, output
device provides printed form or it displays on the screen or interprets
in voice. The examples of output devices are monitor, printer, speaker
etc. Output can exist in two forms:
(i) Hardcopy output
Hardcopy output refers to recording letters, graphics or pictures
on the permanent medium such as paper. The output can be read later
as the user’s requirement. The most commonly used hardcopy output
devices are printer and plotters.
(ii) Softcopy output
Softcopy output refers to the output displayed on the screen.
The output on the screen is lost when the computer is turned off. The
most commonly used softcopy output device is monitor. Sound
produced by voice output device (speaker) is also softcopy output.
2. Differentiate between primary memory and secondary memory.
Ans: Differences between primary and secondary memory:
Primary Memory Secondary Memory
a. Primary memory is also a. Secondary memory is also
known as main or known as magnetic or
semiconductor memory. auxiliary memory.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
b. Primary memory is faster, b. Secondary memory is slower
compact and lighter. and heavier.
c. Primary memory consumes c. Secondary memory consumes
less power. more power.
d. There is no rotating part in d. There is rotating part or tape
primary memory. in secondary memory.
e. Primary memory is e. Secondary memory is cheaper
expensive than secondary than primary memory.
memory.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …23 24 … A Complete Refresh Manual of C Programming


Examples:
1.4 Computer Software All purpose Symbolic Instruction Code), FORTRAN, PASCAL, and
C etc. is used to prepare tailored software. Examples: Salary sheet,
1. What do you mean by computer software? Describe briefly about sales ledger, payroll system, library management, etc.
system software. [T.U. 2057 Chaitra]
b. Packaged Software
Ans: A set of instructions given to the computer in machine code that tells
Package software is the software which is generalized a set of
the computer what to do and how to perform the given task of the user programs and developed for general purpose. These programs are user
is known as computer software. The main objective of software is to friendly and designed for use in more than one environment.
enhance the performance capability of hardware. Example:-Windows
XP, MS Word, MS Excel etc. Software can be divided into two
categories and these are:
• System Software
• Application software
System Software
It is a collection of program, language etc which allows the
user to communicate with computer equipments, the software makes
the machine easier to use and make efficient use of resources of
hardware. It is like a layer which acts as interface between computer
and application software .It is used in almost all kinds of computer
like mainframe, mini or micro computer.
Types of system software:
(a) Operating System
(b) Translating Program
(c) System Support Software/Utility Software
2. What is an application software? Explain its types with suitable
examples.
Ans: Application software is prepared and supplied by software company
and computer manufacturer. Application software is a subclass of
computer software that employs the capabilities of computer directly
to a task that user wishes to perform .Application software are
designed to process data and support users in an organization such as
solving equations or producing bills, result processing of engineering
etc.
Types of application softwares are:
a. Tailored Package
Tailored software is the software, which are specially designed
and developed to solve a specific or particular task. The nature of
processing of data seems similar but actually they are different in
many ways. High-level language such as COBOL, BASIC (Beginners
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

• Word processing packages: MS Word, Word Star etc.


• Spreadsheet: Excel, Lotus etc.
• Graphics: Photoshop, 3D studio max etc.
• DBMS Package: Dbase III, Oracle etc.
3. Differentiate between
(a) Hardware and software
(b) Program and software
(c) System Software and Application software
Ans : (a) Différences between Hardware and Software
Hardware Software
a. It is a physical component. a. It is instruction for
computer.
b. Hardware can be touched and b. It can not be touched and
seen. seen..
c. According to the function, c. There are two types of
there are different types of software, i.e. system
hardware devices like input, software and application
output, memory and software.
processor.
d. Same hardware devices are d. Generally software is
used for different types of deigned to perform only
operation, so we can say that one task or a few similar
hardware is multipurpose. task.
e. Examples: Keyboard, e. Examples: Windows
Monitor ,CPU etc XP,Photoshop,Maya etc.
(b) Differences between program and software
Program Software
a. A collection of instructions a. A set of instructions given
that perform certain task and to the computer in machine
is written in the form of code that tells the computer
computer language is called what to do and how to
program perform the given task of
the user is known as
computer software.
b. The main objective of b. The main objective of
program is to make software software is to enhance the
for general or specific performance capability of
purpose. hardware.
c. It is developed by a c. It is developed by a group
programmer. by programmer.
d. It can not be d. It can be categorized into
categorized. two types,i.e. System
software and application
software.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …25 26 … A Complete Refresh Manual of C Programming


e. License is not required to buy e. Software is licensed by a 1.5 Programming Languages
a program. software company .
f. Examples: Finding total, f. Example:-Windows XP, 1. Classify the types of programming language? Explain advantages
percentage, division and MS Word, MS Excel etc and disadvantages of each .
result of students in college. Or, What is programming language? Explain its type.
(c) Différences between system software and application software [T.U.2059 Poush]
Or, Briefly describe different types of programming languages
System Software Application Software and their major functions. [T.U. 2058 Chaitra]
a. System software is a group of a. Application software is Or, What is programming language? What are the types?
programs, languages which designed to fulfill user's Explain their characteristics. [T.U. 2060 Chaitra]
allow the user to requirements. Ans: Programming language is a set of rules that provides a way of
communicate with computer instructing the computer to perform certain operations. In another
equipments. word, it is a language used for expressing a set of computer
b. System software creates the b. Application software instructions (programs). Since, this language is responsible for
suitable environment to run depends on system human and system communication, it consists of necessary
application software. software to run. symbols, characters and grammar rules, which allow programmers
c. A special kind of training is c. A special training is to communicate with computers.Examples:C,C++,COBOL etc.
required in specific sector for enough for its construction. A. Machine Level Language : 1GL
its construction. Examples: Word, Excel It is the language of CPU. The lowest level of language having
Examples: LINUX, UNIX, etc. only the use two codes "0" and "1".The most difficult way to write a
Windows, etc. program and the chance of error is also high due to the type-error.
Even 1-bit changes the whole meaning. For e.g. if "01100000" is
typed instead of "01100001", then "ADD" may change to "DIVIDE".
Needs a lot of instructions even for writing a very small
program. Moreover, a program written for a CPU to work cannot be
executed in another CPU, because each type of processor has its own
machine code. E.g. the code for INTEL processor cannot execute in
MOTOROLA processor.
Advantages
a. Time taken to execute program is less
b. The programs written in this language need not to be
translated.
Disadvantages
(a) Difficult to learn.
(b) Machine oriented.
(c) The knowledge of computer internal architecture is essential
for program coding.
B. Assembly Level Language : 2GL
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
The language closer to what machines can understand.
Hence, also, known as machine oriented language. This is also
processor dependent likewise machine language. Assembly
language is an example of this. In this language each machine
language instruction is assigned a code. So, instead of having
to remember a string of 0's and
1's, programmer would only need to remember short codes like
ADD, MOV, SUB, MUL etc.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …27 28 … A Complete Refresh Manual of C Programming


object code and gives error messages after translations.
These symbols are called mnemonics. Hence; programming is
relatively easier than in Machine language. But, programmer yet has Advantages
a. They are easier to learn as compared to assembly and machine
to write long sequence of instructions even for a small program. Since
language.
this language just one step far from the machine language, many b. Lower program preparation cost.
programs are written in assembly languages so as to enhance the c. Machine independent
execution speed. This language isn't understood by CPU directly, Disadvantages
hence needed translation. A computer program which converts the a. Require more time and memory to execute.
"assembly language instruction" into " Machine language instruction"
is known as assembler.
Advantages
(a) Assembly language is easier to understand as compared to
machine language.
(b) Easier for program debugging.
(c) Assembly language is less cryptic as compared to machine
language.
Disadvantages
(a) It is machine dependent
(b) Program written in assembly language are comparatively
larger.
C. High Level Language [T.U. 2066 Magh]
High level languages were developed to make programming
easier. It is purely problem oriented rather than machine oriented. It
means, unlike, machine and low level, the program written for a
machine can be executed in another machine. It is fully machine
independent.
Each high level language has their own set of grammar and
rules to represent set of instructions. Programs written in HLL also
must be translated into MLL by compiler or interpreter. They use
familiar English words, special symbols and mathematical symbols in
their syntax. There are different types of high languages like
FORTRAN, COBOL, Visual Basic, Java etc.
The high-level language code is not directly executible. It
requires translators (like interpreter or compiler).
The program written in high-level language is referred as a
source program and has to convert into machine language. A program,
called compiler or interpreter, helps to translate the source code to
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Types of high level language are — natural language. They will use in coming generation computers to
communicate humans with computers i.e. they will use in the areas of
Procedure Oriented Language : 3GL
artificial intelligence and expert system.
The high–level languages, which require step-by-step sequence
Two popular natural languages are LISP (List processor) and
of instructions to solve a variety of problems (general problems), are Prolog (programming logic). Instructions written in such languages
called procedural-oriented languages or third generation languages (or often suffer from ambiguities.
General purpose programming languages). They are designed to help
the programmer in order to express the logic, the procedure, of a
problem in the form of a program. Examples of procedural languages
are BASIC, FORTRAN, C, C++, COBOL, FORTRAN etc.
Advantages
(a) Machine independent.
(b) Programmer is clear about the logic of the program. So he can
make any modification in the program.
(c) Requires less time to write.
(d) Easy to understand / learn.
Disadvantages
(a) Takes more time to execute the program
(b) Programmer should have the in-depth knowledge of the
programming language.
Problem Oriented Language : 4GL
Problem–oriented languages or fourth generation languages are
high–level language designed to solve specific problems or develop
specific applications by enabling the user to describe what he wants
rather than step by step procedures, i.e. it simply describes the
necessary input/output requirements. Sometimes these languages are
called non-procedural languages, as the programmer need not provide
the logic to perform a task. They are mostly database-oriented
language. Examples of 4 GL are: dBase III, Oracle, FoxPro, SQL
(Structured query language), QBE (Query By Example) etc.
Advantages
a. Machine independent.
b. Programmer need not provide the logic to perform a task.
c. Define report on the screen and form layouts including format
to be printed
d. Define input data and validation check
Disadvantage
a. Requires more memory as compared to 3 GL.
D. Natural Language : 5GL
Languages used for everyday communication are known as
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …29 30 … A Complete Refresh Manual of C Programming


For example, 4. Differentiate between high level and low level programming
“Calculate 4 and 6 divided by 2” has different interpretations. cannot be 100% full-proof, so it must be built in such a way that, if
Another example is “ I want ham or eggs and chips” some unavoidable circumstance appears, then it must tackle with this
2. What is high level language?What are the different types of high without being crashed.
level language? [T.U. 2067 Asadh, 2068 Mangsir, 2068 Baisakh] (g) Security
Ans: See the above Q.No. 1, page no. 26 (C) A program must be secured enough so as to avoid tampering
3. What is a Programming? What are the features of good from unwanted people. All the loopholes in the programs must be
programming language?Explain. avoided as much as possible.
Ans: A programming is the series of commands written by programmer in a
systematic order which can perform work easily in higher speed.
Features of good programming language are:
(a) Integrity
The calculations used in the program should be very accurate.
It must provide the desired output (functionally correct) for the given
input. It must do the work according to the specification.
(b) Clarity
The program should be well readable to aid maintenance later.
This can be provided online-documentation or external
documentation. On line documentation, the function of each piece of
code is defined within the program itself. In the external
documentation, a separate report includes the working principle of
each module inside the program.
(c) Simplicity
The program should be able to express the logic in a
considerably simple way. This feature enhances Integrity and Clarity.
Same problem can be done in two or more ways, but one needs to
choose the simplest way to solve the problem.
(d) Efficiency
The program should have a good compromise between Time
and space used, i.e. it should run as fast as possible (Time) with the
minimum memory requirements (Space).
(e) Modularity
Program should be separated to different logical and self-
contained modules. If the entire program is divided into simpler
contained modules then one can easily understand what’s happening
inside it.
(f) Robustness
Program must be fault-tolerant as much as possible. A program
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
language.
[T.U. 2069 Ashad, Pokhara Uiversity 2010, Semester-
Fall] Ans: Differences between low level and high level language
Low level Language High Level Languages
(a) It is machine dependent (a) It is machine independent
language. language.
(b) It is hard to learn. (b) It is easy to learn and
understand.
(c) Requires more time to write (c) Requires less time to write.
the program.
(d) It is older program. (d) It is newer program.
(e) Debugging is more (d) Debugging is easier
complex
(f) Uses assembler to (e) Programs are translated
generate object code using compiler or
interpreter to generate
object code
5. Differentiate between 3GLs & 4GLs.
Third-generation Fourth-generation Languages
Ans: Differences between 3GL and 4GL:
Language
1. Intended for use by 1. May be used by a non-
professional programmers. programming end user as well
as a professional programmer.
2. Requires specification of how 2. Requires specification of what
to perform tasks. task is to be performed
(system determines how to
perform the task.)
3. All alternatives must be 3. Default alternatives are built
specified. in; an end user need not
specify these alternatives.
4. Require large number of 4. Require far fewer instructions.
procedural instructions.
5. Code may be difficult to read, 5. Code is easy to understand
understand and maintain. and maintain because of
English-like commands.
6. Language developed for batch 6. Language developed
operation. primarily for on-line use.
7. Can be difficult to learn. 7. Easy to learn.
8. Difficult to debug. 8. Easy to debug.
9. Typically file-oriented. 9. Typically database-oriented.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …31 32 … A Complete Refresh Manual of C Programming


6. Differentiate between compiler and interpreter. Step3: Link the program using a linker. If no errors occur, the linker
[T. U. 2061 Poush , 2062, 2067 Ashwin, 2068 Baisakh] produces an executable program located in a disk file with an
Ans: Differences between compiler and interpreter .EXE extension and the same name as the object file (for
Compiler Interpreter example, FIRST.OBJ is linked to create FIRST.EXE).
a. Compiler is a program a. Interpreter is a program Step4: Execute the program. You should test to determine whether it
which translates a high which translates a statement functions properly. If not, start again with step 1 and make
level language program to of high level language
modifications and additions to your source code.
machine language at once. program to machine
language. 8. How many ways can we convert high level language to the machine
b. Program execution time is b. It can execute immediately level language? Explain all in detail with block diagram.
more before producing [T.U.2063 Poush]
executable program. Ans: We can convert high level to machine level into two ways,i.e.
c. It occupies larger part of c. It occupies less memory (A) Compiling Process
memory space because it is smaller (B) Interpreting Process
program in comparison to A. Compiling Process
compiler. Programs written in HLL must be translated into MLL by
d. It is faster because it runs d. It is slower because it repeats compiler or interpreter. They use familiar English words, special
executible programs. the process from the symbols and mathematical symbols in their syntax. There are different
beginning.
types of high languages like FORTRAN, COBOL, Visual Basic, Java
e. Examples:C,C++,FO- e. Examples : BASIC, LISP etc.
etc.
RTRAN etc.
The high-level language code is not directly executible. It
7. Explain compilation process in detail. [T.U. 2061, 2062]
requires translators (like interpreter or compiler)
Ans: Program written in high level language must be translated into
machine level language by compiler or interpreter.A program written Program written in HLL (high level)
in high level language is called source program and when a source Interpreter (e.g QBASIC)
program is converted by assembler or compiler, it is known as object
program.But, here we explain only the translation process and the OS
process or method of translating from high level language(i.e. source CPU
code) to machine language(i.e.object code) is called compilation
process.The compilation process is

Diagram to show how complier works


Source Object Program RUN
Compile Exec
Program Program Link
(Machine utabl
Code) e
Prog
Library Sub ram
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
high- referred and has to language. com rpreter, helps to translate the source code to object code and gives error
The level as a convert A pute messages after translations.
program langua source into program, r or B. Interpreting Process
written in ge is program machine called inte Interpreting is a program that converts each high level program
statement in to machine code just before the program statement is to
Step1: Write programs in any editor or compiler(e.g. C source code
be executed. Translation and execution occur immediately one
have extension .C),compile the programs using compiler for
statement at a time.
checking errors.
Step2: If there is no any type of errors arised,then the compiler Program Interpreter Executible
produces object file(i.e. .obj file). Statement Statement
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …33 34 … A Complete Refresh Manual of C Programming


converting our solution, algorithm of flowchart into an actual
9. What are the steps of problem solving process. Explain each of them
briefly. [T.U. 2060 Shrawan] computer program. For this, we have to choose a programming
Or, What are the steps involving during the programming? Explain. language depending on the type of application and code statements to
[Pokhara University 2011, Semester-Fall, implement our algorithm using the instructions that are available in
T.U. 2067 Ashwin, T.U. 2069 Ashad] that particular language. It has to be remembered that coding is the
Ans: Steps of problem solving process. easiest part of programming. Programs are often written first on
(a) Understanding problem special forms called coding sheets.
(b) Planning the method of solution
(c) Development by using algorithm, flowchart etc.
(d) Coding instruction into programming language
(e) Programming testing and debugging
(e) Documentation
(a) Understanding problem
The first step of problem definition is the most important step.
Unless the problem is defined and understood, clearly, the solution
can't be obtained. Clear problem definition and understanding may be
achieved by breaking down the problem into smaller steps.
(b) Planning the method of solution
Once we have understand the problem, we should plan for the
method of solution. Depending upon size of task, the program
preparation may be shared with many programmers. Large programs
may require more programmer to write separate part of program.
These separate parts are often called as modules or schedules. These
modules may be prepared and tested separately, then linked together
and tested as a whole program.
(c) Development of methods by using algorithm, flowchart, etc.
Once the problem has been broken down into smaller steps,
they can be written in a way that could be programmed easily for the
computer. A number of aids such as algorithm, flowcharts etc are
available to visualise the problem in broad terms and identify the
possible alternatives. Any algorithm will be in form step by step
sequence of procedure for solving a specific problem. During this
stage, the data pertaining to problem must be gathered and interpreted.
(d) Coding instructions in programming language
The step in the programming is coding. This is a process of
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
words, break a complex program into smaller, more manageable
(e) Programming testing and debugging
At this stage, we are ready to have next programming step, modules that can be reviewed and inspected before moving to the next
testing. We must first verify that our program has been written out and level of detail. Step-wise refinement is a powerful paradigm for
transcribed correctly and does what it is supposed to do. Computer developing a complex program from a simple program by adding
programs do not work properly the first time. The programmer might features incrementally.
have made logical errors in sequencing or perhaps errors were made in
entertaining the code. The process of correcting such error is called
debugging. The elimination of errors is lengthy and expensive process.
Care should be taken to see that all the errors are corrected. Once all
the errors have been made and corrected, the programmer is ready to
use program.
(f) Documentation
Documentation is an important part of software development.
This should be carried out simultaneously with design. Documentation
is used to keep track of the design process and implementation and
testing. There are two type of documentation, they are:
i. System documentation: System documentation includes
functional description, introductory manuals, reference
manuals, installation manuals, user manuals and so forth.
ii. Program documentation: The program documentation
includes a phase of program development documents. It should
include:
* Statement of problem
* Glossary of i/o values.
* Description of each module of program
* Error message produced by program
* Test data to be used in program modification.
10. Briefly explain what do you understand by stepwise refinement of
the program?
Ans: The concept of “Stepwise refinement” means to take an object and
move it from a general perspective to a precise level of detail and this
cannot be done in one jump but in steps. The number of steps needed
to decompose an object into sufficient detail is ultimately based on the
inherent nature of the object. “Stepwise refinement” of program
represents a "divide and conquer" approach to design. In simple
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …35 36 … A Complete Refresh Manual of C Programming


Some of the steps taken for refinement of a program are:
Flow chart
(i) Analysis of the algorithm used to develop the program, and
analysis of various parts of the program and then making Process 1
appropriate changes to improve the efficiency of the program.
(ii) Keep the program simple to improve memory efficiency. Process 2
(iii) Evaluation and incorporation of memory compression features.
Process 3
(iv) Debugging and testing performed first to module level and then
to interface level. (B) Selection
(v) Take care of correct working and clarity while making it faster. These are the computer instructions, which are to be executed
11. Explain the difference between the following: conditionally. i.e. they are executed based on conditions that can
Program testing and debugging. either true or false when the program is being executed and can do
Ans: Program testing is the process of checking program, to verify that it alternative things based on the truth of the “IF” conditions: There can
be various forms of conditions which are listed below:
satisfies its requirements and to detect errors. These errors can be of
any type-Syntax errors, Run-time errors, Logical errors. Testing a) Ony -way branching: IF statement
include necessary steps to detect all possible errors in the program. Syntax: IF <Condition> THEN
Do statements
This can be done either at a module level known as unit testing or at
ENDIF
program level known as integration testing.
Flowchart :
Debugging is a methodical process of finding and reducing the

One simple way to find the location of the error is to use print IF Condition?
statement to display the values of the variables. Once the location of
the error is found, the error is corrected and debugging statement may Statements
be removed.
12. What is control structure? Explain different types of control
structure. b) Two-way branching: IF … ELSE statement
Ans: The order in which program instructions are performed by the c
(
computer must be carefully controlled and programming language A e
contains features that allow the order of instruction execution to be )
controlled. They are called control structures. i.e., program control
structures are used to regulate the order in which program statements S
are executed. e
They fall into three categories. [T.U. 2062 Baisakh] q
(A) Sequence u
(B) Selection e
n
(C) Repetitions (Iterations)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Syntax:
IF <Condition> THEN
Statement1
ELSE
Statement 2
END IF Flowchart:

Yes

No
Condition?
Normally the statements are executed sequentially as written in Statement -1 Statement -2
the program. In other words, when all the operations specified in
particular statements are executed, the statement appearing on the next
line of the program is taken up for execution. This is also known as Fig. Flowchart of IF .... THEN.. ELSE Statement
the normal flow of control.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …37 38 … A Complete Refresh Manual of C Programming


c) Multi-way branching: IF… ELSE IF…. ELSE statement (d) Syntax and flowchart of SELECTCASE…..END CASE
Syntax: statement
Syntax> Flowchart:
IF <Condition 1> THEN
Statement 1 SELECT CASE
ELSE IF <Condition 2> THEN Expression Expression

CASE case1
Statement 2 Do Statement1 Y
ELSE CASE case2 Case1 Statement1

tatement 3 Do Statement2
…. N
ENDIF …. Y
CASE Default: Case2 Statement1

Example: Do StatementN
END SELECT N .
IF A>B AND A>C THEN .
.
PRINT”A IS GREATER” .
Example: N
ELSE IF B>A AND B>C THEN SELECT choice StatementN

PRINT “B IS GREATER” CASE 1


ELSE PRINT “Sunday”
PRINT “C IS GREATER” CASE 2
ENDIF
PRINT “Monday”
Flowchart:
CASE 3
t
Y
Condition 1 S Statement
3 1
t
a
t
e
Condition 1 m Statement 2
e
n
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
y esday” PRINT
P
CASE 4
” “Thursday” PRINT
R
CASE 5
“Friday”
I
CASE 6
P PRINT “Saturday”
N
CASE 7
R
T

N

T
T


e

W
s

e
d

d
a

n
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
CASE DEFAULT:
PRINT “Wrong choice”
END SELECT
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …39 40 … A Complete Refresh Manual of C Programming


(C) Repetition
These are the computer instructions, which are to be performed Flowchart for DO – WHILE loop
repeatedly and conditionally, i.e. the loop statements are driven by the
loop condition: Few example of iteration in programming languages Examples: Use REPEAT..UNTIL
are listed below: Do..While A=1
(a) While <Condition> A=1 REPEAT
Syntax: WHILE <Condition> DO PRINT A
Statements PRINT A A=A+1
End While A=A+1 UNTIL A<=10
Flowchart: WHILE A<=10
(c) FOR
true Syntax: FOR Loop_variable=Initial_Value TO Final_Value STEP
Statements
ENDFOR
false Flowchart:

Initialize
Flowchart for WHILE -- LOOP

Example: true
A=1
Condition? Statement Increment
WHILE A<=10
PRINT A
A=A+1 False
END WHILE Example:
(b) REPEAT – UNTIL <condition> OR DO –WHILE <condition> FOR A =1 TO 10 STEP 1
statement PRINT A
-for trailing decisions (at the end of the loop) END FOR
-condition must be false to stay in the loop
(Used in Pascal) 13. What is an algorithm? What are the rules to write algorithm. Write
Syntax: REPEAT down its advantages.
Statements Ans: Algorithm
UNTIL(Condition) [Pokhara University 2004, 2005, 2009 & 2006, 2010]
The general syntax of DO…WHILE statements is Algorithm can be defined as a sequence of instructions designed in a
Syntax: DO manner that, if the instructions are executed in the specified sequence,
Statements the desired results will be obtained. It is named after its Arabian
WHILE (Condition) inventor Musa Al-Khowarizmi of Baghdad (Iraq) means receipe, A
sequence of instruction must posses the following characteristics:
Flowchart: [Pokhara University 2004, 2008]
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

(a) Each and every instruction should be precise and unambiguous.


(b) Each instruction should be performed in a finite time.
true (c) One or more instructions should not be repeated infinitely. This
ensures that the algorithm will ultimately terminate.
(d) After performing the instructions, that is, after the algorithm
false terminates, the desired results must be obtained.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …41 42 … A Complete Refresh Manual of C Programming


Advantages of algorithm: Step 5 : Add 2 in A
a) It is a convenient method of communication. Step 8 : Stop
b) It saves the inconveniences in future and serves the purpose of 17. Write an algorithm to print sum of odd numbers up to 100.
documentation for a system. Ans: To solve the questions,
c) It provides facility for troubleshooting. Step 1 : Start
d) It provides an overview of the system and also demonstrates Step 2 : Store 1 to A
the relationship between various steps. Step 3 : Print A
e) It promotes logical accuracy. Step 4 : Store A in sum
f) It makes sure that no logical path is left incomplete without any
action being taken.
14. Write an algorithm to read two numbers M and N, add them and
print the result.
Ans: To solve the questions,
Step1: Start
Step2: Read value of two numbers M & N.
Step3: Add M and N.
Step4: Print sum of M and N.
Step5: Stop
15. Write an algorithm and draw a flow chart to find the biggest number
among and two numbers.
Ans: To solve the questions,
Step1: Start
Step2: Read two numbers A and B
Step3: Is A greater than B ?
Step4: If yes, then display "A is the biggest."
Otherwise, display "B is the biggest."
Step5: Stop
16. Write an algorithm and a draw a flowchart to find sum of first 10
natural numbers.
Ans: Algorithm:
Step 1 : Start
Step 2 : Store 1 to A
Step 3 : Print A
Step 4 : Store A in sum
Step 5 : Add 1 in A
Step 6 : Is A less than 10?
If yes, repeat step 3 onwards
If no, go to step 7
Step 7 : Print sum
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Step 6 : Is A less than 100? program documentation, which is needed for various purposes.
If yes, repeat step 3 onwards d. Efficient Coding: The flowcharts act as a guide or blueprint
If no, go to step 7 during the systems analysis and program development phase.
Step 7 : Print sum e. Proper Debugging: The flowchart helps in debugging process.
Step 8 : Stop
18. Design an algorithm to generate nth member of the Fibonacci
sequence.
Ans: An algorithm to generate nth number of Fibonacci sequence is:
Step1: start
Step2: Scan the number ‘n’ upto which the series to be generated.
Step3: Initialize Sum=0, x=0, y=1 and i=3.
Step4: Print x and y as the part of series.
Step5: Repeat a-e until i<=n
a. Calculate Sum=x+y
b. Print Sum as part of series.
c. Assign y to x
d. Assign sum to y
e. i=i+1
Step6: Stop.
19. What is a flowchart? What are the advantages and disadvantages of
flowchart?
Ans: Flowchart [T.U. 2061 Poush]
[Pokhara University 2009, 2006, 2011]
A flowchart is the symbolic representation of the step by step solution
of a given problem, and it indicates the flow of the entire process, the
sequence of data input, operations, computations, decisions, results
and other relevant information, pertaining to a particular problem. It
uses different shape boxes to denote different types of instructions.
The actual instructions are written within these boxes using clear and
vivid statements. These boxes are connected by lines having arrow
marks to indicate the way of operation, the exact sequence in which
the instructions are to be executed.
Advantages of flowchart
a. Communication: Flowcharts are better way of communicating
the logic of a system to all concerned.
b. Effective analysis: With the help of flowchart, problem can be
analysed in more effective way.
c. Proper documentation: Program flowcharts serve as a good
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …43 Rectangle Process


f. Efficient Program Maintenance: The maintenance of operating
program becomes easy with the help of flowchart. It helps the
programmer to put efforts more efficiently on that part
Disadvantages of flowchart
a. Complex logic: Sometimes, the program logic is quite
complicated. In that case, flowchart becomes complex.
b. Alterations and Modifications: If alterations are required the
flowchart may require re-drawing completely.
c. Reproduction: As the flowchart symbols cannot be typed,
reproduction of flowchart becomes a problem.
20. What are the rules for drawing a flow chart ? What are symbols to
draw flowcharts?
Ans: Rules for designing flowchart are:
a. Always concentrate on the main logic of problem.
b. After complementing the main logic, concentrate on the
branches and loops.
c. Use only one starting and stopping point.
d. Avoid using computer language in a flow chart.
e. The terms used in the flow chart should be unambiguous, so
that any programmer can easily understand the logic.
f. Flow lines should not cross each other normally.
g. The arrowheads are used to indicate the direction of flow of
control in the problem. The general direction of flow in any
flow chart is from top to bottom or from left to right.
h. The connectors joining the different pages must be adequately
referred while drawing a chart on more than one sheet of paper.

Symbols used for drawing flowcharts are: [T.U. 2061 Poush]

Symbol Name Purpose


Oval shape Start / End
Parallelogram Input / Output
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

44 … A Complete Refresh Manual of C Programming Ans: Differences between algorithm and flowchart: Algorithm
Flowchart
21. Differentiate between algorithm and flowchart with examples.
a. It is pictorial representation a. It is a sequence of
Diamond shape Making decision of a program. instructions of a program.
Flow lines Flowing way b. It takes more time because b. It takes less time because we
Circle Connector we need to draw symbols. need to write sequence of
instructions.

c. Require special knowledge c. Special knowledge is not


about flowchart to draw it. required to write algorithm
because it can be written in
human language.

d. Maintaining a flowchart is d. Maintaining an algorithm is


very difficult. not difficult as flowchart.

e. Flowchart has two types,i.e. e. Algorithm has no type.


system flowchart and
program flowchart.

f. Example: An algorithm for f. Example: A flowchart for


finding the biggest number finding the biggest number
among and two numbers. among and two numbers.

Sol:i.Read two numbers A Star t

Inp ut A, B
and B.

ii. Is A greater than B ? No IS Yes

A > B?
iii. If yes, then display "A is
the biggest." Prin t " B is g reater" P rin t "A is g r eater"

Otherwise, display "B is the


Stop
biggest."

iv. Stop
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …45 46 … A Complete Refresh Manual of C Programming


22. Draw a flowchart to read two numbers M and N, add them and print 24. Computer scholarships are given to be on the following basis:
the result.
Ans: Flow chart: Marks Scholarship
Start Less than equal to 90 40%
Greater than equal to 70 and less than 90 35%
Greater than equal to 60 and less than 70 25%
Input M & N
Less than 60 0%

Sum = M + N The computer fee for a course is 20,000. Draw a flow chart which
inputs the marks and computes the fee a student has to pay.

Print Sum Start

Input M
Stop

23. Draw a flow chart to find bigger number among any two different Y
numbers. IS
M > = 90 ? S = (20000 * 40)/10
Ans: Flowchart for finding bigger number

Start

IS Y
Input A, B S = (20000 * 35)/10
M > = 70 AND
M < 90 ?

No IS Yes

A>B?
IS Y
M >= 60 AND S = (20000 * 25)/10
M < 70 ?
Print "B is greater" P rint "A is greater"
N

Fees – 20000 – S
Stop
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Fees = Fees

Stop
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …47 48 … A Complete Refresh Manual of C Programming


25 Write an algorithm and draw a flow chart to print the following Write “C is largest”
series 1, 1, 2, 3, 5, ……. upto 10th term. [or, Fibonacci Series] Else
Ans: Algorithm : Question no. 18. [T.U. 2068 Mangsir] If B>C then
Flowchart Write “ B is largest”
Start Else
Write “C is largest”
Stop4: Stop
Z=1
Flowchart
A= 0 Start

Input A, B , C
B=0

C=1 N IS Y

A>B?
Print C

N N
A= B IS IS

Z =Z+ 1 B>C? A> C ?

B=C
Y Y
Print "B is greater" P rint "C is greater" P rint "A is greater"
C =A+ B

Y IS Ans: Algorithm
Step 1: Start
Z < = 10 ? Step 2: Read three numbers and store them in A, B and C.
Step 3 If A>B then
N If A>C then
Write “A is the largest”
Stop Else

26. Write and algorithm and draw flowchart to find the largest of
three numbers. [T.U. 2057 Chaitra]
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Stop

27. Write an algorithm and flowchart to check whether a number is


exactly divisible by 3 but not by 2. [T.U. 2059 Poush]
Ans: Algorithm
Step 1: Write “Enter a value”
Step 2: Read N
Step 3: Check if N is divisible by 5 but not by 2 then goto
step4; otherwise go to step5
Setp 4: Write “Divisible by 3 but not by by 2”.
Step 5: Stop
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …49 50 … A Complete Refresh Manual of C Programming


Flowchart 29. Write the algorithm and flowchart for a program that reads four
Start numbers and finds the largest among them.
[T.U. 2060 Shrawan]
Input N Ans: Algorithm
Step 1 : Write “ Enter any four numbers”
Step 2 : Read A,B,C,D
True
If (N% 3 = 0 AND Step 3 : If (A>B AND A>C AND A>D) then
N% 2 0)
(Max=A and go to step7)
False Step 4 : If(B>A AND B>C AND B>D) then
Print “Divisible by 3 but not (Max=B and go to Step7).
by 2” Step 5 : If(C>A AND C>B AND C>D) then
(Max=C and go to Step7)
Stop Step 6 : Otherwise;Max=D
Step 7 : Write “Maximum number=”;Max
28. Write an algorithm and flowchart for program that checks whether
the number entered by user is exactly divisible by 5 but not by 11. Step 8 : Stop
[T.U. 2059 Chaitra] Flowchart
Ans: Algorithm Start

Step 1 : Write “Enter a value” Input A, B, C, D


Step 2 : Read N
Step 3 : Check if N is divisible by 5 but not by 11 then goto step 4
If (A>B AND A>C v
otherwise, go to step5 F
a i n
Setp 4 : Write “Divisible by 5 but not by by 11”. l s o
i t False
Step 5 : Stop s b
e l b
Flowchart
P e y
Start r
i b 1
Input N n y 1
” False
t
5

If (N% 5 = 0 D Stop bTrue
AND N% 11 0) i u
t
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Max
AND A>D)
Tru =A
e

IF(B>A ANDB>C AND B>D)


Max
Tru =B
e
IF(C>A ANDC>D AND C>B)
False

Max=D Max
=C
True

Print Max

Stop
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y 30. Write an algorithm and draw a flowchart to find sum of first 10

y
bu

bu
to

to
natural numbers.
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
k e r - s o f t w a Ans: Algorithm
.

.
ac ac
k e r- s o ft w a

Introduction to Computers …51 52 … A Complete Refresh Manual of C Programming


Flowchart

Start
Step 1 : Start
Step 2 : Initialize the variables Count to 1 and Sum to 0..
Step 3 : Write Count A= I
Step 4 : Sum=Sum+Count
Step 5 : Count=Count+1 Ptint A
Step 6 : If Count<=10 then goto step3
Step 7 : Write Sum Sum = Sum + A
Step 8 : Stop
Flowchart A=A+ 2
Start
Yes IS
A=I A <= 100 ?
No
Ptint A
Print Sum
Sum = Sum + A

Stop
A=A+ 1
32. Write an algorithm and draw a flowchart to find factorial of any
Yes IS given number.
A < = 10 ?
Ans: Algorithm
No
Step1: Start
Print Sum
Step2: Write “Enter any number”
Stop
Step3: Read N
31. Write an algorithm and draw a flow chart to print sum of odd Step3: Write Count
numbers up to 100. Step4: Sum=Sum+Count
Ans: Algorithm
Step5: Count=Count+2
Step1: Start
Step6: If Count<=100 then goto step3
Step2: Initialize the variables Count to 1 and Sum to 0..
Step7: Write Sum
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Step8: Stop
Step4: Initialize the value of variables Count=1 and Fact=1.
Step5: Is count less than or equal to N?;then repeat the
steps 5.1 and 5.2
5.1 Fact=Fact*Count
5.2 Count=Count+1
Otherwise;go to step7
Step7: Write Fact
Step8: Stop
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …53 54 … A Complete Refresh Manual of C Programming


Flowchart 34. The Nepal television wants to convert temperature in Fahrenheit of
5 different regions. Write an algorithm and draw a flowchart to
Start F – 32
accomplish this using the formula c = where
1.8
Input N F = Fahrenheit
C = Celcius
Count=1 Ans: Algorithm
Fact=1 Step 1: Start

False Step 2 : First of all, set the value count = 1, which is used to count
Is Count<=N? the number of regions for which temperature conversion is
True done.

Fact=Fact * Count Print Fact Step 3 : Accept region, name & temperature

Coun=Count+1
Step 4 : Compute conversion by using formula

Step 5 : If count =6, stop the process.


Stop
Step 6 : Otherwise, increment the count by 1 and repeat job of
33. Write an algorithm and draw a flow chart to read name, class and conversion for remaining cities.
marks for five different subjects. Find the average. If average is
Step 7: Stop
greater or equal to 40 print "PASS" else print "FAIL" .
Ans: Algorithm: Flowchart
i. Read name, class and marks of five different subjects. Start
ii. Find the average marks.
iii. If the average mark is greater than or equal to 40 then print
"PASS" otherwise print "FAIL". Count = 1
iv. Stop.
Flow chart:
S tar t Input region, F

Read N $, E , M , S , C, N

Avg = (E +N +M +S+ C) /5 1.8

IS Av g > = 4 0 ?
Y
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Print region C

N N IS
Pr int "P as s"
Pr int " Fail" Count = 6 ?
Y
Stop
Sto p
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …55 56 … A Complete Refresh Manual of C Programming


35. Write algorithm and draw a flowchart for a program that calculates 36. Draw flowchart to print the following pattern. [T.U. 2063 Baisakh]
sum of digits of an integer number [T.U. 2062 Baishakh] 5
54
Ans: Algorithm 543
Step1: Start 5432
54321
Step2: Define the variable number,remainder and sum
Ans:
Step3: Initialize sum to 0. Flowchart
Step4: Read the value of number. Start
Step5: Repeat the steps 5.1,5.2,5.3 while number is not equal to 0.
5.1 Find remainder using the formula n mod 10.
5.2 Add sum to remainder I=5
5.3 Divide number by 10 to ontain the value of number..
False
Step6: Write sum
Is I>=1?
Step7: Stop
Flowchart
Stop True
Start
J=5

Define the variable number,remainder and sum False


Is J>I? I=I-1

Sum=0 True

Print J
Read number

lse rem=number
F mod
Is n!=0? 10
a sum=sum+number
/10
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
lowchart to Jread a 5-digit number and check whether the number is
palindrome or = not.
True J [T.U. 2065 Shrawan]
Print sum Ans: Step 1: Start -
1 the variable i.e. n, r, sum & a.
Step 2: Declear
3 Step 3: Read a five digit number ,n
7 Step 4: Assign the value of n to a and zero to sum
Stop
. Step 5: Repeat the step 5.a, 5.b and 5.6 unti the number is not to 0.
5.a r = n% 10
W 5.b sum = sum * 10 + r
r 5.c n = n/10
i
t
e

a
n

a
l
g
o
r
i
t
h
m

a
n
d

d
r
a
w

f
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …57 58 … A Complete Refresh Manual of C Programming


Step 6: Check if sum is equal to a,display number is Step 4: If x1 = 0 or x2 = 0 or y1 = 0 or y2 = 0 go to step 3 otherwise
palindrome,otherwise,display number is not palindrome. goto step 5.
Step 7: stop Step 5: Calculate D = (x2 – x1)2 + (y2 – y1)2
Start Step 7: Stop
Start
Declare variables
n,r, sum Declare variables

Read five digits number n


Read x1,y1,x2 & y2

Assign t = n & sum = 0


True
Is x1 = 0 or x2 = 0
Calculate or y1 = 0 or y2 = 0
r = n% 10
Sum = s*10 + r
n = n/1
False

sum = ? D = (x2 - x1)2 + (y2 – y1)2

True
Display D
False Is False Display number is
n = 0? not palindrome Stop
True points (x1, y1) and (x2, y2), governed by formula D2 = (x2 – x1)2 +
(y2 – y1)2, where x1, y1, y2 are given by user, but should not be zero.
Display number is
palindrome [T.U. 2067 Ashadh]
Ans: Algorithm
Step 1: Start
Step 2: Declare variable x1, x2, y1, y2, D
Stop Step 3: Read Co-ordinates of points x1, y1 & x2, y2

38. Write an algorithm and flow chart of the distance between two
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

39. What is a pseudocode? Explain.


[Pokhara University 2010, Semester-Fall]
Ans: Pseudocode
It is another programming analysis tool which is used for
planning program logic. It allows programmer to represent the logic of
program in manner which may look like plain English, so anybody
can understand it without any difficulty.
It put verbal descriptions into a logical structure, which
removes logical ambiguities. This methodology provides the best of
two areas: The logical structure removes logical ambiguities. But,
English narratives can still be to describe activities.
In short, Pueudocode is an aid to develop program and it
expresses the logic of program in way similar to that of flowchart.
Example:
Write a pseudocode to find sum of first 10 natural numbers.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …59 60 … A Complete Refresh Manual of C Programming


Initialize number to 1. (f) Decision Tree
Initialize sum to 0. Explanation of any three of them are:
REPEAT
Comments:
Add number to sum
Comment is a tool used for documenting progam.It means the
Increase number by 1.
explanation of program instructuion which help programmer to
UNTIL number=10
understand program easily.It is provided in systematic order.
Print sum
In C, /* is called opening comment mark and */ is closing
STOP
comment mark. The C compiler ignores everything between the
40. What is testing and debugging? Explain. [T.U. 2057 Chaitra]
opening comment mark and closing comment mark. The comment is
Ans: Program testing is the process of checking program, to verify that it
used for program documentation.
satisfies its requirements and to detect errors. These errors can be of
42. Draw a flowchart and algorithm to find of a quadratic equation
any type-Syntax errors, Run-time errors, Logical errors and Latent
(ax3 + bx + c = 0). Include all three conditions of the determinant.
errors. Testing include necessary steps to detect all possible errors in
[T.U. 2068 Shrawan]
the program. This can be done either at a module level known as unit
testing or at program level known as integration testing. Ans: Algorith
Step 1: start
Debugging is a methodical process of finding and reducing the
number of bugs in a computer program making it behave as expected. Step 2: Declare variable a, b, c, real, imag, d, x2,x2
One simple way to find the location of the error is to use print Step 3: Read the coefficient a, b & c
statement to display the values of the variables. Once the location of Step 4: Calculate discriminant, d = b2 – 4ac
the error is found, the error is corrected and debugging statement may Step 5: Check if d is greater than zero, perform the following
be removed. operations.
41. What are different techniques to keep documentation? Explain any
–b + d –b – d
5.a x1 =
three of them. 2a 5.b = 2a
Ans: Documentation is one of the most vital parts of software development.
(a) Algorithm
It helps to those who use and maintain software so that the software
becomes easy to extend, redesign and debug. (b) Comments
Among the popular techniques found in documentation are (c) Diagrammatical documentation such as
flowcharts, on-line comments, data flow diagram, Entity relationship Flowchart,DFD,ERD (d) Pseudocode
diagram, Use-Case diagram, Class/Object diagram, Structure diagram, (e) Decision Table
interaction diagram and state-diagram etc.
The different techniques to keep documentation are:
The documentation techniques are –
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Display roots are real & unequal
Step 6: Display value of x1 & x2,
Step 7: check if d is equal to zero, perform the following operations.
–b
7.a: calculate, x1 = x2 =
2a
Display roots are real & equal
Step8: Display value of x1 & x2, go to step 10
Step 9: calculate, d = – d
–b d real =
& imag =
2a 2a
Display roots are imaginary
Display x1 = real + imag i
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …61 62 … A Complete Refresh Manual of C Programming


Display x2 = real – imag i In above example, when b=1, then term will be infinite.
Step 10: stop (c) Logical error
43 What are three types of errors? Explain each of them briefly. Logical errors arise due to the mistake made by the
Ans: The three types of errors are: programmer while coding his/her problem. It is the most difficult
(a) Syntax error stage of the programming process because one does not know as to
what is going wrong and where? i.e., logical errors are difficult to
(b) Run-time errors/Execution error
predict than syntax errors because the computer will not print any
(c) Logical error error message and will produce some wrong results.
(a) Syntax error Logical errors may be due to;
Syntax relates to a grammar of the programming language. (i) Faulty methods
This type of error occurred because of misuse of a programming
(ii) Incorrect implementation of formula
language, i.e., syntax error occurs when we have violated the rules of
programming language. When an error is encountered, the computer for(num =1; num<=5; num++)
rejects the program and print out an error message. These errors are {
very easy to correct. In many cases, these errors arise due to spelling sum =0;
mistakes, missing commas, missing semicolons etc.
sum=sum +num;
For example,
}
10 REED x, y
cout<<”sum=” <<sum;
has been written in correct form
The above example is syntactically correct but does not give correct
10 READ x, y Syntax error Logical error
answer.
(b) Run-time error (Execution Errors) a. This type of error occurred a. It is a type of program’s
44. Differentiate between syntax errors and logical errors.
because of misuse of a logic errors.
If a program is grammatically correct, then compiler translates {
programming language, i.e.,
source code into object code. While execution, the program may syntax occursbwhen= b-1;we have
behave abnormally because of some errors other than syntax or violated the rules of
term = a /b;
semantic errors. The errors, which appear during execution of a programming language.
program, are called run-time errors. For example, divide by zero, b. Syntax error cout<<term;
is located by b. Logical errors are not
translator or
} interpreter identified by compilers and
infinite loop causing no output, machine error etc are run time errors.
during translating the interpreters during
a = 20; program. translation.
for(b=1; b<=5; b++) c. Users of a program can c. Logical errors are not easy
correct syntax errors. for users. So logical errors
can be solved only by
specific programmers.
d. Cost is low in correcting d. Cost is high in correcting
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Ans: Differentiation between syntax and logical errors is


F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Introduction to Computers …63 64 … A Complete Refresh Manual of C Programming


syntax errors, since normal logical errors, since
users can solve this problem. program development team Unit 2
are required to be involved C Programming Language
to solve this problem.
e. Example: e. Example:
x=a + b for(a =1;a>=5; a++)
In the above assignment { are frequently used for debugging process. These are used to
statement, there is missing Printf(“%d\n”,a); insert the break-point in the program.
semicolon ( ; ) at the end.
}
Infinite loop causing no output
45. What is debugging? Explain the process of program debugging.
Ans: Program debugging is the discovery and correction of programming
errors. A program cannot be 100% correct throughout its life-time and
a very few programs run correctly for the first time. So, debugging is
an important and time-consuming stage of software development.
Program debugging and testing is also known as Verification and
validation respectively. Verification ensures that the program does
what the programmer intends to do. Similarly, validation ensures that
the program produces the correct results for a set of test data.
Debugging is basically done to find
• Syntactical error
• Semantic / logical error
The tools and methods for debugging a program are as follows:
(a) Simulator: A simulator is a computer program that simulates
the execution of programs on another computer.
(b) Break-point: A break point is a place in a program at which
execution of program can be halted, in order to examine the
current state of program.
(c) Trace routines: A trace is a program that prints information
concerning the status of the processor at specified intervals.
(d) Memory dump: A memory dump is a listing of the current
contents of a section of memory.
(e) Software interrupt: Software interrupts or trap instructions
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
1. What is structured programming? Explain its advantages.
Ans: It is the collection of principles and practices that are directed toward
developing correct programs which are easy to maintain and
understand. A structured program is characterized by clarity and
simplicity in its logical flow.
The Three important constructs upon which structured
programming is built are:
• Sequence-Steps are performed one after the other.
• Selection-Logic is used to determine the execution of a
sequence of steps. For example,if-then-else construct.
• Iteration-A set of actions are repeated until a certain condition
is met. For example while construct.
The various advantages of structured programming are:
1. Complexity of program reduces.
2. Easy maintenance.
3. Simplified understanding.
4. Reusability of code increases.
5. Testing and debugging become easier.
2. What is a ‘C’ language? Why we use C? Explain.
Ans: It is a structured programming language which is used to develop
operating system, business system, word processing, database
management system etc. It was developed by Dennis Ritchie at the
Bell Telephone Laboratories in 1972, USA. Every function of C is
accompanied by its own set of library functions and every library
function is accompanied by their separate header files. Unlike some
languages that ignore case, C is case-sensitive. This means that a
variable named a is different from a variable named A.
In today's world of computer programming, there are many high-level
languages to choose from, such as C, Pascal, BASIC, and Java. These
are all excellent languages suited for most programming tasks. Even
so, there are several reasons why many computer professionals feel
that C is at the top of the list:
a/ C is a powerful and flexible language. What you can
accomplish with C is limited only by your imagination. The
language itself places no constraints on you. C is used for
projects as diverse as operating systems, word processors,
graphics, spreadsheets, and even compilers for other languages.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …65 66 … A Complete Refresh Manual of C Programming


b. C is a popular language preferred by professional 4. Explain the C development cycle.
programmers. As a result, a wide variety of C compilers and Or, Explain the compilation process of C program.
helpful accessories are available. Ans: The C Development Cycle is
c. C is a portable language. Portable means that a C program Step 1: Use an editor to write your source code. By tradition, C source
written for one computer system (an IBM PC, for example) can code files have the extension .C (for example, FIRST.C,
be compiled and run on another system (a DEC VAX system, DATABASE.C, and so on).
perhaps) with little or no modification. Portability is enhanced Step 2: Compile the program using a compiler. If the compiler doesn't
by the ANSI standard for C, the set of rules for C compilers.
find any errors in the program, it produces an object file. The compiler
d. C is a language of few words, containing only a handful of
terms, called keywords, which serve as the base on which the produces object files with an .OBJ extension and the same name as the
language's functionality is built. You might think that a source code file (for example, FIRST.C compiles to FIRST.OBJ). If
language with more keywords (sometimes called reserved the compiler finds errors, it reports them. You must return to step 1 to
words) would be more powerful. This isn't true. As you make corrections in your source code.
program with C, you will find that it can be programmed to do Step 3: Link the program using a linker. If no errors occur, the linker
any task. produces an executable program located in a disk file with an .EXE
e. C is modular programming. C code can (and should) be written extension and the same name as the object file (for example,
in routines called functions. These functions can be reused in
FIRST.OBJ is linked to create FIRST.EXE).
other applications or programs. By passing pieces of
information to the functions, you can create useful, reusable Step 4: Execute the program. You should test to determine whether it
code. functions properly. If not, start again with step 1 and make
3. What are the advantages and disadvantages of C language? modifications and additions to your source code.
Ans: Advantages of C languages are:
a. It is block structured language with functional flow-control
constructs.
b. It differs from many of the higher level languages by Compilation process of C program
permitting interaction with the computer’s inner workings Source Compile Object Executable RUN
Program Program Link Program
c. It is simple, contained, versatile, more expressive general (Machine
purpose language. code)
d. It has high degree of language mobility Library sub
e. It is fast and efficient Program
f. It is function oriented.All additional tasks including input and
output, graphics, math computations and access to peripheral
devices are placed as library functions. Disadvantages of C language
g. The characters and numeric digits are the fundamental data a. Unlike other language,it is difficult for novice user to learn c
objects of C language. language.
h. It has rich set of operators. b. The register declaration in c language is only an instruction to
i. Dynamic storage location is possible with C the compiler but does not refer to specific machine registers.
j. It permits all data conversion, mixed mode operations c. Memory,input/output,string manipulation etc is done through
k. It easily manipulates with bits, bytes and addresses functions.Hence function calls through proper parameters
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
should be made. 5. How can you define character set in C language? Explain.
Ans: C uses the uppercase letters A to Z, the lowercase letters a to z, the
digit 0 to 9, and some special characters to form basic program
elements (e.g., constants variables, operators, expression) as we
discussed above. The special characters are listed below:
! * + \ ” <
# ) = ; } >
^ ( ] , { ?
& - [ : ‘ /
% _ = = ~ . (blank)<>
C also uses some combinations of these characters such as \t, \n
to represent special conditions such as horizontal tab and new line
respectively. These character combinations are called escape
sequences. Each escape sequence represents a single character,
although it is a combination of two or more characters.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …67 68 … A Complete Refresh Manual of C Programming


6. What is token? List name of token. Explain any two of them. 7. What is a variable? How variables is declared in C language?
Ans: Token is the smallest individual units of C language.The different Explain.
types of tokens are: Ans: Variable
a. Keyword A variable is a named data storage location in your computer's
b. Identifier memory. By using a variable's name in your program, you are, in
c. Constant effect, referring to the data stored there. For many compilers, a C
d. Operator variable name can be up to 31 characters long. (It can actually be
a. Keyword longer than that, but the compiler looks at only the first 31 characters
The reserved words that have standard predefined meaning in of the name.)
C is called Keywords. The keywords can not be used as variable In C, variable names must adhere to the following rules:
name, array name or any others name. They are used by the compiler • The name can contain letters, digits, and the underscore
as an aid to compile the program. They are always written in lower character (_).
case. A complete list follows: • The first character of the name must be a letter. The underscore
is also a legal first character, but its use is not recommended.
auto double int long struct
• Case matters (that is, upper- and lowercase letters). Thus, the
break else register switch
names count and Count refer to two different variables.
case enum return typedef
char extern short union • C keywords can't be used as variable names. A keyword is a
const float signed unsigned word that is part of the C language.
continue for sizeof void • It should not contain any special characters.
default goto static volatile The following list contains some examples of valid and invalid C
do if while variable names:
Variable Namex, Valid
In addition to this list of keywords, your compiler may define a
few more. If it does, they will be listed in the documentation that came Age Valid
year2009,tax_rate,_tax_rate_of_2066,GRADEXII etc.
with your compiler. Year2x5Some
abcof the following
Valid names are invalid identifiers:
b. Identifier 2nd, “y”, ship-no, year 2009 etc.
annual_profit Valid
According to the ANSI-C standard, at least 31 significant
Identifiers refer to the name of user-defined variables, array _2009_tax
characters can Valid butand
be used not advised
will be considered significant by a
and functions.Identifier consists letter and digits in any order but the
savings#account
conforming ANSI-C compiler. the
Invalid: Contains illegalthan
If more character # used, all
31 are
rule is that the first character must be a letter. It can be written in both
Int characters beyond theIs 31st
Invalid: may be ignored by any given
a C keyword
uppercase and lowercase letters but uppercase and lowercase letters
compiler.
are not having the same meaning. For example, NAME, Name and 3winner Invalid: First character is a digit
name refer to different variables. A identifier should not contain a
space.So the space cab be combined with help of underscore.
The underscore character (_) can also be included and is considered to
be single letter.
Some of the following names are valid identifiers:
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

Because C is case-sensitive, the names age, AGE, and Age would be


considered three different variables. C programmers commonly use only
lowercase letters in variable names, although this isn't required. Using all-
uppercase letters is usually reserved for the names of constants .
Declaring Variables
Before you can use a variable in a C program, it must be
declared. A variable declaration tells the compiler the name and type of a
variable and optionally initializes the variable to a specific value. If your
program attempts to use a variable that hasn't been declared, the compiler
generates an error message. A variable declaration has the following form:
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …69 70 … A Complete Refresh Manual of C Programming


Data_type_name variable_name; i. Decimal integer constant: A decimal integer constant
Data_type_name specifies the variable type and must be one of the represented in terms of their escape sequences. The compiler
keywords listed. variable_name is the variable name, which must automatically places a null character at the end of every string
follow the rules mentioned earlier. You can declare multiple variables constant, as the last character within the string. This character
of the same type on one line by separating the variable names with is invisible when the string is displayed.
commas. (c) Integer Constant: An integer constant refers to a sequence of
int rollno,grade, age; /* three integer variables */ digits that will be either positive or negative. There are three
float percent, total; /* two float variables */
types of integers, namely, decimal, octal and hexadecimal.
8. What is a constant? Explain different types of constant with suitable
examples.
Ans: A constant is the fixed values that do not change during the execution
of a program. C supports four types of constants. They are character,
string, integer & floating-point constants. As the name suggests integer
and Floating point constants represent numbers. They are often
referred to collectively as numeric-type constants.
The numeric-type constants must follow the following rules:
(i) Commas and blank spaces cannot be included within the
constant.
(ii) The constant can be preceded by a minus(-) sign if desired.
(iii) The value of a constant cannot exceed specified minimum and
maximum bounds. For each type of constant, these bounds will
vary from one C compiler to another.
Types of constants are:
(a) Character constant: Character constant is a single character
which is enclosed with single quotation marks.
Some of the valid character constants are ‘A’, ‘y’, ‘4’, ‘$’ etc.
Each character constant has its equivalent ASCII value like ‘A’
has 65, ‘y’ has 121, ‘4’ has 52 and so on.
(b) String Constant: String constants consist of any number of
consecutive characters enclosed in double quotation marks
whose maximum length is 255 characters.
Some of the valid string constants are:
“Red’’, “Mary Marry quite contrary”, “2*(J+3)/J”, ‘‘’’ and
”1500” etc.
Sometimes a backslash or a quotation mark must be
included as a part of a string constant. These characters must be
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
can consist of any combination of digits taken from the (c) Logical operators
set 0 through 9, proceeded by an optional - or + sign. (d) Assignment operators
Various examples of decimal integer constants are: (e) Increments and Decrement operators
123, – 345, 0, 5324, +62 etc (f) Conditional operators
ii. Octal integer constant: An octal integer constant can (g) Bitwise operators
consist of any combination of digits taken from the set 0
through 7, with a leading 0. Some examples of octal
integers are:
0, 01, 0456, 05555 etc
iii. Hexadecimal integer constant: A hexadecimal integer
constant must begin with either 0x or 0x. It can then be
followed by any combination of digits taken from the
sets 0 through 9 and A through F (either upper or
lowercase). Note that the letters A through F represent
the numbers 10 through 15 respectively. Some examples
of hexadecimal integers are:
0x2, 0xgf, 0xbc5, 0x etc
d. Floating point constant: A floating point constant is a base-
10 number that contains either a decimal point or an exponent
(or both).
Some of the valid floating point constants are
0. 1. 0.3. 1.555E+8 .121265e18 etc
If an exponent is present, its effect is to shift the location of the
decimal point to the right if the exponent is positive or to the left if the
exponent is negative. Floating point constants have a much greater
range than integer constants. Typically the magnitude of a floating
point constant might range from a minimum value of app. 3.4E-38 to a
maximum of 3.4E+38. These constants are normally represented as
double precision quantities in C. Each floating point constant will
typically occupy 2 words (8 bytes) of memory. Unlike integer
constants floating point constants are approximations.
9. What is an operator? Explain in brief about the different types of
operators available in C languages. [T.U. 2061 Baisakh, Poush]
Ans: An operator is a symbol which helps the user to command the
computer to do a certain mathematical or logical manipulations.
Operators are used in C language program to operate on data and
variables. C has a rich set of operators which can be classified as
(a) Arithmetic operators
(b) Relational operators
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …71 72 … A Complete Refresh Manual of C Programming


(h) Special operators They differ in terms of when the increment or decrement is performed:
(i) Siz eof operators • When used in prefix mode, the increment and decrement
a. Arithmetic operator operators modify their operand before it's used.
It is the basic and common operations in a computer • When used in postfix mode, the increment and decrement
programming language and used to perform mathematical operations. operators modify their operand after it's used.
It is known as binary operator since they take two operands to be An example of prefix mode
evaluated. x = 10;
C's binary mathematical operators. y = x++;
After these statements are executed, x has the value 11, and y
Operator Symbol Example
Addition + x+y has the value 10. The value of x was assigned to y, and then x was
Subtraction - x-y incremented. In contrast, the following statements result in both y and
Multiplication * x*y x having the value 11. x is incremented, and then its value is assigned
Division / x/y to y.
Modulus % x%y An example of postfix mode
(Returns remainder) x = 10;
b. Assignment Operator y = ++x;
The assignment operator is used to assign a value to a variable. d. Relational operator
The form is as follows:
variable = expression; C's relational operators are used to compare expressions,
When executed, expression is evaluated, and the resulting value is asking questions such as, "Is x greater than 100?" or "Is y equal to 0?"
assigned to variable. An expression containing a relational operator evaluates to either true
Some assignment operators are:+=, -=, *=, /=, %=. (1) or false (0).
The symbol = is used as assign operator . C's relational operators.
Examples: Operator Symbol Example
x = y; Equal == x == y
a+=5 is equal to a=a+5; Greater than > x>y
a+=b; is equal to a=a+b; etc. Less than < x<y
In a C assignment statement, the right side can be any expression, and Greater than or equal to >= x >= y
the left side must be a variable name. Less than or equal to <= x <= y
c. Unary operator Not equal != x != y
The unary mathematical operators are so named because they e. Logical operator
take a single operand. Unary operator acts upon single operand to be C's logical operators let you combine two or more relational
increased or decreased by one. expressions into a single expression that evaluates to either true or
C's unary operators. false.
Operator Symbol Action Examples C's logical operators.
Increment ++ Increments the ++x, x++ Operator Symbol Example
operand by one AND && exp1 && exp2
Decrement -- Decrements the --x, x--
operand by one
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
OR || exp1 || exp2 NOT ! !exp1
The statements f. Ternary operator
++x;
--y; The ternary operators are the new important feature of C
are the equivalent of these statements: language which is used to check certain relational expression and
x = x + 1; execute the true statement if the condition is true and display the false
y = y - 1; statement if the condition is false.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …73 74 … A Complete Refresh Manual of C Programming


Syntax: 10. Write about formatted input/output functions available in C with the
[Condition] ? [true statement ]:[false statement]; syntax and examples. [T.U. 2063 Baisakh]
Example: Ans: Formatted output function: printf
a>b?printf("a is greater"):printf("b is greater"); The printf() function is the most commonly used output
g. Comma operator displaying function by which we can display the output in our required
The comma operators use in different ways.They are format.
i. Comma operators can be used in variable declarations. Syntax:
Examples: int a, b, c; printf(“control string”, variable names);
ii. Comma operators can be used in linked list of expression. Every text in between the double quotes(control string) is printed as it
Example:c = (a = 10, b = 20, a + b); is except the format specifier and the escape sequence characters.
iii. Comma operators can be used in for loop. Format specifier:
Example: Character meaning
{ %d for calling integer type of value
int i,j; %s for calling string type of value
printf(“Number and its reverse\n”); %c for calling single character values
for(i=0,j=9;i<9;++i,j--) %f for calling single precision floating point values
printf(“%d\t%d\n”,i,j); %lf for calling double precision floating point values
} %u for calling unsigned integer values
h. Bitwise operator Example:
The bitwise operators are used for having bit level printf(“This is my first program”);
computations of different values. printf(“My name is Charles\nI live in the UK”);
Operators Meaning
& bitwise AND Formatted input function: scanf
| bitwise OR It is the most commonly used function for accepting input from
^ bitwise exclusive OR the users.
>> shift cells right Syntax:
<< shift cells left
scanf("control string”, variables);
~ One's complement
i. Sizeof() operator [T.U. 2068 Mangsir] The control string may contain any of the format specifier as
The sizeof operators return the number of bytes occupied in the per our requirement. The first format specifier is used for the first
memory.The sizeof particular data type may vary from compiler to variable and the rest for the corresponding ones. The scanf() function
compiler. terminates as soon as it encounters the blank space in case of string.
Example: Example:
{ scanf("%d",&a); scanf("%d %s",&age,name);
char ch; 11. What is expression? Explain with examples.
int a; Ans: An expression represents a single data item, such as a number or a
float b; character. The programmers can use operators in the expressions in
C like other programming languages. Expressions can also represent
printf(“Size of ch=%d\n”,sizeof(ch));
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
logical conditions that are either true or false.e.g.
printf(“Size of a=%d\n”,sizeof(a)); x+y;
printf(“Size of b=%d\n”,sizeof(b)); y=z;
} x=y+z;
Result: The first expression involves use of addition operator(+), the
Size of ch=1 second expression involve use of assignment operator(=) and third
Size of ch=2 expression involves use of both addition operator & assignment
Size of ch=4 operator.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …75 76 … A Complete Refresh Manual of C Programming


An expression statement consists of an expression followed by d. Control statement
a semicolon. For example, following two expression statements cause Control statements are used to create special program features,
the value of the expression on the right of the equal sign to be such as logical tests, loops and branches. Examples:
assigned to the variable on the left. i. if(a>b)
x=5; printf(“A is greater”);
x=y+z; else
printf(“B is greater”);
12. What is a statement? Explain different types of statement with
ii. while
examples.
13. What do you know about comments and escape sequences ?
Ans: Any line written in a 'c' editor that normally terminates by a semicolon Ans: Comments
';' is called statement. Examples: Comments are the statements that are used for user aid. Such
int a, b, c, d = 55; statements are ignored by the compiler. A comment is denoted by
float rate ; / * ........................ */ For multi –line statements
char n; etc. Anything written between this is ignored by the compiler
// For single statement
The different types of statements are:
Escape Sequence
a. Null Statements
These are the characters not printed when used but provide various
If you place a semicolon by itself on a line, you create a null
functions. Escape sequences are always started with a backslash '\'.
statement--a statement that doesn't perform any action. This is
Commonly used escape sequences are :
perfectly legal in C. Example: Constant Meaning
; - Null statement '\a' Audible Alert (Bell)
b. Expression statement '\b' Backspace
An expression statement is a constant, variable or combination '\f' Formfeed
of constant and variable. This can also include a function call. An '\n' New Line
expression statement consists of any valid C expression and followed '\r' Carriage Return
'\t' Horizontal tab
by a semicolon.
'\v' Vertical Tab
Examples: '\'' Single Quote
a=b; -Expression statement '\"' Double Quote
c=a+b; - Expression statement {
greater (a, b,c); -Function call printf("Hello, ");
c. Compound Statements printf("sathi!");
}
A compound statement, also called a block, is a group of two
or more C statements within a pair of braces ({ and}). Unlike an In C, a block can be used anywhere a single statement can be
expression statement, a compound statement does not end with a used. Many examples of this appear throughout this book. Note that
semicolon. the enclosing braces can be positioned in different ways.
Example:
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
'\?' Question Mark
'\\' Back Slash
'\0' Null
14. Explain the following terms:
(a) Symbolic constants
(b) Library functions
(c) Header files
Ans: (a) Symbolic constants
A symbolic constant allows a name to appear in place of
numeric constant, character constant or a string. symbolic constants
are usually defined at the beginning of the program. Symbolic
constants may appear later in the program in place of numeric
constants, character constant and so on. At the time of compiling each
occurrence of a symbolic constant get replaced by its corresponding
character sequence. Examples :
# define AND &&
# define Pi 3.1412
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …77 78 … A Complete Refresh Manual of C Programming


# define True 1 clrscr() function to clear the output screen. Similarly the pow()
# define friend "Susan" etc. function, to calculate the power of different numbers. The library
Using symbolic constant in C program simply by accessing these special files. This is accomplished with the
#include <stdio.h> preprocessor statement.
#include <conio.h> Examples :
#define pi 3.14 sqrt ( ), to lower ( ), to upper, abs ( ) etc.
void main ( )
The library functions like printf(), getch(), clrscr(), pow() etc. are
{
int r;
primarily coded by the manufacturer and stored in the C library. All such
flaot a; functions are given specific task. For example the printf() function is used
printf ("\nEnter the value of radius ="); to display different text on the monitor while the
scanf ("%d", &r);
a = 3.14 * r * r;
printf ("Area of a circle = %.2f", a);
getch ( );
}
Result:
Enter the value of radius=2
Area of a circle =12.56
(b) Library functions
Many functions of C is carried out by library functions. These
functions perform file access, mathematical computation, graphics,
memory management, data conversion etc. A typical set of library
functions will include a large number of functions that are common to
most C compilers.
A library function is accessed simply by writing the function
name, followed by a list of arguments that represent information being
passed to the function. The arguments must be enclosed in parentheses
and separated by commas. The arguments can be constants, variable
names or more complex expressions. The parentheses must be present,
even if there are no arguments, A function that returns a data item can
appear anywhere within an expression in place of a constant or an
identifier. A function that carries out operations on data items but does
not return anything can be accessed simply by writing the function
name, since this type of function reference constitutes an expression
statement. In order to use a library function it may be necessary to
include certain specific information within the main portion of the
program. This information is generally stored in special files supplied
with the compiler. Thus, the required information can be obtained
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
functions are also called built in function as they are built in functions like toupper(),tolower() etc.
with the • The use of angle brackets <> informs the compiler to search
C compiler, and the user mustn’t bother to code them. the compiler’s include directories for the specified file. The use
(c) Header files of the double quotes "" around the filename informs the
• Header files contain definitions of functions and compiler to start the search in the current directory for the
variables which can be incorporated into any C specified file.
program by using the pre-processor #include Some commonly used header files are :
statement.Standard header files are provided with each stdio.h, conio.h, process.h, math.h, ctype.h, string.h, stdlib.h etc.
compiler, and cover a range of areas:string handling, 15. List any six commonly found programming errors in a C program.
mathematics, data conversion, printing and reading of Ans: Commonly found six errors are:
variables, etc. 1. Missing or misplaced; or , missing return type for a procedure,
• To use any of the standard functions, the appropriate missing or duplicate variable declaration.
header file should be included.This is done at the 2. Type mismatch between actual and formal parameters, type
beginning of the C source file. For example, to use the mismatch on assignment.
function printf() in a program, the line #include
<stdio.h> should be at the beginning of the source
file, because the declaration for printf() is found in the
file stdio.h. All header files have the extension .h
stdio.h : It contains the standard input output
functions like
printf(), scanf(), gets(),
puts() etc.
conio.h: It contains some of the functions like getch(),
clrscr()
e
t
c
.
math.h : It contains the mathematical functions like
pow(), sqrt(),
abs()
,fmod()
etc.
String.h: It contains the string manipulating functions
like strlen(),
strcpy() ,strcmp( ),
strrev() etc.
ctype.h : It contains some validating function like
isdigit(),isalnum(),isalpha() and some vale converting
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …79 (integer, float, character etc.) and need to store the values being used
in the program. C language is rich of data types. A C programmer has
3. Forgetting the precedence of operators, declaration of function
to employ proper data type as per his requirement.
parameters.
4. Output errors means the program runs but produces an Data types are used to declare the variable name in C language.
incorrect result. This indicates an error in the meaning of the C supports different types of data, each of which may be represented
program. differently within the computer’s memory.
5. Exceptions that include division by zero, null pointer and out
of memory.
6. Non-termination means the program does not terminate as
expected, but continues running "forever."
16. What is user-defined data type name? Explain with examples.
Ans: C language allows user to define their own data types which are based
on existing data types.The general format of declaring data type is
typedef existing_data_type user_defined_data_type;
where typedef is keyword.
existing_data_type is C data type.
user_defined_data_type is new data type name which user want
to define.
Example:
#include <stdio.h>
#include <conio.h>
void main ( )
{
typedef int integer;
integer a,b,c;
printf(“Enter value of a and b:”);
scanf(“5d%d”,&a,&b);
c=a+b;
pritf(“Sum=%d”,c);
getch ( );
}
17. What are different data types used in C ? Explain.
[Pokhara University 2010, 2011]
Or, What are data types available in C? Write about their size in
memory, their range and the digit of precision for each data type.
[T.U. 2062 Baisakh]
Or, What are data types available in C? Write about their size in
memory, their range and the digit of precision for each data type.
[T.U. 2062 Baisakh]
Ans: A program usually contains different types of data types
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

80 … A Complete Refresh Manual of C Programming with longer precision. To extend the precision further we can use long
double which consumes 80 bits of memory space.
C language data types can be broadly classified as
A. Primary data type Void Type
B. Derived data type Using void data type, we can specify the type of a function. It
C. User-defined data type is a good practice to avoid functions that does not return any values to
A. Primary data type the calling function.
All C Compilers accept the following fundamental data types
Data type Data sub_ type Bytes Format Range
Character Signed character 1 %c – 128 to 127

Unsigned character 1 %c 0 to 255


Numeric Short signed int 2 %d – 32768 to
32767
Short Unsigned int 2 %d 0 to 65535
Long signed int 4 %ld –2147483648 to
2147483647
Long unsigned int 4 % ld 0 to 4294967295
Float 4 %f 3.4E–38 to
3.4E+38
Double 8 % lf 1.7E–308 to
1.7E+308
Long double 10 %lf 3.4E-4932 to
3.4E + 4932
Integer Type
Integers are whole numbers with a machine dependent range of
values. A good programming language as to support the programmer
by giving a control on a range of numbers and storage space. C has 3
classes of integer storage namely short int, int and long int. All of
these data types have signed and unsigned forms. A short int requires
half the space than normal integer values. Unsigned numbers are
always positive and consume all the bits for the magnitude of the
number. The long and unsigned integers are used to declare a longer
range of values.
Floating Point Type
Floating point number represents a real number with 6 digits
precision. Floating point numbers are denoted by the keyword float.
When the accuracy of the floating point number is insufficient, we can
use the double to define the number. The double is same as float but
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …81 82 … A Complete Refresh Manual of C Programming


Character Type 18. What is an unsigned integer constant? What is the significance of
A single character can be defined as a defined as a character Example:
type of data. Characters are usually stored in 8 bits of internal storage. enum day {Monday, Tuesday, …. Sunday};
The qualifier signed or unsigned can be explicitly applied to char. enum day week_st, week end;
While unsigned characters have values between 0 and 255, signed week_st = Monday;
characters have values from –128 to 127. week_end = Friday; if(wk_st
B. Derived data type == Tuesday) week_en =
Functions,arrays and pointers are derived data type. Saturday
C. User defined type declaration [T.U.2060 Shrawan]
The user defined data types are:
(a) Structure
(b) Union
(c) Enumeration
In C language a user can define an identifier that represents an
existing data type. The user defined datatype identifier can later be
used to declare variables. The general syntax is typedef type identifier;
here type represents existing data type and ‘identifier’ refers to the
row’ name given to the data type.
Example:
typedef int salary;
typedef float average;
Here salary symbolizes int and average symbolizes float. They can be
later used to declare variables as follows:
Units dept1, dept2;
Average section1, section2;
Therefore dept1 and dept2 are indirectly declared as integer
datatype and section1 and section2 are indirectly float data type.
The second type of user defined datatype is enumerated data
type which is defined as follows.
Enum identifier {value1, value2 …. Value n};
The identifier is a user defined enumerated datatype which can
be used to declare variables that have one of the values enclosed
within the braces. After the definition we can declare variables to be
of this ‘new’ type as below.
enum identifier V1, V2, V3, ……… Vn;
The enumerated variables V1, V2, ….. Vn can have only one of the
values value1, value2 ….. value n
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
declaring a constant as from the keyboard and store in the given variable.
unsigned? It reads a whole line of input into a string until a newline or
Ans: An integer constant is any number in the range -32768 to EOF is encountered. It is critical to ensure that the string is large
+32767, because an integer constant always occupies two bytes enough to hold any expected input lines.
in memory and When all input is finished, NULL as defined in stdio.h is
in two bytes we cannot store a number bigger than +32767 or returned.
smaller Syntax:
than -32768. Out of the two bytes to store an integer, the gets(variable name);
highest bit is used to store the sign of the integer. This bit is 1 if Example:
the number is negative and 0 if number is positive. Unsigned gets(sentence); gets(message);
integer constant is an integer constant which has the (ii) puts
permissible range from 0 to 65536. Thus significance of The puts function can be used to display a large text in the
declaring a constant as unsigned almost doubles the size of the monitor. The puts function is used only for the character data types
largest possible value. This happens because on declaring a and the strings.
constant as unsigned, the sixteenth bit is free and is not used
to store the sign of the constant.
19. Why is C standard library needed? Explain.
Ans: C would have been a tough programming language in absence
of the
standard library. The standard library in C includes header files
and standard functions in these files. Header files are collection
of macros, types, functions and constants. Any program that
needs those functions has to include these header files. For
example, the standard library functions, included in “stdlib.h”
header file, are used for number conversions, storage
allocation and other functions on the same line. These
functions are called utility functions. C does not have any built-
in input/output statements as part of its syntax. All I/O
operations are carried out through function calls such as printf
and scanf. There are many functions that have become standard
for I/O operations in C, collectively known as standard I/O
library “stdio.h”. Because of this standard input-output header
file, standard I/O functions can be used on many machines
without any change.
20. What are the functions of string input /output ?Explain.
Ans: The string input/output functions are:
(i)
gets
This function is used to read a string of words(text or
sentence)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …83 84 … A Complete Refresh Manual of C Programming


Syntax: ) #include directory
puts(variable); In C, #include is a preprocessor directive that tells the C
OR preprocessor to look for a file and place the file in the location where
puts("string");
#include indicates. The preprocessor includes the header file such as
Example:
Puts(a); Puts("Enter the number:"); etc. • All programming statements must lie within curly braces.
21. Explain the structure of C program. • Comment statements doesn’t compile by the computer.
Ans: C program can be written using combinations of three control ) Comments /*……..*/
structures i.e. sequential, selection and repetitive. All C programs are In C, /* is called opening comment mark and */ is closing
made up of one or more function, each performing a particulars task. comment mark. The C compiler ignores everything between the
Every program has a special function named main(). It is special opening comment mark and closing comment mark. The comment is
because the execution of any program starts from main functions. used for program documentation.
General form of C program:
Comments
Preprocessor directives
Global variables
main() function
{
local variables
statements
--------------
--------------
}
function1() other functions
{
local variables
statements
--------------
--------------
}

/*Example number 1*/


#include<stdio.h>
main()
{
printf (“This is first program \n ”);

return 0;
}
Notes:
• Every program statements must end with a semi colon (;).
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
stdio.h, conio.h, string.h etc. program. Under normal circumstances, program execution starts at the
) Header file first statement in main() and terminates at the last statement in main().
The file that are included by the #include directive such as
stdio.h is called header file. The header files are always placed at the
start of a C program.
) Angular <> braces
In C, the angular bracket asks the C preprocessor to look for a
header file in directory other than the current one. If we want to let the
C preprocessor look into current directory first for header file before it
starts to work, we can use double quotes to surround the name of the
header file. Normally, the header file are saved in a sub directory
called include.
) Main function
Every C program must have one and only one main functions.
The main function can be put anywhere but the execution of a
program starts with main function. The main function starts and end
with curly braces {}
) Printf functions and new line character
The printf function is used to print the character string. The
new line character which is usually sufficient at the end of the
message, tells the system to move the cursor to the beginning of next
line.
) Return statements
All function in C can return value. The main function itself
returns an integer value. So, return 0 indicates that 0 is returned from
main function and the program is terminated normally. We can return
values other than 0 to tell the system that there is an error.
Identifiers and Keywords
An identifiers can be defined as the name of the variable,
function, arrays, structures, constants etc, are created by the
programmer. They are the fundamental requirements of any
programming language.
22. For what purpose main() function and #include directive are used.
Ans: The main() Function
The only main component that is required in every C program
is the main() function.The main() function consists of the name main
followed by a pair of empty parenthesis (()) and a pair of braces ({}).
Within the braces are statements that make up the main body of the
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …85 86 … A Complete Refresh Manual of C Programming


The #include directive 2.1 C Programmings – 1 [Sequence]
The #include directive instructs the C compiler to add the
contents of an include file into your program during compilation. An 1. Write a program to calculate area and circumference of a circle
include file is a separate disk file that contains information needed by where radius of a circle is input and define by user as constant.
your program or the compiler. Several of these files (sometimes called Ans: #include<stdio.h>
header files) are supplied with your compiler. You never need to #include<conio.h>
modify the information in these files; that's why they're kept separate #define pi 3.14
from your source code. Include files should all have an .h extension void main()
(for example, stdio.h). {
You use the #include directive to instruct the compiler to add a int r;
specific include file to your program during compilation. The #include float a,c;
directive in this sample program means "Add the contents of the file printf("Enter value of radius=");
stdio.h." Most C programs require one or more include files. scanf("%d",&r);
23. What are pre-processor directives? List three types of them. What is
the difference between the following directives: #include <filename> a=pi*r*r;
and #include “filename”? c=2*pi*r;
Ans: These are the commands given to a program known as preprocessor
printf("\nArea=%.2f",a);
that processes the source code before it passes through the compiler.
printf("\nCircumsatances=%.2f",c);
Each of these preprocessor directives begins with a # symbol. These getch();
can be placed anywhere in the program but usually placed before main }
( ) or at the beginning of the program. Before the source code passes Result:
through the compiler, it is examined by the preprocessor for any Enter value of radius=2
directives. If there are any, appropriate action is taken and the source
program is handed over to compiler. These directives can be divided Area=12.56
into following three categories: Circumferences=12.56
1. Macro substitution directives 2. Write a program that read principle, time and rate to calculate
2. File inclusion directives. simple interest and total amount.
3. Compiler control directives. Ans: #include<stdio.h>
#include “filename”: The search for the file is made first in the #include<conio.h>
current directory and then in the standard directories as mentioned in void main()
the include search path. {
int p,t;
#include <filename>: This command would look for the file in the
standard list of directories. float r,si,ta;
printf("Enter Principle=");
Both of these directives cause the entire contents of filename to be scanf("%d",&p);
inserted into the source code at that point in the program. printf("Enter time=");
scanf("%d",&t);
printf("Enter rate=");
scanf("%f",&r);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

si=(p*t*r)/100;
ta=si+p;

printf("\nSimple Interest=%.3f",si);
printf("\nTotal Amount=%.3f",ta);
getch();
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …87 88 … A Complete Refresh Manual of C Programming


Result: 5. Write a program to enter distance between two cities in km and
Enter principle=5000 convert it into meter, centimeter, inch and ft.[inch=cm/2.54,
Enter time = 5 m=km*1000, ft=inch/12, cm=m*100]
Enter rate= 6
Ans: #include<stdio.h>
#include<conio.h>
Simple Interest=1500.000
void main()
Total Amount=6500.000
{
3. Write a program to convert temperature in Fahrenheit (F) into int km,m,c;
centigrade (c). [F = 1.8 c + 32] float c,i,f;
Ans: #include<stdio.h> printf("Enter value of distance in
#include<conio.h> Kilometer=");
void main ( ) scanf("%d",&km);
{
int f; }
float c;
printf ("\n Enter temp in fahrenheit ="); Result:
scanf ("%d", & f); Enter cost of pen in paisa=205

c = (f – 32)/1.8; Rupees=2
Paisa=5
printf ("Result = %.2f", c);
getch ( );
}
Result:
Enter temp in fahereinheit=200

Result=93.33
4. Write a program asking cost of pen in paisa. Convert it into the
nearest rupees and paisa.
Ans: #include <stdio.h>
#include <conio.h>
void main ( )
{
int paisa, rup, paisa1;
printf ("Enter cost of pen in paisa =");
scanf ("%d", & paisa);

rup = paisa/100;
paisa1 = paisa%100;

printf ("\nRupees = %d", rup);


printf ("Paisa = %d", paisa1);
getch ( );
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
m=km*1000;
c=m*100;
i=c/2.54;
f=i/12;

printf("\nMeter=%d",m);
printf("\nCentemeter=%d",c);
printf("\nInch=%.3f",i);
printf("\nFeet=%.3f",f);
getch();
}

Result:
Enter value of distance in kilometer=200

Meter=200000
Centimeter=20000000
Inch=3610108.250
Feet=300842.344
6. Write a program to enter 4-digit number and find sum of the first
and last digit of the number. [e.g. If n = 4567, then sum = 4 + 7]
Ans: #include <stdio.h>
#include <conio.h>
void main ( )
{
int n, r, sum = 0;
printf ("Enter 4-digit number =");
scanf ("%d", &n);

r = n/10000;
sum = sum + r;
r = n%10;
sum = sum + r;

printf ("sum of first and last digit =


%d",sum);
getch ( );
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …89 90 … A Complete Refresh Manual of C Programming


Result:
Enter 4-digit number=1234 Result:
sum of first and last digit=5
Total=330
7. Write a program to supply length and breadth of a rectangle. Find Percentage=66.00
out area and perimeter.
Ans: #include <stdio.h> 9. Write a program to read any two numbers through the keyboard and
#include <conio.h> to perform simple arithmetic operations (i.e. addition, subtraction,
void main ( ) multiplication & division) and display the results using scanf and
{ printf functions.
int l, b, a, p;
printf ("Enter breadth & length ="); Ans: #include<stdio.h>
scanf ("%d%d", &b, &l); #include<math.h>
void main( )
a = l*b; {
p = 2*(l + b); int a, b, sum, sub, mul;
float div;
printf ("Area of a rectangle = %d\n", a); printf ("Enter any two numbers =");
printf ("Perimeter of a rectangle = scanf ("%d %d", &a, &b);
%d\n", p);
getch ( ); sum = a + b;
} sub = a – b;
mul = a*b;
Result: div = a/b;
Enter breadth & length=4 6
Area of a rectangle=24 printf ("\nAddition =%d", sum);
Perimeter of a rectangle=20 printf ("\nSubtraction =%d", sub);
8. Write a program to find total and percentage of a student whose printf ("\nMultiplication =%d", mul);
marks are given below : printf ("Division = %f", div);
getch ( );
Subjects Marks }
English 65
Result:
Nepali 55 Enter any two numbers=5 2
Computer Science 70
Math 80 Addition=7
Account 60 Subtraction=3
Multiplication=10
Ans: #include<stdio.h>
#include<conio.h> Division=3.500000
void main ( ) 10. Write a program to enter 4-digit number and find sum of them.
{ (i.e. 1234 = 1 + 2 + 3 + 4 = 10)
int eng=65, nep=55, math=80, acc=60,
cscience=70;
Ans: #include<stdio.h>
int total; #include<conio.h>
void main( )
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a float per; k e r- s o ft w a
{
int num, r, n, sum = 0;
total = eng + nep + math + acc + cscience;
printf ("Enter 4-digit number =");
per = total/5;
scanf ("%d", & num);
printf ("Total = %d\n", total);
r = num % 10;
printf ("Percentage = %.2f", per);
getch ( ); n = num/10;
} sum = sum + r;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …91 92 … A Complete Refresh Manual of C Programming


r = n% 10; 12. Basic salary of Kiran Yadav is input through the keyboard. His
n = n/10; medical allowance is 10% of basic salary, house rent allowance is
sum = sum + r; 8% of basic salary and provident fund is 10% of basic salray. Write
r = n% 10;
a program to find his net salary.
n = n/10; Ans: #include<stdio.h>
sum = sum + r; #include<conio.h>
void main ( )
r = n% 10; {
sum = sum + r; float bs,ma,hra,pf,netsal;
printf(“Enter basic salary of employee:”);
printf ("sum of 4-digit = %d", sum); scanf(“%f”,&bs);
getch ( ); ma=bs*10/100;
} hra=bs*8/100;
pf=bs*10/100;
Result: netsal=bs+ma+hra-pf;
Enter 4-digit number=2354 printf(“\nBasic salaray=%.2f”,bs);
printf(“\nMediacl allowance=%.2f”,ma);
Sum of 4-digit=14 printf(“\nHouse rent allowance=%.2f”,hra);
11. Write a program to solve the quadratic equation ax2 + bx + c = 0, printf(“\nProvident fund=%.2f”,pf);
printf(“\nNet salaray=%.2f”,netsal);
– b ± b2 – 4ac getch();
where x = . Printf ("Value of y = %.2f\n", y); getch
2a
( );
Ans: #include<stdio.h>
}
#include<conio.h>
Result:
#include<math.h> Enter the value of a, b & c =2 3 1
void main ( ) Value of X = -2.00
Value of Y = -4.00
{
int a, b, c;
float x, y;
printf ("Enter the value of a, b & c =");
scanf ("%d %d %d", &a, &b, &c);

x = pow ((– b + b*b – 4*a*c),0.5)/2*a;


y = pow ((–b–b*b–4*a*c),0.5)/2*a;

Printf ("Value of X = %.2f\n", x);


F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
printf(“\nNew content of x: %d”,x);
} printf(“\nNew content of y: %d”,y);
Result: getch();
Enter basic salary of employee:5000 }

Basic salaray= 5000.00


Mediacl allowance= 500.00
House rent allowance=400.00
Provident fund=500.00
Net salaray=6400.00
13. Write a program to interchange the contents of x and
y after entering the value of x and y.
Ans:
#include<stdio.h
>
#include<conio.h>
void main ( )
{
int
x,y
,z;
printf(“Enter the value of
x:”);
scanf(“%
d”,&x);
printf(“Enter value of
y:”);
scanf(“%
d”,&y);

z
=
x
;

x
=
y
;

y
=
z
;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …93 94 … A Complete Refresh Manual of C Programming


Result:
Enter the value of x:3 si=p*(pow((1+r)/100,t)-1);
Enter the value of x:2
printf(“The compound interest is %.2f”,si);
New content is 2
New content is 3 getch();
}
14. Write a program to find area of area of a triangle, if the length of Result:
the sides of a triangle are denoted by a,b,c. Then area of triangle is Enter the value of principal:2000
given by Enter the value of time:5
Area = S(S – a) (S – b) (S – c) Enter the value of rate:10
Where S=(a+b+c)/2
The compound interest is 3220.02
Ans: #include<stdio.h>
#include<conio.h> 16. Write a program to find area of a triangle after reading the value of
#include<math.h> base and height.
void main ( ) Ans: #include<stdio.h>
{ #include<conio.h>
int a,b,c; void main ( )
float s,area; {
float base,height,area;
printf(“Enter the value of a,b and c:”);
printf(“Enter the value of base:”);
scanf(“%d%d%d”,&a,&b,&c);
scanf(“%f”,&base);
printf(“Enter value of height:”);
s=(a+b+c)/2;
scanf(“%f”,&height);
area=sqrt(s*(s-a)*(s-b)*(s-c));
area=0.5*base*height;
printf(“Area of triangle is %.2f”,area);
getch();
printf(“Area of a triangle:%.2f”,area);
}
getch();
Result: }
Enter the value of a,b and c: 5 4 5
Result:
Area of triangle is 9.17 Enter the value of base:2
Enter value of height:3

15. Write a program to find compound interest. The value principal, Area of a triangle:3.00
time and interest rate is given by user. 17. Write a program to read the value of radius of a sphere. Find
Ans: #include<stdio.h> volume and area of it. Also define value of as constant.
#include<conio.h> Ans: #include<stdio.h>
#include<math.h> #include<conio.h>
void main ( ) float p,t,r,si;
{ printf(“\nEnter the value of principal:”):;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
scanf(“%f”,&p); #define pi 3.14
void main ( )
{
int r;
float v,a;
printf(“\nEnter the value of time:”); printf(“Enter the value of radius:”);
scanf(“%f”,&t); scanf(“%d”,&r);
printf(“\nEnter the value of rate:”);
scanf(“%f”,&r); v=4/3*pi*r*r*r;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …95 96 … A Complete Refresh Manual of C Programming


a=4*pi*r*r;
2.2 Branching
printf(“\nVolume of a sphere=%.2f”,v); 1. What is branching? Explain various types of branching statement
printf(“\nArea of sphere=%.2f”,a); with suitable examples.
getch(); Ans: The C language programs presented follows a sequential form of
}
execution of statements. Many times it is required to alter the flow of
Result: the sequence of instructions. C language provides statements that can
Enter the value of radius:2
alter the flow of a sequence of instructions. These statements are called
nVolume of a sphere=25.12 control statements. These statements help to jump from one part of the
Area of sphere=50.24 program to another. The control transfer may be conditional or
18. Write conditional operators to evaluate the following function unconditional.
y = 2.4x + 3, for x <= 2 The various branching statements are :
y = 3x –5, for x > 2 (a) One way branching.(i.e. if statement)
Ans: #include<stdio.h> (b) Two way branching(if ............else statement)
#include<conio.h> (c) Multi way branching(i.e.if ... else if .... else)
void main()
Explanations of various types of branching statements are:
{
int x; (a) One way branching (i.e. if statement) [T.U. 2062 Baisakh]
float y; It is the type of statement which is used to evaluate only one
clrscr(); statement at a time.‘if’ statement will execute if the given expression
printf("enter the values of x\n"); is true. If the user wants to add more than one statement then there
scanf("%d",&x); must be pair of curly braces after ‘if’.
y=((x<=2)?(2.4*x+3):(y=3*x+5));
Syntax:
printf("y=%f",y);
if(expression) True False
getch();
{ If condition ?
}
statement1;
Statements
…………..
}
If expression is true,
statement1 is executed. If
expression is not true, statement1 is ignored.
Let us consider an example of if statement.
#include <stdio.h>
#includ<conio.h>
void main()
{
char grade;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
printf(“Enter a character value for grade:”);
scanf(“%c”, grade);
if(grade = = ‘A’)
printf(“The grade is excellent \n”);
printf(“Thanks for using this program\n”);
getch():
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …97 98 … A Complete Refresh Manual of C Programming


Result: statement2;
Enter a character value for grade: A …………
}
The grade is excellent else
Thanks for using this program {
Statement3;
(b) Two way branching(if ............else statement)
…………
The two way branching statement is used for two option, i.e. }
True or False. If the statement is true, the block of true part is If the first expression, expression1, is true, statement1 is
executed, otherwise, the block of false part is executed. executed before the program continues with the next_statement. If the
Syntax: first expression is not true, the second expression, expression2, is
if(expression) checked. If the first expression is not true, and the second is true,
{ statement2 is executed. If both expressions are false, statement3 is
statement1; yes No executed. Only one of the three statements is executed at a time.
Conditio n?
………… Let us consider an example of if ..else if..else statement
}
State me nt 1 State me nt -2 #include <stdio.h>
else
#include<conio.h>
{
void main()
statement2;
{
…………
char grade;
}
If expression is true,then statement1 is executed; otherwise, Syntax:
statement2 is executed. if(expression1)
{
Let us consider an example of if ..else statement. statement1;
#include <stdio.h> …………
#include<conio.h> }
else if(expression2)
void main() {
{
char grade;
printf(“Enter a character value for grade:”);
scanf(“%c”, grade);
if(grade= =’A’)
printf(“grade is excellent \n”);
else
printf(“grade is other than excellent\n");
getch();
}
(c) Multi way branching(i.e.if ... else if .... else)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
printf(“Enter a character value for grade:”);
scanf(“%c”, grade);
if(grade= =’A’)
printf(“grade is excellent \n”);
else if(grade= =’B’)
printf(“grade is very good\n");
else
printf(“Good\n”);
getch();
}
switch…case: It is alternate statement of if …. else /if ….else if …
else statement
It allows us to select a choice out of many available choices.
The switch statement causes a particular group of statements to be
chosen from several available groups. The selection is based upon the
current value of an expression that is included within the switch
statement.
Syntax :
switch(expression) {
case a:
DoSomething();
break;
case b:
DoSomethingElse();
break;
……….
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …99 100 … A Complete Refresh Manual of C Programming


………. 2. Differentiate between local and global variables.
default: [T.U. 2068 Mangsir]
Handle GeneralCase();
break; Ans: Differentiation between local and global variables :
} Global variables
Other non-C-like languages have similar constructs, often with the It is declared outside of all functions or before main.These can
keywords "case" or "select", often without the need for an explicit be used in all the functions in the program.It need not be declared in
"break". other functions.A global variable is also known as an external
Example : variable.
{ Local variables
int a ; It is declared inside a function where it is to be used.These are
printf(“Enter number of day:”): not known to other function in the program.These variables are visible
and meaningful inside the functions in which they are declared.
scanf(“%d”,&a);
For example:
switch (a)
#include<stdio.h>
{ int m; //Global variable
case 1 : void main( )
printf ("Sunday"); { int i; //local variable
break; …..
case 2 : …..
Fun1();
printf ("Monday");
}
break;
Fun1( )
case 3: { int j; //local variable
printf(“Tuesday”); ….
break; …..
case 4: }
printf(“Wednesday”); Here m is a global variable , i is local variable local to main( )
break; and j is local variable local to Fun1( ).
case 5: 3. Write down syntax ,working and use of switch statement in “C”.
printf(“Thursday”); break;
break; default:
printf ("not the value");
case 6:
printf(“Friday”); exit(0);
}
break;
case 7:
printf(“Saturday”):
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
[T.U. 2057 Chaitra] unconditionally from one point to another in the program.The goto
Or, Describe how switch statement work. What are keyword is followed by a label, which is basically some identifier
the restrictions on case labels? placed elsewhere in the program where the control is to be transferred.
[T.U. 2058 Chaitra] During running of a program, the statement like “goto label1;”
Ans: Question no.(1), d. cause the flow of control to the statement immediately following the
4. Write the syntax and an example of "goto" label “label1”. We can have a forward jump or a backward jump.
statement. syntax > goto /identifier
Ans: C support goto statement to branch
getch(); Example : A program for finding odd or even numbers by using
} GOTO statement.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …101 102 … A Complete Refresh Manual of C Programming


# include <stdio.h> ch = getchar ( );
# include <conio.h> printf ("Output");
void main ( ) putchar (ch);
{ ghetch();
int n; }
char ch; 6. Write short notes on "Format Specifier".
x : clrscr ( ); Ans: Format specifiers are characters starting with % sign and followed
printf("Enter any number ="); with a character. It identifies the data type that is being processed. It is
scanf("%d", & n); also known as "conversion specifier".
if (n% 2 = = 0) Some of character specifications used with format specifiers are:
printf ("Even number"); Character Meaning
else
% First character
printf ("Odd number");
printf ("Do you want to continue (Y/N) ? = "); – (minus sign) Used for left justification.
scanf ("%c", ch); w Used for specifying width of field.
if (ch = = ‘Y’|| ch= =’y’) . (dot) Used for specifying decimal part.
goto x; p Used for specifying precision.
getch ( ); List of format specifiers symbol.
} Data type Format specifier symbol used
5. Describe the getchar and putchar function with limitation. Integer %d
Or, Explain the functions of single input/output . Unsigned integer %u
Ans: Getchar:
Octal %o
It returns only one character at a time from a standard input
Hexadecimal %x
device. The getchar accept all type of characters even space, tab,
blank, return. This function has the limitation, i.e. this isn't used for Float %f
numeric operations and also not used for looping. Float (scientific or exponential) %e
Example : character %c
# include<stdio.h> string %s
#include<conio.h> Example :
void main ( )
main ( )
{
char c; { int r;
c = getchar ( ); float a;
printf("\n input character = %c", c); r = 2;
getch(); a = 12.562, 01547;
} printf ("%d", r); // prints 2 at initial
Putchar position of screen
It transmits a single character to a standard output device. This and not displaying for loops.
function accepts all types of characters even space, tab, blank. This E
function has also the limitation, that isn't used for numeric operation x
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
ample : printf ("%10d", r); // prints 2 leaving 10
spaces. Right justified.
printf ("%–d", r); // prints 2 left justified
printf ("%f",a); // prints 12.56201547
printf ("%10.2f",a); // prints 12.56 leaving 10
spaces
# include <stdio.h>
printf ("%e",a); // prints1.256201c + 01
#include<conio.h>
void main ( ) printf ("%15.2e",a); //prints 1.25e + 01
{ leaving 15 spaces. Right
char ch; justified.
printf ("Enter any letter :-"); }
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …103 104 … A Complete Refresh Manual of C Programming


7. Differentiate between if..else and switch..case statement. 2.3 C Programmings – 2 (Selection)
Ans: Differences between if…else and switch…case statement:
If ..else statement Switch…case
a. It checks whether the a. It is multi-way decision 1. Write a program that accepts an integer and checks whether it is
condition is true or false statement divisible by 3 and 5 or not.
b. It contains the condition b. It contains the variable Ans: #include<stdio.h>
which will evaluates to true whose value is to be #include<conio.h>
or false checked void main()
c. It supports all types of c. It supports checking only
conditions integer and character {
values int a;
d. Syntax: d. Syntax: printf("Enter an integer=");
if(condition) switch(variable) scanf("%d",&a);
{ {
//statements case value1:
} break; if(a%3==0 && a%5==0)
else case value2: printf ("Divisible by 3 and 5.");
{ break; else
//statements default: printf("Not divisible by 3 and 5");
} }
e. Example: e. Example:
#include<stdio.h> getch();
{
#include<conio.h> int a ; }
void main() printf(“Enter day
{ number :”):
Result:
int a; scanf(“%d”,&a); Enter an integer=15
printf("Enter an switch (a) {
integer="); case 1 : Divisible by 3 and 5.
scanf("%d",&a); printf ("Sunday");
if(a%3==0 && a%5==0) break; 2. Write a program to enter any number and check whether the entered
printf ("Divisible by 3 case 2 : number is odd or even.
and 5."); printf ("Monday");
else break; Ans: # include<stdio.h>
printf("Not divisible case 3: # include<conio.h>
by 3 and 5"); printf(“Tuesday”); void main( )
getch(); break;
} case 4: {
printf(“Wednesday”); int n;
break; printf ("Enter any number = ");
case 5: scanf ("%d", &n);
printf(“Thursday”);
break;
case 6: if (n% 2 = = 0)
printf(“Friday”); printf ("The entered number is even");
break;
case 7: else
printf(“Saturday”): printf ("The entered number is odd");
break;
default:
printf ("not the
value");
exit(0);
}
getch();
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

getch ( );
}

Result:
Enter ay number=4

The entered number is even.


F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …105 106 … A Complete Refresh Manual of C Programming


3. Write a C program to read any number and check whether the Result:
entered number is divisible by 4 but not by 11 or not Enter any character= e
Ans: #include<stdio.h> vowel
#include<conio.h>
5. Write a program to enter any year and check whether the entered
void main() year is leap or not. [T.U.2061 Baisakh]
{ Ans: #include<stdio.h>
int a; #include<conio.h>
printf("Enter an integer="); void main ( )
{
scanf("%d",&a); int year;
printf ("Enter year = ");
if(a%4==0 && a%11!=0) scanf ("%d", & year);
printf ("Divisible by 5 but not by
if (year% 400 = = 0 || year % 100! = 0 &&
11."); year% 4 = = 0)
else printf ("Leap year");
printf("Not"); else
printf ("Not a leap year =");

getch(); getch ( );
} }
Result:
Result: Enter year= 2000
Enter an integer=12
Leap year.
Divisible by 4 but not by 11. 6. Write a computer program that asks the user to type two integer
values from the terminal. Test these two values to determine if the
4. Write a program to enter any character and check whether the first is evenly divisible by the second and display appropriate
entered character is vowel or consonant. message at the terminal. [T.U.2057 Chaitra]
Ans: # include <stdio.h> Ans: #include<stdio.h>
# include <conio.h> #include<conio.h>
void main ( ) void main()
{
{ int first,second;
char ch; printf("Enter any two numbers:");
printf ("Enter any character ="); = 'E' || ch = = 'O' || ch = = 'I' ||
scanf ("%c", ch); ch = =
'U')
printf ("vowel");
if (ch = = 'a' || ch = = 'e' || ch = = 'i' ||
ch = = '0' || ch = = 'u' || ch = = 'A' || ch = else
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
} scanf("%d%d",&first,&second);
printf ("consonant");
if(first%second==0)
getch ( ); printf ("First is divisible by second
number");
else
printf("Not divisible");

getch();

Result:
Enter any two numbers:20 3
} Not divisible
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …107 108 … A Complete Refresh Manual of C Programming


7. Write a program to test whether the triangle is right angled or not, if 9. A salesman gets commission on the basis of his daily sales and the
three sides of triangle are given. rate of commission is as follows :
Ans: #include<stdio.h> Total sales made Commission rate
#include<conio.h> Below 5000 1.5%
void main ( ) Equal or more than 5000 3%
{ Write a program asking his total sales and calculate his commission
int a, b, c; amount.
printf ("Enter the value of a, b and c Ans: #include<stdio.h>
="); #include<conio.h>
scanf ("%d %d %d", &a, &b, &c); void main( )
{
if (a + b==90 || a+c== 90 || b+c == 90) int sales;
float totalsales, commission;
printf ("It is a right angled
printf ("Enter sales amount =");
triangle."); scanf ("%d", & sales);
else
printf ("It is not a right-angled if (sales < 5000)
triangle"); {
commission = sales * 1.5/100;
getch ( ); totalsales = sales + commission;
} printf ("Total sales = %.2f",
Result:
Enter any two numbers =60 30 getch ( );
}
It is right angled triangle. Result:
Enter ant two numbers =20 3
8. Write a program to enter any two numbers and find the greatest
number among these two numbers. A is the greater number.
Ans: #include<stdio.h>
#include<conio.h>
void main ( )
{
int a, b;
printf ("Enter any two numbers =");
scanf ("%d %d", &a, &b);

if (a > b)
printf ("A is the greater number.");
else
printf ("B is the greater number");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
totalsales);
}
else
{
commission = sales * 3/100;
totalsales = sales + commission;
printf ("Totalsales = %.2f",
totalsales);
}

getch ( );
}
Result:
Enter sales amount =4000

Totalsales=4060.00
10. In a company an employee is paid as under:
(i) HRA=10% of Basic salary and DA=55% of Basic salary.
ii) If his Basic salary is greater than 1500 then
HRA=500/- and DA=60% of Basic Salary.
Write a C program to find Gross salary of the employee.
Ans: #include<studio.h>
#include<conio.h>
void main()
{
float basic,hra,da,gross;
clrscr();
printf("\n Enter the basic salary of the
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …109 110 … A Complete Refresh Manual of C Programming


employee : Rs."); 12. Write a program of NTC to enter number of calls and find out total
scanf("%f",&basic); vat (10% of total) telecom service charge (10% of total + tsc) and
total amount. The rate of total is given below :
if(basic>1500)
Number of calls Rate
{
hra=500; number of call <=175 minimum Rs. 200/-
da=(60.00/100.00)*basic; otherwise, number of call is more Rs. 2 per call
} than 175
else Ans: #include<stdio.h>
{ #include<conio.h>
hra=(10.00/100.00)*basic; void main( )
da=(55.00/100.00)*basic; {
} int noc;
gross=basic+hra+da; float total, vat, tsc, tamt;
printf ("Enter total number of calls =");
printf("\n The Gross Salary is Rs. scanf ("%d", &noc);
%.2f",gross);
getch(); if (noc <=175)
} {
Result: total = 200;
Enter the basic salary of the employee tsc = total * 10/100;
: Rs.5000 vat = (total + tsc)* 10/100;
tamt = total + vat;
printf ("Total amount = %f", tamt);
The Gross Salary is Rs.8500.00 }
11. Write a program that asks cost of price(CP) and selling price(SP) else
and determine whether there is gain or loss. {
Ans: #include<stdio.h> total = 200 + (noc – 175) * 2;
#include<conio.h> tsc = total * 10/100;
void main( ) vat = (total + tsc) * 10/100;
{ tamt = total + vat;
int CP,SP,loss,gain; printf ("Total amount = %f", tamt);
printf(“Enter value of CP and SP:”); }
scanf(“%d%d”,&CP,&SP);
getch();
if(SP>CP) }
{ Result:
gain=SP-CP; Enter total number of calls =300
printf(“Gain=Rs%d”,gain);
} Total amount =499.500000
else
{
loss=CP-SP; }
printf(“Loss=Rs%d”,loss); getch();
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
}
13. Citizen are eligible to cast vote if they are 18 years or above and
Result:
Enter value of CP and SP:5000 3000 must be nepali. Write a program for this purpose.
Ans: #include<stdio.h>
Gain=2000 #include<conio.h>
void main ( )
{
int age;
char nep;
printf ("Enter the age = ");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …111 112 … A Complete Refresh Manual of C Programming


scanf ("%d", &age); 15. Write a program to enter a character from keyboard, convert the
printf ("Enter 'y' if nepali citizen,
otherwise enter 'n': "); getch ( );
scanf ("% c", nep); }
Result:
if (age >= 18) Enter any character =5
{
if (nep = = 'y') Entered character is digit.
printf ("ok, you are eligible to
cast vote");
else
printf ("Nepali citizen, not be
other.");
}
else
printf ("You are not eligible to cast
vote");

getch ( );
}
Result:
Enter the age: 19

Enter 'y' if nepali citizen,otherwise enter 'n':n


Nepali citizen, not be other.

14. Write a program to enter a character and check whether the entered
character is digit or not.
Ans: #include<stdio.h>
#include<conio.h>
void main ( )
{
char ch;
printf ("Enter any character =");
scanf("%c ", &ch);

if (ch>='0' && ch<='9')


printf("Entered character is digit.");
else
printf ("Not");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
lowercase character to uppercase and vice-versa. printf(“Imaginary roots can not be
Ans: #include<stdio.h> obtained.”);
#include<conio.h>
void main ( ) getch();
{ }
char ch;
printf ("Enter any character =");
scanf("%c",ch);

if (ch>=97 && ch<=122)


printf("The uppercase character
is%c.",ch-32);
else
printf ("The lowercase character
is%c.",ch+32);

getch ( );
}
Result:
Enter any character =y

The uppercase character is Y.

16. Write a program to find all possible roots of quadratic equation


ax2+bx+c=0. [T.U. 2069 Ashad]
Ans: #include<stdio.h>
#include<conio.h>
#include<math.h>
void main( )
{
int a,b,c,d;
float x,y;
printf(“Enter the value of a,b and c:”);
scanf(“%d%d%d”,&a,&b,&c);

d=sqrt(b*b-4*a*c);
if(d>0)
{
x=(-b+sqrt(d))/2*a;
y=(-b-sqrt(d))/2*a;

printf(“\nX=%.2f”,x);
printf(“\nY=%.2f”,y);
}
else
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …113 114 … A Complete Refresh Manual of C Programming


Result: 18. Write a program to display greatest number among three numbers
Enter the value of a,b and c:2 3 1 taken as input from user.
Ans: #include<stdio.h>
X=-2.00
Y=-4.00 #include<conio.h>
void main( )
17. Admission to a college in science branch is given if the following {
conditions are satisfied int a, b, c;
(i) Maths marks >= 80
(ii) Physics marks >= 75 printf ("Enter any three numbers = ");
scanf ("%d %d %d", &a, &b, &c);
(iii) Chemistry marks >= 70
(iv) Total percentage in all three subjects >= 80 if (a > b && a > c)
Given the marks in three subjects, write a program to process the printf ("A is greater");
applications to list the eligible candidates. else if (b>a && b>c)
Ans: #include<stdio.h> printf ("B is greater");
#include<conio.h> else
void main() printf("C is greater");
{
float math,phy,che; getch();
float per; }
char ch; Result:
clrscr(); Enter any three numbers=2 3 8

printf("\nDo u want to enter any record:-> "); C is greater


ch=getch();
while(ch=='y' || ch=='Y') 19. Write a c program to find largest among three numbers using
{ binary minus operator.
clrscr();
Ans: #include<stdio.h>
printf("\nEnter Marks in Math:-> ");
#include<conio.h>
scanf("%f",&math); int main()
printf("\nEnter Marks in Physics:-> "); {
scanf("%f",&phy); int a,b,c;
printf("\nEnter Marks in Chemistry:-> "); printf("\nEnter 3 numbers: ");
scanf("%f",&che); scanf("%d %d %d",&a,&b,&c);
per=(math+phy+che)/3.00; if(a-b>0 && a-c>0)
if(math>=80.00 && phy>=75.00 && che>=70.00 && printf("\nGreatest is a :%d",a);
per>=80.00) else
if(b-c>0)
printf("\nYou are eligible for selection."); printf("\nSorry you are not eligible!!");
else printf("\nDo u want to enter new record:-
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
> "); printf("\nGreatest is b :%d",b);
ch=getch(); else
} printf("\nGreatest is c :%d",c);
getch();
}
printf ("\nThanks for using it!"); Result:
getch(); Enter 3 numbers=2 3 8
}
Greatest number is c:8
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …115 116 … A Complete Refresh Manual of C Programming


else
20. Write a program to enter any three numbers and find out the middle printf("The month is not included in our
number. calender");
Ans: #include<stdio.h>
getch();
#include<conio.h>
void main ( ) }
{ Result:
int a, b, c; Enter any number= 8
printf ("Enter any three numbers = ");
scanf ("%d %d %d", &a, &b, &c); The month has 31 days
22. Write a program to test whether the entered character is alpha digit
if ((a>b && a<c) || (a < b && a > c)) or alpha character or special character on the basis of given
printf ("A is middle number"); condition.
else if ((b>a && b<c) || (b<a && b>c))
printf ("B is middle number"); character message
else if ((c>a && c<b) || (c<a && c>b)) 0-9 Alpha digit
printf ("C is middle number"); a-z Alpha character
else others Special characters
; Ans: #include<stdio.h>
#include<conio.h>
getch(); void main( )
} {
Result: char ch;
Enter any three numbers=2 3 8
printf ("Enter character =");
B is middle number scanf ("%c", ch);
21. Write a program whose input is a month entered as a number from 1 if (ch > = '1' && ch <= '9')
to 12 and whose output is the number of days in that month as [use printf ("Alpha digit");
if else or switch case] else if (ch>= 'a' && ch <= 'z')
Month input output printf ("Alpha character");
1,3,5,7,8,10,12 the month has 31 days else
printf ("special character");
2 the month has 28 days or 29 days in leap year
4,6,9,11 the month has 30 days getch ( );
other the month is not entered in oyr calender }
Ans: #include<stdio.h> Result:
#include<conio.h> Enter character= 8
void main()
{ Alpha digit
int m; 23. Write a program to check whether a box is cube, rectangle or semi-
printf("Enter any number="); rectangle. Prepare a test procedure to test this program.
scanf("%d",&m); Ans: #include<stdio.h>
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
#include<conio.h>
if(m==1 || m==3 || m==5 || m==7 || m==8 || m==10 void main()
|| m==12) {
printf("The month has 31 days"); float length, width, height;
else if(m==2) clrscr();
printf("The month has 28 or 29 days");
else if(m==4 || m==6 || m==9 || m==11) printf("enter the dimension of box\n");
printf("The month has 30 days"); printf("Length= ");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …117 118 … A Complete Refresh Manual of C Programming


scanf("%f",&length); scanf("%d",&math);
printf("width= "); printf(“Enter marks in account:”);
scanf("%f",&width); scanf("%d",&acc);
printf("height= "); printf(“Enter marks in cscience:”);
scanf("%f",&height); scanf ("%d",&cscience);
if(length==width)
{ if(length==height) total = eng + nep + math + acc + cscience;
printf("\nThe box is a cube\n"); scanf ("%s", name);
else printf ("Enter class =");
printf("\nThe box is a rectangle\n"); scanf ("%d", &clas);
} printf ("Enter marks in English:”);
if(width==(0.5*length)) scanf("%d",&eng);
printf("\nThe box is a semirectangle\n"); printf(“Enter marks in nepali:”);
getch(); scanf("%d",&nep);
} printf(“Enter marks in math:”):
Result:
Enter the dimension of box

Length=2
width= 2
height=3

The box is rectangle.


24. Write a program to input name, class and marks in five subjects like
english, math, nepali, account, computer science. Find total,
percentage, division, remarks. The condition of division is
percentage division
per > = 75 Distinction
per > = 60 AND per < 75 First
per > = 45 AND per < 60 Second
per > = 35 AND per <45 Third
Below 35 Fail
Ans: #include<stdio.h>
#include<conio.h>
void main( )
{
char name [30];
int clas, eng, nep, math, acc, cscience,
total;
float per;
printf ("Enter name of a student = ");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
per = total/5;

printf ("Name = %s\n", name);


printf ("Class %d\n", clas); printf
("Total =%d\n", total);
printf ("Percentage = %.2f\n", per);

if (eng > = 35 && nep > = 35 && math > = 35 &&


acc > =35 && cscience > = 35)
printf ("Remarks = passed\n");
else
printf ("Remarks = failed\n");

if (per > = 75)


printf("Division= distinction\n");
else if (per > = 60 )
printf ("\n division = first");
else if (per > = 45)
printf ("\n division = second");
else if (per> = 35)
printf ("\n Division = third");
else
printf ("\n division = fail");
getch ( );
}
Result:
Enter name of a student=Haris
Enter class=13
Enter marks in English:45
Enter marks in nepali:44
Enter marks in math:54
Enter marks in account:55
Enter marks in cscience:56

Name = Haris
Class=13
Total =254
Percentage = 50.80
Remarks=Passed
Division=Second
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …119 120 … A Complete Refresh Manual of C Programming


25. Write a program to input time in second and convert it into hour, scanf("%c",ch);
minute and second.
Ans: #include<stdio.h> switch(ch)
{
#include<conio.h>
void main( ) case 'r': case 'R':
{ printf("The color that you
int t, m, s, h, r; have choosen is red");
printf ("Enter time in seconds:"); break;
scanf ("%d", &t); case 'w': case'W':
printf("The color that you
if (t < 60) have choosen is white");
printf ("hh:mm:%d", t); break;
else if (t >60 && t < 3600) case 'b': case'B':
{
printf("The color that you
m = t/60;
s = t%60; have choosen is blue");
printf ("hh:%d:%d", m, s); break;
}
else default:
{ printf("Please choose a
h = t/3600; proper character ");
r = t%3600; }
m = r/60;
getch();
s = r%60; }
printf ("%d:%d:%d", h, m, s); Result:
} Enter a character=r

getch ( ); The color that you have chosen is red.


}
Other No more primary color
Result: Ans: #include<stdio.h>
Enter time in seconds:5000 #include<conio.h>
void main()
1:23:20 {
char ch;
26. Write a program that accepts a single character & gives output as: [
printf("Enter a character:");
Use if-else or switch-case ]
Character Color
r or R Red
w or W White
b or B Blue
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

27. Write a menu driven program to perform following: adding two


numbers, showing difference between two numbers, showing
product of two numbers and showing remainder when one number
is divided by another.
Or, Write a program that accepts two integer and an operator (+, -, *, /
or %). And the program should calculate the value as directed by the
operator and display the result. [Use Switch-Case]
Ans: #include<stdio.h>
#include<conio.h>
#include<process.h>
void main ( )
{
int a, b, c;
char ch;
printf ("Enter any two numbers =");
scanf ("%d%d",&a, &b);
printf("Enter your choice (+/-/*///%):");
scanf ("%c", ch);

switch (ch)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …121 122 … A Complete Refresh Manual of C Programming


{ {
case ‘+’ : float rad, per;
c = a + b; printf("\nEnter the radius of circle");
break; scanf("%f",&rad);
case ‘-‘ : per=(2*22*rad)/7;
if(a>b) printf("\nThe perimeter of circle is:
c = a – b; %.2f",per);
else break;
c=b-a; }
break; case 2:
case ‘*’ : {
c = a * b; int b,l,per;
break; printf("\nEnter the breadth of
case ‘/’ : rectangle:\t");
c = a/b; scanf("%d",&b);
break; printf("\nEnter the length of
case ‘%’ : rectangle:\t");
exit (o); scanf("%d",&l);
default : per = 2*(l+b);
printf ("You have to type (1-5) printf("\nThe perimeter of rectangle is: %d",per);
options"); break;
exit (o); }
} case 3:
printf(“Result:%d”,c); printf("Enter choice 1 for perimeter of
circle\n"); printf("Enter choice 2 for perimeter
getch ( ); of rectangle\n"); printf("Enter choice 3 for
} perimeter of triangle\n"); printf(“Enter your
Result: choice:\n”);
scanf("%d",&choice);
Enter any two number=3 2
Enter your choice (+/-/*///%):+
switch(choice)
Result:5
{
case 1:

28. Write a menu driven program which has the following options:
1. Perimeter of circle
2. Perimeter of rectangle
3. Perimeter of triangle
Ans: #include "conio.h"
#include "stdio.h"
int main()
{
int choice;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
{
int a,b,c,per;
printf("\nEnter the sides of the triangle\n");
printf("\nEnter the first side:\t"); scanf("%d",&a);
printf("\nEnter the second side:\t");
scanf("%d",&b);
printf("\nEnter the third side:\t");
scanf("%d",&c);
per=a+b+c;
printf("\nThe perimeter of triangle is:%d",per);
break;
}
default:
{
printf("Wrong choice");
}
}
getch();
}
Result:
Enter choice 1 for perimeter of circle Enter
choice 2 for perimeter of rectangle Enter
choice 3 for perimeter of triangle Enter your
choice:1

Enter the radius of circle:2


The perimeter of circle is:12.57
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …123 124 … A Complete Refresh Manual of C Programming


2.4 Looping (Repetition)
29. Write a c program to find largest among three numbers using
conditional operator
Ans: #include<stdio.h> 1. What is looping? List the name of loop. Also, write down the syntax
#include<conio.h> of do while ‘loop.
void main() Ans: Loop is a control structure used to perform repetitive operation. Some
{ programs involve repeating a set of instruction either a specified
int a,b,c,big; number of times or until a particular condition is met. This is done
printf("\nEnter 3 numbers:"); using a loop control structure. A program loop consists of two parts:
scanf("%d %d %d",&a,&b,&c);
big=(a>b&&a>c?a:b>c?b:c);
Body of the loop and control statement. The control statement tests
printf("\nThe biggest number is:%d",big); certain conditions and then decides repeated execution or termination
getch(); of statements. Most real programs contain some construct that loops
} within the program, performing repetitive actions on a stream of data
or a region of memory. The various looping statements are :
(a) for
(b) while
(c) do while
The syntax of ‘do while’ loop is
syntax : do
{
statement1;
statement2;
................
} while (condition);
When program execution reaches a do...while statement, the
following events occur:
1. The statements in statement are executed.
2. Condition is evaluated. If it's true, execution returns to step 1.
If it's false, the loop terminates
2. Differentiate between definite and indefinite loops with an example
of each. [T.U. 2058 Poush]
Ans: Definite loop [T.U. 2066 Magh]
The loop which repeats instructions for fixed or defined number of
times is called definite loop.Example:’for’ loop.
It is the most commonly used loop in the C program.The for
loop executes the initial expression first. It then checks the condition.
If the condition is true, the statements execute. Once the statements
are completed, the increment expression or decrement is evaluated.
The for statement then rechecks the condition and continues to loop
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
until the condition is false.The syntax of ‘for’ loop is
Syntax>for (exp1; exp2; exp3)
{
statement1;
..................
}
When a for statement is encountered during program execution,
the following events occur:
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …125 126 … A Complete Refresh Manual of C Programming


1. The expression,exp1 is evaluated. Exp1 is usually an [T. U. 2061
assignment statement that sets a variable to a particular value. Poush] Ans: Differences between break and continue statement
2. The expression,exp2,i.e. condition is evaluated. condition is B
r
typically a relational expression.
e
3. If exp2,i.e.condition evaluates to false (that is, as zero), the for
a
statement terminates, and execution passes to the first k
statement following statement. :
4. If exp2,i.e.condition evaluates to true (that is, as nonzero), the The "break" statement is used to terminate the control from the
C statement(s) in statement are executed. loop.It is normally used in switch-case statement,the break
5. The exp3,i.e. increment or decrement is evaluated, and statement must be used if not the control will be transferred to
execution returns to step 2. the subsequent case condition also. Example :
Indefinite loop
The loop which repeats the instruction for undefined number of
times is called indefinite loop.Examples:’while’ and ‘do while’ loop.
Let me to explain the ‘while’ loop.
It allows repeated execution of a statement or block of
statements as long as the condition remains true (nonzero). If the
condition is not true when the while command is first executed, the
statement(s) is never executed.The syntax of ‘while’ loop is
syntax>while (condition)
{
statement1;
................
}
When program execution reaches a while statement, the
following events occur:
1. The expression condition is evaluated.
2. If condition evaluates to false (that is, zero), the while
statement terminates, and execution passes to the first
statement following statement.
3. If condition evaluates to true (that is, nonzero), the C
statement(s) in statement are executed.
4. Execution returns to step 1.
3. Differentiate between break and continue statement with examples
[T.U. 2063 Baishakh]
Or, Explain in detail about break and continue statement.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

#include<stdio.h> Result:
#include<conio.h> 2 4 5 7 8 10
void main()
{
int a =1;
while (a < 20)
{
a = a + 1;
if (a%3==0)
break;
printf ("%d",a);
}
getch();
}
Result:
2

Continue :
Continue is another keyword that controls the flow of loops. If we
are executing a loop and hit a continue statement, the loop will stop its
current iteration, update itself (in the case of for loops) and begin to
execute again from the top. Essentially, the continue statement is
saying "this iteration of the loop is done; let's continue with the loop
without executing whatever code comes after me." Example :
#include<stdio.h>
#include<conio.h>
void main()
{
int a =1;
while (a < 10)
{
a = a + 1;
if (a%3==0)
continue;
printf ("%d",a);
}
getch();
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …127 128 … A Complete Refresh Manual of C Programming


4. Differentiate between 'for' and 'while' statements. 5. Differentiate between 'while' and 'do while' statement with example.
Ans: Differentiation between 'for' and 'while' statements : [T.U. 2059 Chaitra]
For While O, Explain along with flowchart how do-while loop differs from while
(a) The for statement executes the initial (a) It allows repeated loop. [T.U. 2061 Baisakh, 2066 Jestha]
expression first. It then checks the execution of a statement or Ans: Differentiation between while and do while statements :
condition. If the condition is true, the block of statements as While statement
statements execute. Once the long as the condition The basic format of while statement is while (conditional
statements are completed, the remains true (nonzero). If expression)
increment expression or decrement is the condition is not true {
evaluated. The for statement then when the while command ...block of statements to
execute...
rechecks the condition and continues is first executed, the
to loop until the condition is false. statement(s) is never The while loop continues to loop until the conditional
executed. expression becomes false. Once this expression become false, the
(b) syntax > (b) syntax>while control is transferred out of the loop. On exit, the program continues
for (exp1; exp2; exp3) (condition) with the statement immediately after the body of the loop. For
{ {
statement1; statement1; example:
i=0;
..................
} ................ while(i<10)
where, } {
exp1 = Initial expression printf(“Hello world\n”);
exp2=Conditional expression i++;
exp3=Increment or }
decrement This statement will print “Hello world” 10 times in a new line
(c) The flow chart of for loop (c) The flow chart of while and come out of the loop when ‘i’ become 10.
loop Flow chart of while loop
Initialize

Inc/Dec True
Condition ? Statements True
True Condition? Statements
Condition ? Statements
False
False False
printf("%d\t",
(d) Example:Displaying 1 to 10 numbers a);
(d) Example: Displaying 1 to
# include <stdio.h> 10 numbers
getch( );
# include <conio.h> # include <stdio.h>
}
void main ( ) # include <conio.h>
{ void main ( )
int a; {
for (a = 1; a <= 10; ++a) int a;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
a = 1; D of the form:
while (a <= 10) do
o
{ { ...block of statements to execute...
printf("%d\t", a); } while(conditional expression);
a = a + 1; w
While construct checks the conditional expression before the
} h
loop is executed. Sometimes it is necessary to execute the body of the
getch( ); i
loop before the conditional expression is evaluated. Such situations
} l
are handled by do-while loop construct. On reaching the do statement,
e
the body of the loop is evaluated and at the end of the loop, the
conditional expression is checked for true or false. If true,it continues
s
to evaluate the body again and when condition become false, the
t
control is transferred to the statement immediately after the while
a
statement.
t
e
m
e
n
t
T
h
i
s

l
o
o
p

c
o
n
s
t
r
u
c
t

i
s
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …129 130 … A Complete Refresh Manual of C Programming


For example: 2.5 C Programmings-3 (Repetition)
do
{
printf( “Input a character\n”); 1. Write a program to find sum of 1 to 100 numbers.
ch=getch( ); Ans: #include<stdio.h>
} while(ch=’n’); #include<conio.h>
This segment of program reads a character from the keyboard void main( )
until ‘n’ is keyed in. {
The flowchart of ‘do while’ loop is int n, sum = 0;
Statements for (n = 1; n < = 100; ++n)
sum = sum + n;
printf ("sum =%d", sum);
getch ( );
}
Condition? Result:
True
Sum=5050
False
2. Write a 'C' program to print all the ASCII codes for alphabets from
6. Differentiate between pre-test and post- test loop. A to Z.
Ans: Diffrerences between pre-test and post test loop: Ans: #include<stdio.h>
Pre-test loop Post-test loop #include<conio.h>
a. Before beginning of the a. At the end of body of void main( )
loop execution ,tst loop,test condition is {
condition is evaluated. evaluated. char ch1;
for (ch1 = 'A'; ch1 < = 'z';ch1=ch1+1)
b.Body of loop will be executed b. The loop executes a body of
printf ("%d\t", ch1);
if the condition is true. instruction at least one time getch ( );
without depending on the }
test condition.
c. Flowchart of pre-test loop c.The flowchart of post test loop Result:
Statements 65 66 67 68 69 70 71 72
73 74 77 78 79 80 81 82
83 84 85 86 87 88 89 90
True Statements
Condition ? Condition ? 91 92 93 94 95 96 97 98
True 99 100 101 103 102 104 105 106
False False 107 108 109 110 111 112 113 114
115 116 117 118 119 120 121 122
d. The pre-test loops are for and d. The post-test loops is 3. Write a program to read two integers n1 and n2. Display all even
while. do…while. numbers between those two numbers. [T.U.2058]
e. The pre-test loop is also e. The post-test loop is also Ans: #include<stdio.h>
known as entry controlled known as exit controlled #include<conio.h>
loop. loop.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
void main()
{
int n1,n2,i;
printf(“Enter the value of n1 and n2:”);
scanf(“%d%d”,&n1,&n2);

for(i=n1;i<=n2;++i)
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …131 132 … A Complete Refresh Manual of C Programming


if(i%2==0) 5. Write a computer program to display a table of numbers, its square
printf(“%d\t”,i); values and its cube values from 1 to n-1,where n is any number
} typed by user at the terminal. [T.U.2058 Poush]
getch(); Ans: #include<stdio.h>
} #include<conio.h>
void main()
{
Result: int a,n,sq,cu;
Enter the value of n1 and n2:5 10 printf(“Enter the value of n:”);
scanf(“%d”,&n);
6 8 10
4. Write a program to find sum and average of user defined number. printf(“Number\t Square\t Cube\n”);
for(a=1;a<=n-1;++a)
Ans: #include<stdio.h>
{
#include<conio.h> sq=a*a;
void main() cu=a*a*a;
{ printf(“%d\t%d\t%d\n”,a,sq,cu);
int i,a,n,sum=0; }
float avg; getch();
printf(“How many numbers?”); }
scanf(“%d”,&n);
Result:
for (i=0;i<n;++i) Enter the value of n:6
{ Number Square Cube
printf(“Enter numbers:”); 1 1 1
scanf(“%d”,&a); 2 4 8
3 9 27
sum=sum+a;
4 16 64
} 5 25 125
avg=sum/n;

printf(“Sum=%d\n”,sum);
printf(“Average=%.2f”,avg);
6. Write a program to compute factorial for a given number n, where
n is a non-negative integer,[n!=1*2*3*4......(n-1)*n].
getch();
}
Ans: #include<stdio.h>
#include<conio.h>
void main()
Result: {
How many number?5 Enter numbers:40
Enter numbers:5
Enter numbers:10
Enter numbers:20 Sum=105
Enter numbers:30 Average=21.00
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
i scanf("%d",& num);
n
t if(num<0)
printf("Error.Plz enter positive no only.");
n else if(num==0)
= printf("The factorial of the given no
1 is:%d",fact);
, else
f {
a while(n<=num)
c {
t fact=fact*n;
=
1
,
n
u
m
;

p
r
i
n
t
f
(
"
E
n
t
e
r

n
u
m
b
e
r
:
"
)
;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …133 134 … A Complete Refresh Manual of C Programming


n=n+1;
} 9. Write a program to calculate the area of n number of circle where
printf("The factorial of the given no radius of circle is input by user and define Gas constant.
is:%d.",fact);
Ans: #include<stdio.h>
} #include<conio.h>
getch(); void main()
} {
Result: int n,i,r;
Enter a number:4 float a;
printf("Enter number of circle=");
The factorial of the given no is 24. scanf("%d",&n);

for(i=1;i<=n;++i)
7. Write a program to print the series 1,5,9,13........upto 10th terms. {
Ans: #include<stdio.h> printf("Enter value of radious of circle=");
#include<conio.h> scanf("%d",&r);
void main() a=3.1416*r*r;
{ printf("Area=%.2f\n",a);
int cnt=1,i; }
printf("%d\t",cnt);
getch();
for(i=0;i<10;++i) }
{ Result:
cnt=cnt+4; Enter number of circle=3
printf("%d\t",cnt);
} Enter the valu of radiuys of circle=2
getch(); Area=12.56
} Enter the valu of radiuys of circle=3
Area=28.27
Result: Enter the valu of radiuys of circle=4
1 59 13 17 21 25 27 Area=50.26
33 37 41
8. Write a program to display following series:30,25,20,………up to
10th terms. 10. Write a C program to read any number and check whether the
Ans: #include<stdio.h> entered number is palindrome or not.
#include<conio.h> Ans: #include<stdio.h>
void main() #include<conio.h>
void main( )
{
{
int a,i=30;
i=i-5;
for(a=1;a<=10;++a)
}
{
getch();
printf(“%d”,i);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
} int n,num,rev=0,r;
Result: printf(“Enter any number:”);
scanf(“%d”,&num);
30 25 20 15 10 5 0 -5 -10 -15
n=num;

while(num!=0)
{
r=num%10;
rev=rev*10+r;
num=num/10;
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …135 136 … A Complete Refresh Manual of C Programming


if(n==rev) {
printf(“The enterd number is palindrome”); c=a+b;
else printf("%d\t",c);
printf(“The entered number is not palindrome”); a=b;
getch(); b=c;
} }
Result: getch();
Enter any number:121 }
than 500. [T.U. 2061 Poush]
The entered number is palindrome. Ans: #include<stdio.h>
#include<conio.h>
void main()
11. Write a program to check whether a number is Armonstrong or not. {
[Armonstrong no: - An Armonstrong number is that whose sum of
cube of digits is equal to number itself.e.g. 371 = 33 + 73 + 13 = 371]
Ans: #include<stdio.h>
#include<conio.h>
void main()
{
int i,n,sum=0,r;
printf("Enter any nuber=");
scanf("%d",&n);
i=n;
do{
r=n%10;
sum=sum+r*r*r;
n=n/10;
} while(n>0);

if(sum==i)
printf("The entered number is armonstrong”);
else
printf("Not armonstrong");
getch();
}
Result:
Enter any nuber=371

The entered number is armonstrong

12. Write a program to print the fibonacci series until the term is less
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Result: }
Enter how many numbers to be entered:7
Result:
1 1 2 3 5 8 13 1 25 10 17 26 37 50
13. Write a program to print the following series until the term value is 65 82 101 122 145 170 197 266
less than 750.The series is 1,2,5,10,17,26,37…… ………………………………………… 559505 561002
[T.U. 2063 Baishakh]
Ans: #include<stdio.h>
#include<conio.h> 14. Write a C program to find the sum of the following series and input
void main() steps from keyboard. Sum=1 + 2 + 6 + 24 + 120 + ......
{ Ans: #include<stdio.h>
int a=0,n=1;
while(n<=750) #include<conio.h>
{ void main()
printf("%d\t",a*a+1); {
++a; long int fact=1,i,n,sum=0;
++n; clrscr();
} printf("\n ENTER THE VALUE OF N: ");
getch();
int a=0,b=1,c,count; scanf("%ld",&n);
printf("\n THE SERIES IS ");
printf("%d\t%d\t",a,b);
for(count=2;count<500;count++) for(i=1;i<=n;i++)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …137 138 … A Complete Refresh Manual of C Programming


{ printf ("=%d",sum);
fact = fact * i; getch();
if(i==n) }
printf(" %ld",fact); Result:
else Enter the numbers of terms to be added:10
printf("%ld + ",fact); 1-3+5-7+9-11+13-15+17-19=-10
sum = sum + fact;
}
16. Write a C program to print out n values of the following sequence. 1
printf("\nTHE FACTORIAL VALUE IS %ld the sum is 1 1 1 11 1111 …..
%ld",fact,sum); Ans: #include<stdio.h>
getch(); #include<conio.h>
} main()
Result: {
ENTER THE VALUE OF N: 5 int i,j,n,k;
THE SERIES IS 1 + 2 + 6 + 24 + 120 clrscr();
printf("\n Enter number: \n");
THE FACTORIAL VALUE IS 120 the sum is 153 scanf("%d",&n);
k=1;
for(i=1;i<=n;i++)
{
15. Write a C program to compute the sum of first n terms of the for(j=1;j<=i;j++)
following series using ‘for’ loop. printf("%d",k);
1 – 3 + 5 – 7 + 9 - …… printf("\t");
Ans: #include <stdio.h> }
#include <conio.h> getch();
void main ( ) }
{ Result:
int start=1,i=1,sum=0; Enter number:4
clrscr();
printf("\nEnter number of terms to be added:-> "); 1 11 111 1111
scanf("%d",&no);
17. Write a 'C' program to read positive integers less than 20 and
for (i=1;i<=no;i++) display its multiplication table.
{ Ans: #include<stdio.h>
if (i%2!=0) #include<conio.h>
{ void main ( )
sum+=start; {
if (i==1) int n, i, mul;
printf ("%d",start); x :
else printf ("Enter no:-");
printf ("+%d",start); scanf ("%d", &n);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
}
else
if (n > 20)
{
goto x;
sum-=start;
printf ("-%d",start); else
} {
start+=2; for (i = 1; i <=10; i ++)
} {
mul = n * i;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …139 140 … A Complete Refresh Manual of C Programming


printf ("\n %d x %d = %d", n, i, mul); Ans: #include <stdio.h>
} #include <conio.h>
} void main ( )
getch ( ); {
} int a, b, c = 1, i;
Result: printf ("Enter the value of base =");
Enter no:5 scanf ("%d", &a);
printf ("Enter value of exponent =");
5 x 1=5 scanf ("%d", &b);
5 x 2=10
5 x 3=15 for (i = 0; i < b; ++i)
5 x 4=20
c = c*a;
5 x 5=25
5 x 6=30
5 x 7=35 printf ("Power = %d", c);
5 x 8=40 getch ( );
5 x 9=45 }
5 x 10=50 Result:
Enter the value of base =5
Enter value of exponent =2
18. Write a program to input an integer number and checks whether it
is prime or not. [T.U. 2061 Poush] Power=25
Ans: #include<stdio.h>
#include<conio.h>
void main ( ) 20. Write a program to accept any integer and print it in reverse order.
{ For example, if number is 542 then reverse order is 245.
int a, n, j; Ans: #include <stdio.h>
printf ("Enter any number ="); #include <conio.h>
scanf ("%d", &n); void main ( )
a=n; {
getch ( );
for (j = 2; j <n; j++) }
{ Result:
if (n%j==0) Enter any number=7
{
printf("Not prime"); Prime no=7
break;
}
}

if (a==j)
printf ("\n Prime no=%d ", a);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
int n, r; n = n/10;
printf ("\n Enter any number :-"); }
scanf ("%d", &n);
printf(“The reverse order of digits getch ( );
=”); }
Result:
while (n!=0) Enter any number=123
{
r = n%10; The reverse order of digits =321
printf ("%d", r);
19. Write a program to calculate the value of a raised to b. [e.g. 23 = 8]
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
r = n%10;
C Programming Language …141 sum = sum + r;
21. Write a computer program that reads in an integer value for n then n = n/10;
sums the integers from n to 2n if n is non-negative, or from 2n to n }
if n is negative. Display the sum. [T.U. 2057 Chaitra] printf ("Sum of digit of number =%d",sum);
Ans: #include <stdio.h> getch ( );
#include <conio.h> }
void main ( )
{
int a,n,sum=0;
printf(“Enter value of n:”);
scanf(“%d”,&n);

if(n>0)
{
for(a=n;a<=2*n;++a)
sum=sum+a;
}
else
{
for(a=2*n;a<=n;++a)
sum=sum+a;
}

printf(“Sum=%d”,sum);
getch();
}

Result:
Enter value of n:10
Sum=165
22. Write a program to accept any number and find sum of digit of that
number. [e.g. 275, sum = 2 + 7 + 5 = 14]
Ans: #include <stdio.h>
#include <conio.h>
void main ( )
{
int n, sum = 0, r;
printf ("Enter any number =");
scanf ("%d", &n);

while (n > 0)
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
{
142 … A Complete Refresh Manual of C Programming printf ("Enter the number =");
scanf ("%d", &no);
Result: if (no > max)
Enter any number=124 max = no;
}
Sum of digit of number=7
printf ("\n maximum no = %d", max);
23. Write a program to read a number and check whether the entered getch ( );
number is perfect or not.
Ans: #include<stdio.h>
#include<conio.h>
int main()
{
int n,i=1,sum=0;
printf("\nEnter a number:-");
scanf("%d",&n);
while(i<n)
{
if(n%i==0)
sum=sum+i;
i++;
}
if(sum==n)
printf("\nThe no %d is a perfect number",i);
else
printf("\nThe no %d is not a perfect
number",i);
getch();
}
Result:
Enter a number:5
The no is not a perfect number.

24. Write a program to read 'n' different user defined numbers and
picks largest of them.
Ans: #include <stdio.h>
#include <conio.h>
void main ( )
{
int n, max = 0, no, count;
printf ("Enter how many numbers =");
scanf ("%d", &n);

for (count = 1; count < = n; count + +)


F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …143 144 … A Complete Refresh Manual of C Programming


}
if(n>0)
Result: sum=sum+n;
Enter how many numbers=5 }
printf("sum=%d",sum);
Enter the number=4 getch();
Enter the number=400 }
Enter the number=405 Result:
Enter the number=1 enter no=1
Enter the number=10 enter no=-20
enter no=2
Maximum no=405 enter no=-3
enter no=40
enter no=5
25. Write a program to enter a decimal number and converts it into enter no=-56
binary number. enter no=65
Ans: #include <stdio.h> enter no=5
#include <conio.h>
enter no=10
void main ( )
{
int p = 1, t = 0, n,r; Ans: #include<stdio.h>
printf ("Enter decimal number = "); #include<conio.h>
scanf ("%d", &n); void main()
{
while (n! = 0) int i,n,sum=0;
{ for(i=1;i<=10;++i)
r = n%2; {
t = t + (r * p); printf("enter no=");
n = n/2; scanf("%d",&n);
p = p*10;
}
printf ("Binary number = %d", t);
getch ( );
}

Result:
Enter decimal number=15

Binary number=1111

26. Write a program that reads 10 integer value and prints the total of
all non negative numbers in the list.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Sum=128

27. Write a program to enter highest and lowest number and find the
sum of lowest to highest number.
Ans: #include <stdio.h>
#include <conio.h>
void main ( )
{
int high, low, sum = 0, temp, num;
printf ("Enter a high number =");
scanf ("%d", &high);
printf ("Enter a low number =");
scanf ("%d", &low);
if (low > high)
{
temp = low;
low = high;
high = temp;
}
for (num = low; num < = high; num + +)
{
sum = sum + num;
}

printf ("High no is %d\n", high);


printf ("Low no is %d\n", low);
printf ("Sum of high & low : %d", sum);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …145 146 … A Complete Refresh Manual of C Programming


getch ( );
} 29. Write a program to reverse any given integer number and also find
their sum.[Example: if number input=294, then output must be 492
Result: and sum=15] .
Enter a high number =20
Enter a low number=15 Ans: #include<stdio.h>
#include<conio.h>
High no is 20 void main()
Low no is 15 {
Sum of high & low:105 int n,r,sum=0;
printf("enter any no=");
Enter the value of n=5
28. Write a program to read ‘n’ different numbers, count total number
of +ve and -ve numbers. Enter numbers=30
Ans: #include<stdio.h> Enter numbers=-4
#include<conio.h> Enter numbers=12
Enter numbers=90
void main( )
Enter number=-6
{ Total number of +ve no. =3
int n,no ,i,pcount=0, ncount=0;; Total number of -ve no. =2
printf ("Enter the value of n =");
scanf ("%d",&n);

for (i =1;i<=n;i++)
{
printf ("Enter numbers : \n");
scanf ("%d",&no);
if(no>0)
pcount = pcount + 1;
else
ncount = ncount + 1;
}

printf ("Total number of +ve no. =


%d\n", pcount);
printf ("Total number of -ve no. = %d",
ncount);
getch();
}

Result:
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
scanf("%d",&n);
printf(“The reverse order of digits=”);

while(n>0)
{
r=n%10;
printf("%d",r);
n=n/10;
sum=sum+r;
}

printf("sum=%d",sum);
getch();
}
Result:
Enter any no=123

The reverse order of digits=321


Sum=6

30. Write a menu driven program which has following options :


1. Factorial number
2. Prime or not
3. Odd or even
4. Multiplication table
5. Exit
Ans: #include <stdio.h>
#include <conio.h>
void main ( )
{
int choice, num, i;
long int fact;
printf ("\n\n 1. Factorial number");
printf ("2. Prime \n");
printf ("3. Odd or even\n");
printf ("4. Multiplication Table");
printf ("5. Exit \n");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …147 148 … A Complete Refresh Manual of C Programming


}
printf ("Enter your choice (1/2/3/4/5):-"); {
scanf ("%d", &choice); printf ("Enter no =");
scanf ("% d", &num);
switch (choice) for (i = 1; i < = 10; i + +)
{ {
case 1 : int mult = num * i;
{ printf ("\t %d X %d = %d \n", num, i, mult);
printf ("Enter number =");
scanf ("%d", &num);
fact = 1;
for (i = 1; i <= num; i + +)
fact = fact * i;
printf ("Factorial no = % ld", fact);
}
break;

case 2 :
{
printf ("Enter number =");
scanf ("%d", &num);
for (i = 2; i < num; i + +)
{
if (num % i = = 0)
{
printf ("\n Not Prime");
break;
}
}
if (i = = num)
printf ("\n Prime number");
}
break;
case 3 :
{
printf ("Enter number =");
scanf ("%d", &num);
if (num%2 = = 0)
printf ("\n even number");
else
printf ("\n odd number");
}
break;
case 4 :
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
} bin_no;
break; pow8=1;
oct_no=0;
case 5 :
exit (0); while (no>0)
{
default : i=0;
printf ("You are not inter_oct=0;
allowed to type pow2=1;
other”); while (i<=2)
exit (0); {
} if (no==0)break;
getch ( ); rem=no%10;
} inter_oct+=rem*pow2;
Result: i++;
1. Factorial number pow2*=2;
2. Prime
3. Odd or even
4. Multiplication Table
5. Exit
Enter your choice (1/2/3/4/5):-1
Enter number=4
Factorial no=24
31. Write a C program to convert a binary
number to its corresponding octal number.
Ans:
#include
<stdio.h>
#incl
ude
<coni
o.h>
void main ( )
{
long int bin_no,no;
int oct_no,oct_p,i,rem,pow2,pow8 ,
inter_oct;
clrscr();

printf ("\nEnter the Binary


number:-> ");
scanf("%ld",&bin_no);
n
o
=
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …149 150 … A Complete Refresh Manual of C Programming


no/=10; 33. Write a program that will generate every third integer beginning
} with i=2 and containing for all integers that are less than 100.
oct_no+=inter_oct*pow8; Calculate the sum of these numbers that are exactly divisible
pow8*=10;
}
by 7. [T. U. 2059 Poush]
Ans: #include<stdio.h>
printf ("\nOctal Equivalent for %ld= #include<conio.h>
%d",bin_no,oct_no); void main()
getch(); {
} int a,sum=0;
for(a=2;a<100;a+=2)
{
Result:
if(a%7==0)
Enter the Binary number:->11101 {
sum=sum+a;
Octal Equivalent for 11101=35 printf(“\n%d”,a);
}
}
32. Write a C program to test whether a given pair of numbers are printf(“\nSum of numbers=%d”,sum);
amicable numbers. (Amicable number are pairs of numbers each of getch();
whose divisors add to the other number) (8) }
Ans: #include<stdio.h> Result:
#include<conio.h> 14
#include<math.h> 28
void main() 42
{ 56
int i,j,n,sum_i=0,sum_j=0; 70
clrscr(); 84
printf("enter any two numbers >"); 98
scanf("%d%d",&i,&j);
Sum of numbers=392
for(n=1;n<i;n++) else
{ printf ("\nNot Amicable");
if (i%n==0) getch();
sum_i+=n; }
} Result:
for (n=1;n<j;n++) Enter any two number >5 3
{
if (j%n==0) Not Amicable
sum_j+=n;
}

if ((sum_j==i) && (sum_i==j))


printf ("\nAmicable");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
34. Write a program to read an integer and add /10;
the individual digits contained in it until the }
final sum is single digit. For example if
entered number is n=2175698 then
2+1+7+5+6+9+8=38
38=3+8=11
11=1+1=2 is the final answer.
[T. U. 2063 Poush] Ans: #include<stdio.h>
#include<conio.h>
void main()
{
int
n,r,sum=0
,r1,s1=0;
printf("E
nter any
number=")
;
scanf("%d
",&n);

while(n>0)
{
r
=
n
%
1
0
;

s
u
m
=
s
u
m
+
r
;

n
=
n
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …151 152 … A Complete Refresh Manual of C Programming


while(sum>0) 36. Write a c program to find out L.C.M. of two numbers.
{ Ans: #include<stdio.h>
r1=sum%10; #include<>conio.h>
s1=s1+r1; void main()
sum=sum/10; {
} int n1,n2,x,y;
printf("Happy number=%d",s1); printf(“\n HCF is %d”,hcf);
getch();
getch();
}
}
Result:
Enter any number=5234 Result:
Enter two number=34 2
Happy number=5
2
35. Write a C program to find the HCF of two integer numbers just
entered by user. Program to find the HCF of two integer numbers
just entered by user. [T.U. 2063 Poush]
Ans: #include<stdio.h>
#include<conio.h>
void main()
{
int n,m,rem,temp,hcf;
printf(“Enter two numnber:”):
scanf(“%d%d”,&m,&n);

if(m<n)
{
temp=m;
m=n;
n=temp;
}
do
{
rem=m%n;
m=n;
hcf=n;
n=rem;
}while(rem!=0);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
printf("\nEnter two numbers:"); scanf("%s",&ch);
scanf("%d %d",&n1,&n2);
x=n1,y=n2;
while(n1!=n2)
{
if(n1>n2)
n1=n1-n2;
else
n2=n2-n1;
}
printf("L.C.M=%d",x*y/n1);
getch();
}
Result:
Enter two number=34 2

L.C.M.=34

37. Write a program that reads positive numbers until user enters “no”
and then sum the numbers divisible by 4 that lie between the range
of 10 and 50 and finally display the count and the average value.
[T.U. 2065 Shrawan]
Ans: #include<stdio.h>
#include<conio.h>
void main()
{
char ch='y';
int sum=0,a=10,num,count=0;
float avg;
while(ch=='Y' || ch=='y')
{
if(a<=50)
{
printf("Enter numbers:");
scanf("%d",&num);
if(num%4==0)
{
sum=sum+num;
count=count+1;
}

printf("Do you want to continue(y/n)?");


F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …153 154 … A Complete Refresh Manual of C Programming


} printf(“Enter value of n and x:”)
} scanf(“%d%f”,&n,&x);
avg=sum/count;
printf("\nCount=%d",count); Sn=1+1/x+1/x2+1/x3+………….. [T.U. 2062 Baisakh]
printf("\nAverage=%.2f",avg); Ans: #include<stdio.h>
getch(); #include<conio.h>
} #include<math.h>
Result: void main()
{
Enter numbers=4
Do you want to continue(y/n)?y
Enter numbers=3
Do you want to continue(y/n)?y
Enter numbers=20
Do you want to continue(y/n)?n

Count=2
Average=12.00
38. Write a program to find the terms in the given series till the value of
the term is less than 1000.(12+22)/3,(22+32)/4,(32+42)/5,……..
[T. U. 2059 Chaitra]
Ans: #include<stdio.h>
#include<conio.h>
void main()
{
int a=1;
float term;
do{
term=((a*a)+(a+1)*(a+1))/((float)(a+2));
printf("%.2f\t",term);
++a;
} while(a<250);
getch();
}
Result:
1.67 3.25 5.00 6.83 8.71 10.62 12.56 14.50
16.45 18.42 20.38 22.36 24.33 26.31 28.29 30.28
…………………………………………………………………
…………………………………………………494.02 496.02

39. Write C programs to evaluate the series until the term becomes less
than 10-6.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
for(i=1;i<n;++i) float */
{ printf("\n How many terms ? ");
term=term*1/pow(x,i);
scanf("%d", &n);
sum=sum+term;
}
printf(“Sum=%.2f”,sum); for ( i = 1; i <= n ; ++i)
getch(); {
} term = i/(i +1); /*cast to float is must else
Result: term = 0*/
Enter value of n and x:5 2 ft += (float) i / ( i + 1);
Sum=0.64 sum += ft;
}
40. Sum of first n terms of a series 1 /2 + 2/3 +3/4 ……….
In this program it is essential to use cast. As shown in the program. printf("\n sum = %.2f", sum); /*Note TERM IS
PRINTED AS 0*/
Ans: #include<stdio.h> printf ("\n term = %.2f", term);
#include<conio.h>
getch();
void main()
}
{
int n, i; Result:
float sum = 0, term = 0, ft ; /* ft is term in How many terms?5
int i,j,n; Sum=9.85
float sum=1,term=1; Term=0.00
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …155 156 … A Complete Refresh Manual of C Programming


2 scanf("%ld",&x);
41. Write a program to sum of first n terms of the series 1 + x + x /2.1 +
x3/3.2.1 + …
Ans: #include<stdio.h> for(i=1,cnt=1;i<=n;i=i+2,cnt++)
{
#include<conio.h>
for(j=1,sq=1;j<=i;j++)
void main() sq=sq*x;
{ printf("\n SQ = %ld",sq);
float sum = 1, x, ter = 1; for(k=1,fact=1;k<=i;k++)
int n, i; fact=fact*k;
clrscr(); printf("\n fact = %7.2lf",fact);
printf("\n how many terms ? ");
scanf("%d", &n); if(cnt%2==1)
printf (“%f”, &%); sum=sum+(sq/fact);
scanf("%f", &x); else
sum=sum-(sq/fact);
printf("\n THE SUM OF THIS SERIES IS
for ( i= 1 ; i<=n ; ++i) %7.2lf\n",sum);
{ }
term = term * % / i ; getch();
sum += term; }
printf("\n sum = %.2f", sum); Result:
}
ENTER THE VALUE OF N: 5
getch(); ENTER THE VALUE OF X: 4
} SQ= 4
Result: fact= 1.00
THE SUM OF THIS SERIES IS 4.00
how many terms? 5
give x? 2 SQ= 64
sum = 3.00 fact= 6.00
sum = 5.00 THE SUM OF THIS SERIES IS -6.67
sum = 6.33
SQ=1024
sum = 7.00 fact=120.00
sum = 7.26 THE SUM OF THIS SERIES IS 1.87

42. Write a program to find sum of series given below for given n terms {
long int x,i,j,k,n,sq,cnt;
and x..
double fact,sum=0;
x-x3/3!+x5/5!-x7/7!+…….. [T.U. 2062 Poush] clrscr();
Ans: #include<stdio.h>
#include<conio.h> printf("\n ENTER THE VALUE OF N: ");
void main()
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
scanf("%ld",&n);
printf("\n ENTER THE VALUE OF X: "); 43. Code for program to print the sum of series 1 + 1/2 + 1/3 + 1/4 + ... +
1/n. in c programming
Ans: #include<stdio.h>
#include<conio.h>
void main()
{
double n,sum=0,i;
clrscr();

printf("\n Please Give The Value of N: ");


scanf("%lf",&n);
for(i=1;i<=n;i++)
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …157 158 … A Complete Refresh Manual of C Programming


sum = sum + (1/i); }
if(i==1) Result:
printf("\n 1 +"); PLEASE ENTER THE VALUE OF N: 9
else if(i==n) SUM = 12 - 32 + 52 - 72 + 92 - 112 + 132 - 152 + 172
printf(" (1/%d) ",i);
else THE SUM IS 92
printf(" (1/%d) + ",i);
} 45. Write a program to calculate sum of terms of 1/n i.e. 1/n + 2/n + 3/n
printf("\n\n THE SUM OF THIS SERIES IS %.2lf",sum); printf("%ld",i);
getch(); else
} printf("%ld + ",i);
Result:
Please Give The Value of N: 5
1 + (1/2) + (1/3) + (1/4) + (1/5)
THE SUM OF THIS SERIES IS 2.28

44. Write a program to find sum of the following series.


Input steps from keyboard. sum =12-32+52-72+.....
Ans: #include<stdio.h>
#include<conio.h>
void main()
{

long int n,i,j,sum=0;


clrscr();
printf("\n PLEASE ENTER THE VALUE OF N: ");
scanf("%ld",&n); printf("\n
SUM = ");
for(j=1,i=12;j<=n;i=i+20,j++)
{
if(j%2==1)
{
sum=sum+i;
if(j==n)
printf("%ld",i);
else
printf("%ld - ",i);
}
else
{
sum=sum-i;
if(j==n)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
and so on till n/n. }
Ans: #include<stdio.h>
#include<conio.h> printf("Sum = %.2f\n",sum);
void main() getch();
}
{
float sum,n,term; Result:
Enter value of n:10
int count = 1;
sum = 0; Sum=1.00
46. Write a C program to convert a binary number to its corresponding
printf("Enter value of n\n"); octal number.
scanf("%f",&n); Ans: #include<stdio.h>
term = 1.0/n; #include<conio.h>
void main()
while(count<=n) {
{
main()
sum = sum + term;
{
count++;
long int bin_no,no;
} int oct_no,oct_p,i,rem,pow2,pow8,inter_oct;
} clrscr();
printf("\n\n THE SUM IS %ld",sum); printf ("\nEnter the Binary number: -> ");
getch(); scanf("%ld",&bin_no);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …159 160 … A Complete Refresh Manual of C Programming


no=bin_no; }
pow8=1; 49. Write a Program to read values from user and find sum until user
oct_no=0;
while (no>0)
types ),also display sum and average. [T.U. 2068 Shrawan]
{ Ans: #include<stdio.h>
i=0; #include<conio.h>
inter_oct=0; void main()
pow2=1;
{
while (i<=2)
{ int sum=0,num,count=0;
if (no==0)break; rem=no%10; float avg;
inter_oct+=rem*pow2;
i++; do{
pow2*=2; printf("Enter numbers:");
no/=10;
} scanf("%d",&num);
oct_no+=inter_oct*pow8; sum=sum+num;
pow8*=10; count=count+1;
} }while(n!=0);
printf("\nOctal Equivalent for %ld =
%d",bin_no,oct_no);
getch(); avg=(float)sum/count;
} printf("\nSum=%d",sum);
47. Write a C program to generate the following series: printf("\nAverage=%.2f",avg);
Sum=X+x/2!+x4/4!+…………………..+xn/n! getch();
Ans: #include<stdio.h> }
#include<conio.h>
void main()
{
main()
{
int n,i=0,j=1;
long int fact=1;
clrscr();
printf ("\nEnter the limit for the series:-> ");
scanf("%d",&n);
if (n%2!=0)
n-=1;
printf(“X +”);
for (i=1;i<=n;)
{
fact=1;j=1;
while (j<=i)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
{
fact*=j;
j++;
}
printf("\tX^%d/%ld\t+",i,fact);
i*=2;
}
getch();
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …161 162 … A Complete Refresh Manual of C Programming

2.6 Nested Loop 2.7 C Programmings - 4 (Nested Loop)


1 What is a nested loop ? Explain. 1. Write a program to print multiplication table of first 10 natural
Ans: A nested loop is a loop within a loop, an inner loop within the body of number.
an outer one. What happens is that the first pass of the outer loop Ans: #include<stdio.h>
#include<conio.h>
triggers the inner loop, which executes to completion. Then the second void main()
part of the outer loop triggers the inner loop again. This repeats until {
the outer loop finishes. Of course, a break within either the inner or int i,j,c;
for(i=1;i<=10;++i)
outer loop may interrupt this process. {
Example: for(j=1;j<=10;++j)
{
for (i = 1; i < 5; ++i) c=i*j;
{ printf("%d*%d=%d\t",j,i,c);
}
for (j = 1; j < = i; ++j) printf("\n");
{ }
Outer Inner printf ("%d", i); getch();
loop loop }
}
Result:
printf ("\n"); 1x1=1 2x1=2 ………………………………..10x1=10
} 1x2=2 2x2=4 ………………………………..10x2=20
Example: 1x3=3 2x3=6 ………………………………..10x3=30
1x4=4 2x4=8………………………………….10x4=40
#include<stdio.h> 1
#include<conio.h> 22
void main() 333
{ 4444
int i,j;
55555
for(i=1;i<=5;++i)
{
for(j=1;j<=i;++j)
{
printf("%d",i);
}
printf("\n");
}
getch();
}
Result
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
1x5=5 stdio.h>
2x5=10……………… #include<conio.h>
void main()
………………...10x5=5
{
0 int i,j,f;
1x6=6 for(i=1;i<=10;++i)
2x6=12……………… {
………………...10x6=6 f=1;
0 for(j=i;j>0;--j)
1x7=7 {
2x7=14……………… f=f*j;
}
………………...10x7=7
printf(“%d=%d\n”,i,f);
0 }
1x8=8 getch();
2x8=16……………… }
………………...10x8=8
0
1x9=9
2x9=18………………
………………...10x9=9
0
1x10=10
2x10=20………………
…………….10x10=100
2. Write a program to
display factorial
number of first 10
natural number.
A
n
s
:

#
i
n
c
l
u
d
e
<
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …163 164 … A Complete Refresh Manual of C Programming


Result: {
1=1 int n,r,k,sum=0,up;
2=2 clrscr();
printf("Enter the limit of series:");
3=6 scanf("%d",&n);
4=24 up=n;
5=120
6=720 while (up>1)
7=5040 {
8=40320 k=n;
9=362880 sum=0;
while(n>0)
10=3628800
{
3. Write a program to display prime number within a given range. r=n%10;
[T.U. 2064 Jestha] sum=sum+pow(r,3);
Ans: #include<stdio.h> n=n/10;
}
#include<conio.h>
void main()
{ if(sum==k)
printf("%d\t",k);
int i,j,r1,r2;
up--;
printf(“Enter the range:”);
n=up;
scanf(“%d%d”,&r1,&r2);
}
getch();
for(i=r1;i<=r2;++i)
{ }
for(j=2;j<i;++j) Result:
{ Enter the limit of series: 500
if(i%j==0)
break; 407 371 370 153
} if(i==j)
printf("%d\t",i); 5. Write a program to generate the following:
} 1
getch(); 22
} 333
Result: 4444
Enter the range:2 500 55555
Ans: #include<stdio.h>
2 35 7 11 13 17 19 #include<conio.h>
23 29 31 37 41 43 47 53 void main()
…………………………………………………………………………………………………………….. {
…………………………………………………………………487 491 499 int i,j;
for(i=1;i<=5;++i)
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
for(j=1;j<=i;++j)
4. Write a C program to generate a series of Armstrong numbers. A {
number is an Armstrong number if the sum of the cube of its digit is printf("%d",i);
equal to the number. }
Ans: #include<stdio.h> printf("\n");
#include<conio.h> }
#include<math.h> getch();
void main() }
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …165 166 … A Complete Refresh Manual of C Programming


Result: {
1 printf("1\t");
22 }
333 printf("\n");
4444 }
55555 getch();
}
6. Write a program to display the following series : Result:
1
1
1 1
22 1 1 1
333 1 1 1 1
4444 1 1 1 1 1
55555
Ans: #include <stdio.h>
#include <conio.h> Ans: #include<stdio.h>
void main ( ) #include<conio.h>
{ void main()
int n, a, j; {
for (a = 1; a < =5; a + +) int i,j;
{ for(i=1;i<=5;++i)
for (j = 0; j < = 5-a ; j + +) {
printf (" "); for(j=1;j<=i;++j)
for (j = 1; j <=a; j + +)
printf ("%d ", a);
printf ("\n");
}
getch ( );
}
Result:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

7. Write a program to display the following:


1
1 1
1 1 1
1 1 1 1
1 1 1 1 1
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

8. Write a C Program to display the following:


[ T.U. 2063]
55555
4444
333
22
1
Ans:
#include
<stdio.h
>
#include<conio.h>
void main()
{
int i,j;
for(i=5;i>=0;--i)
{
for(j=1;j<=i;++j)
{
printf("%d",i);
}
printf("\n");
}
getch();
}
Result:
55555
4444
3
3
3
2
2
1
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
void main()
C Programming Language …167 {
9. Write a C Program to display the following: int i,j;
12345678 for(i=0;i<=4;++i)
{
2345678
for(j=1;j<=4;++j)
345678 {
45678 printf("%d\t",(i+j)*10);
5678 }
678
78
8
Ans: #include<stdio.h>
#include<conio.h>
void main()
{
int b,c;
for(b = 1; b <= 8; b++)
{
for(c = b; c <= 8; c++)
{
printf("%d", c);
}
putchar('\n');
}
getch();
}
Result:
12345678
2345678
345678
45678
5678
678
78
8

10. Write a program to display the following table:


10 20 30 40
20 30 40 50
30 40 50 60
40 50 60 70
Ans: #include<stdio.h>
#include<conio.h>
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

168 … A Complete Refresh Manual of C Programming 1


121
printf("\n"); 1 23 21
}
1 2 34 321
getch();
} 12 3 45 4321
Result: 1 23 4 56 54321
10 20 30 40 12 3 45 67 654321
20 30 40 50
30 40 50 60
40 50 60 70

11. Write a C program to display the pyramid of numbers for a given


number.
1
12 1
1 23 21
1 2 34 321
12 3 45 4321
1 23 4 56 54321
12 3 45 67 654321
Ans: #include<stdio.h>
#include<conio.h>
void main()
{
int n,a,j,k;
printf(“Enter a number to form a pyramid:”);
scanf(“%d”,&n);
printf(“\n\t\n\t”);

for (a = 1; a < =n; a + +)


{
for (j = 1; j < = n-a ; j + +)
printf(" ");
for (k=1 ; k <=a; k + +)
printf ("%d ", k);
for (k=a-1 ; k >0; k--)
printf ("%d ", k);

printf ("\n\t\t");
}
getch ( );
}
Result:
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …169 170 … A Complete Refresh Manual of C Programming


12. Write C program to produce 10 rows of the following form of 13. Write a program to display the following series
Floyd’s triangle 1
1 2 3
0 1 4 5 6
1 0 1 7 8 9 10
0 1 0 1 11 12 13 14 15 [i.e. Floyd’s Triangle]
Ans: #include<conio.h> Ans: #include<stdio.h>
#include<stdio.h> #include<conio.h>
void main() void main()
{ {
int i,j; clrscr(); int i,j=1,k;
for(i=1;i<=10;i++) for(i=1;i<=5;++i)
{ {
for(j=1;j<=i;j++) for(k=1;k<=i;j++,k++)
{ printf("%d\t",j);
printf(" "); printf("\n");
if(i%2==0) }
if(j%2==0) getch();
printf("1"); }
else OR,
printf("0"); #include<stdio.h>
else #include<conio.h>
if(j%2==0) void main()
printf("0"); {
else int i,j,sum=0;
printf("1"); for(i=1;i<=5;++i)
} {
printf("\n\n"); for(j=0;j<i;++j)
} {
getch(); sum=sum+1;
} printf("%d\t",sum);
Result: }
1 printf("\n");
01 }
10 01 01 1 0 1 getch();
10 01 10 01 1 0 1
}
10 01 10 01 10 1 0 1
101010101
0101010101
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
R
e 1
s 2 3
u 4 5 6
l 7 8 9 10
t 11 12 13 14 15
:
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …171 172 … A Complete Refresh Manual of C Programming


14. Write a program to generate a triangle as shown below for n = 4. printf("%d",j);
The program should take the input from the user. }
A printf("\n");
A B A }
A B C B A getch();
A B C D C B A (8) }
Ans: #include<stdio.h>
#include<conio.h> Result:
void main() 5
{
54
int i,j,k,ch;
clrscr(); 543
for(i=3;i>=0;i--) 5432
{
ch=65; #include<conio.h>
printf("\n\n"); void main()
{
for(j=i;j>0;j--) int i,j;
printf(" "); for(i=5;i>=0;--i)
for(k=i;k<4;k++) {
printf("%c ",ch++); for(j=5;j>i;--j)
ch-=2; {
for(j=i;j<3;j++)
printf("%c ",ch--);
for(k=i;k>0;k--)
printf(" ");
}
getch();
}
Result: A
A B A
A B C B A
A B C D C B A

15. Write a C Program to display the following:


5
54
543
5432
54321
Ans: #include<stdio.h>
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
5 12345
4 1234
3 123
2 12
1 1

16. Write a C Program to display the


following:
1
2
3
4
5
1
2
3
4
123
12
1
Ans: #include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
for(i=5;i>=0;--i)
{
for(j=1;i>=j;++j)
{
printf("%
d",j);
}
printf("\n");
}
getch();
}
Result:
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
* * * * *
ww

ww
om

om
1
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
* * * *
.

.
ac
k e r- s o ft w a 3 5 ac
k e r- s o ft w a

* * * C Programming Language …173 7 Refresh


174 … A Complete 9 11
Manual of C Programming
* * 13 15 17 19
17. Write a C Program to display the following: Result:
* 21 23 25 2

7 29
Ans: #include<stdio.h> 19. Write a program to display the following series
#include<conio.h> 1
void main() 2 3
{ 3 4 5
int i,j;
for(i=5;i>=0;--i) 4 5 6 7
{ 5 6 7 8 9
for(j=1;i>=j;++j) Ans: #include<stdio.h>
{ #include<conio.h>
printf("*\t"); void main()
} {
printf("\n"); int i,j,sum=0;
} for(i=1;i<=5;++i)
getch(); {
} for(j=0;j<i;++j)
Result: { sum=i+j;
printf("%d\t",sum);
* * * * *
* * * * }
printf("\n");
* * *
}
* *
3 5* getch();
2 3
7 9 11 } 3 4 5
18. Write a program to display the following series
13 15 17 19 Result: 4 5 6 7
1
21 23 25 27 29 15 6 7 8 9

Ans: #include<stdio.h>
#include<conio.h>
void main()
{
int i,j=1,k;
for(i=1;i<=5;++i)
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
for(k=1;k<=i;j++,k++)
printf("%d\t",j);

printf("\n");
}
getch();
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …175

2.8 Array Num[0]


Num[1]
1. What is an array ? How array can be declared? Explain with Num[2]
examples.
Ans: Array [T.U. 2066 Jestha] Num[3]
An array can be defined as a set of finite number of Num[4]
homogeneous elements or data items.It means an array can contain
one type of data only,either all integers,all characters,all floating point
etc.The individual data items are represented by their corresponding
array elements(i.e.first data item is represented by first array
element,second data item is represented by second array element and
so on). The individual array elements are distinguished from one
another by the value that is assigned to a subscript.
Example:
Marks[7];
Represents the marks of the 7th student. The complete set of
values is referred to as an array, the individual values are called
elements. The arrays can be of any variable type.
Types of arry:
• One-dimensional array
When a list of items can be given one variable name using only
one subscript and such a variable is called a single-subscripted
variable or one dimensional array.
In C language ,single-subscripted variable xi can be
represented as
x[1],x[2],x[3]……………x[n]
The subscripted variable xi refers to the ith element of x. The
subscript can begin with number 0. For example, if we want to
represent a set of five numbers, say (57,20,56,17,23), by a array
variable num, then we may declare num as follows
int num[5];
And the computer reserves five storage locations as shown
below:
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

176 … A Complete Refresh Manual of C Programming [2][0] [2][1] [2][2]


Row2 490 235 240
The values can be assigned as follows:
Row3 [3][0] [3][1] [3][2]
Num[0]=57;
240 350 480
Num[1]=20;
• Declaration and initialization of arrays:
Num[2]=56; The arrays are declared before they are used in the program.
Num[3]=17; The general form of array declaration is
Num[4]=23;

The table below shows the values that are stored in the particular
numbers.
Num[0]
Num[1]
Num[2]
Num[3]
Num[4]

57
20
56
17
23

• Two dimensional arrays: [T.U. 2060 Shrawan]


Two dimensional arrays are declared as follows:
Type array_name [row_size][column_size];
In c language the array sizes are separated by its own set of
brackets. Two dimensional arrays are stored in memory as shown in
the table below. Each dimension of the array is indexed from zero to
its maximum size minus one; the first index selects the row and the
second index selects the column within that row.

Column0 Column1 Column2


[0][0] [0][1] [0][2]
Row 0 210 340 560
[1][0] [1][1] [1][2]
Row 1 380 290 321
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …177 178 … A Complete Refresh Manual of C Programming


type variable_name[size]; The values in the list are separated by commas.
The type specifies the type of element that will be contained in For example, the statement below shows
the array, such as int,float,or char and the size indicates the maximum static int num[3]={2,2,2};
number of elements that can be stored inside the array. Will declare the variable num as an array of size 3 and will
Example: assign two to each element. If the number of values is less than the
float weight[40] number of elements, then only that many elements will be initialized.
Declares the weight to be an array containing 40 real elements. The remaining elements will be set to zero automatically.
Any subscripts 0 to 39 are valid. For example:
Similarly, static float num1[5]={0.1,2.3,4.5};
int group1[11]; Will initialize the first three elements to 0.1,2.3 and 4.5 and the
Decalres the group1 as an array to contain a maximum of 10 remaining two elements to zero. The word static used before type
integer constants. declaration declares the variable as a static variable.
The C language treats character strings simply as arrays of In some cases the size may be omitted. In such cases, the
characters. The size in a character string represents the maximum compiler allocates enough space for all initialized elements. For
number of characters that the string can hold. example, the statement
For example: static int count[ ]= {2,2,2,2};
char text[10]; Will declare the counter array to contain four elements with
Suppose we read the following string constant into the string variable initial values 2.
text. Character arrays may be initialized in a similar manner. Thus,
“HOW ARE YOU” the statement
Each character of the string is treated as an element of the array text static char name[ ]={ ‘S ‘W,’A,’N}
and is stored in the memory as follows. Declares the name to be an array of four characters, initialized
with the string “SWAN”
‘H’ There certain draw backs in initialization of arrays.
1. There is no convenient way to initialize only selected elements.
‘O’
2. There is no shortcut method for initializing a large number of
‘W’ array elements.
Reading Writing and manipulation of above types of arrays.
‘A’ Program to read and write two dimensional arrays.
#include<stdio.h>
‘R’ main()
‘E’ {
When the compiler sees a character string, it terminates it with an
additional null character. Thus, the element text[11] holds the null character
‘Y’
‘\o’ at the end. When declaring character arrays, we must always allow one
‘O’ extra element space for the null terminator.
‘U’ • Initialization of arrays:
‘\o’ The general form of initialization of arrays is:
static type array-name[size]={ list of values};
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
int a[10][10];
int i, j row,col;
printf(“\n Input row and column of a
matrix:”);
scanf(“%d %d”,
&row,&col); for(i=0;
i<row;i++)
for(j=0;j<col;j++)
scanf(“%d”,
&a[i][j]);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf(“%5d”,
a[i][j]);
printf(“\n”);
}
}
2. What are the concept remembered about arrays? Explain.
Ans: Followings are some of the concept to be remembered about
arrays:
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …179 180 … A Complete Refresh Manual of C Programming


(i) The individual element of an array can be accessed by printf ("Enter age for(i=0;i<2;++i)
specifying name of array,followed by index or subscript inside \n"); {
square brackets.Example:int a[5]; scanf ("%d", &age); for(j=0;j<2;++j)
printf ("\n Name :%s",
(ii) The first element of array has index zero[0].It means first
name); scanf(“%d”,&matrixa[i][
element and last element will be specified as a[0] and a[4] printf ("Age:%d", age); j]);
respectively. getch ( ); }
(iii) The elements of array always be stored in consecutive memory } //Displaying data
locations. for(i=0;i<2;++i)
(iv) The size of array is given by (Upperbound-lowerboiund)+1 , {
(4-0)+1=5. for(j=0;j<2;++j)
where 0=lowerbound and 4=upperbound.
printf(“%d\t”,matrixa[i
(v) Arrays can be read or written through loop.If we read a one- ][j]);
dimensional array,it requires one loop for reading and writing. }printf(“\n”);
If we are reading or writing two-dimensional array it would getch();
require two loops.Similarly array of n dimension would require n }
loops.
3. Differentiate between one-dimensional and two-dimensional array. 4. What is the difference between array and ordinary variable in C?
Ans: Differentiation between one-dimensional and two-dimensional Ans: Differences between array and ordinary variable
array: a. Array is the set of multiple values where as variable can store
single value at a time.
One-Dimensional array Two-dimensional array
b. The difference between the definition of array and ordinary
(a) Only one subscript is used in (a) Two subscript is used in
one-dimensional array two-dimensional array. variable is the, array is always declared, initialized, and
accessed using subscript whereas ordinary variable do not
(b) Syntax>data_type (b) Syntax>data_type
have any subscript.
array_name[subscript]; array_name[subscript1][subs
c. The syntax for ordinary variable definition is data_type v1,v2,
cript2];
….;
Examples: Examples:
And the syntax for array variable is data_type
char name[20]; int marks[100][5];
v1[N1],v2[N2],…; where v1,v2 are name of variable and N1,
int marks[5]; etc int matrix[5][5]; etc.
N2 are the integer constants indicating the maximum size of
array.
Here,subscript is used to denote Here,subscript1 is used to
5. What are advantages of using array? Explain.
either rows or columns. denotes rows and subscript2
Ans Advantages of array
denotes columns.
(a) An array holds elements that have the same data type.
(c) Only one loop statement is (c) Two looping statements are (b) Array elements are stored in subsequent memory locations
used to create or retrieve array used to create or retrieve
(c) Two-dimensional array elements are stored row by row in
elements. array elements,i.e.first loop
Subsequent memory locations.
for rows and second loop for (d) Array name represents the address of the starting element
columns.
(e) Array size should be mentioned in the declaration. Array size
(d)Example : Display name (d) Example : Display elements
& age of a student. must be a constant expression and not a variable.
of a matrix:
#include <stdio.h> #include <stdio.h>
#include <conio.h> #include <conio.h>
void main ( ) void main ( )
{ {
char name [20]; Int matrixa[2][2],i,j;
int age; printf(“Enter
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
(f) While declaring the 2D array, the number of columns
should be specified and its a mandatory. where as for
number of rows
there is no such
rule.
(g) An Array index by default starts from 0 and ends with
the index no. (n-1).
(h) The size of an Array can not be changed at Run Time
6. What is a string? Explain, how string is declared?
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …181 182 … A Complete Refresh Manual of C Programming


Ans: A string is a group of characters of any length. The string enclosed 7. Explain, in brief the purpose of the following string handling
within double quotation marks is known as a literal. For example, functions:
“Hello” is literal. We can use such strings in our programs to display a. strlen b. strcpy c.strcat d.strcmp
various kinds of messages on the screen. The strings can be stored and e. strrev f. strlwr g.strupr h. strncpy()
manipulated as array of characters in C and C++. The last character in Use suitable examples
a string is always ‘\0’, a null character. For example, the string Ans: String functions are:
“PROGRAM” can be stored in an array as (a) Strlen
This function counts and returns the number of characters in a
0 1 2 3 4 5 6 7 string. The length does not include a null character.
items P R O G R A M \0 Syntax: n=strlen(string);
Where n is integer variable. Which receives the value of length
The string requires total 8 locations of array item: seven for the of the string.
alphabets in the string PROGRAM and one for the null character. The Example :
array item can be declared as:
length=strlen(“Hollywood”);
char item[8]; The function will assign number of characters 9 in the string to a
integer variable length.
Other examples of array declarations are
int x[25]; /*writr a c program to find the length of the string
char name[20]; using strlen() function*/
#include < stdio.h > include < string.h >
float sal[15];
#include<conio.h> void main()
Array declarations that include the assignment of initial values are {
char name[100];
int x[5] = { 56, 42, 90, 65, 55 }; int length;
x[0] x[1] x[2] x[3] x[4] printf(“Enter the string:”);
or, char text[6] = { “today”}; gets(name);
length=strlen(name); printf(“\nNumber of
char text[6] = ‘t’ ‘o’ ‘d’ ‘a’ ‘y’ ‘\0’ }; characters in the string is=%d”,length);
{ getch();
text[0] text [1] text text text text }
[2] [3] [4] [5] Result:
or, Enter the string:Universe
int A[4][3] = { 5, 2, 7, int list[5][10] = { “Ram”, “Shyam”, “Hari”, “Gopal”,
“Rampayri” };
3, 9, 6,
1, 7, 8
9, 2, 3 };
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Number of characters in the string is=8
(b) Strcpy ( )
C does not allow you to assign the
characters to a string directly as in the statement
name=”Robert”; Instead use the strcpy(0 function
found in most compilers the syntax of the
function is illustrated below.
strcpy(string1,string2);
Strcpy function assigns the contents of
string2 to string1. string2 may be a character
array variable or a string constant.
strcpy(Name,”Robert”);
In the above example Robert is
assigned to the string called name.
Let us consider an example:
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …183 184 … A Complete Refresh Manual of C Programming


# include<stdio.h> strcmp(string1,string2);
#include<conio.h> String1 & string2 may be string variables or string constants.
#include<string.h>
void main()
String1, & string2 may be string variables or string constants some
{ computers return a negative if the string1 is alphabetically less than
char name [ ]=”National”; (d) Strcmp( )
char name1[20];
strcpy(name1, name); In c you cannot directly compare the value of 2 strings in a
printf(“\n Original string=%s”, name); condition like if(string1==string2)
printf(“\n Copied string =%s”, name1); Most libraries however contain the strcmp() function, which
getch();
} returns a zero if 2 strings are equal, or a non zero number if the strings
Result : are not the same. The syntax of strcmp() is given below:
Original string=National
Copied string= National
(c) Strcat()
when you combine two strings, you add the characters of one
string to the end of other string. This process is called concatenation.
The strcat() function joins 2 strings together. It takes the following
form strcat(string1,string2) string1 & string2 are character arrays.
When the function strcat is executed string2 is appended to string1.
the string at string2 remains unchanged.
Example
strcpy(string1,”sri”); strcpy(string2,”Bhagavan”);
Printf(“%s”,strcat(string1,string2);
From the above program segment the value of string1 becomes
sribhagavan. The string at str2 remains unchanged as bhagawan. Let
us consider an example:
# include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name [20 ]=”Sri”;
char name1[20]=”Krishna”;
printf(“Concatenate string:%s”,strcat(name,name1);
getch();
}
Result :
Concatenate string:Srikrishna
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
the second and a positive number if the string is greater than the
second. If the two strings are identical,strcmp() returns a value zero. If
they are not, it returns the numeric difference between the ASCII
values of the non-matching character.
Let us consider an example:
#include <stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[ ]=“National”;
char name1[ ]= “Open”;
if(strcmp(name,name1)==0)
printf(“Both are equal.”);
else
printf(“Not equal.”);
getch();
} Result:
Not equal.
This function takes two strings, S1 and S2 and compares them.
It returns
• A negative value if name is less than name1.
• 0 if name and name1 are equal .
• A positive value if name is greater than name1.
(e) Strrev()
This function reverses the characters in a string.
Syntax:
strrev(string);
For ex strrev(“program”) reverses the characters in a string into
“margrop”.
Let us consider an example:
#include <stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[ ]=“National”;
printf(“Reverse string=%s.”,name);
getch();
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …185 186 … A Complete Refresh Manual of C Programming


Result: (h) strncpy()
lanoitaN The strncpy() function works like the strcpy() function. As a
(f) Strlwr () function: difference, the strncpy() function allows you to specify the number of
This function converts all characters in a string from uppercase printf("\nWhat is that drink? %s" ,Drink);
to lowercase. SayItLoud = strupr(Drink);
Printf(“\nSay it loud:%s ",SayItLoud);
syntax
getch();
strlwr(string); }
For example: Result:
strlwr(“JESSICA”) converts to jessica. What is that drink? 100% Apple Juice
Let us consider an example: Say it loud: 100% APPLE JUICE
#include <stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char CustomerAddress[] = "4812 LOCKWOOD Drive #F04";
printf( "\nCustomer Address:%s ",CustomerAddress);
char *ShippingAddress = strlwr(CustomerAddress);

printf( "\nCustomer Address:%s ",ShippingAddress);


getch();
}
Result:
Customer Address: 4812 LOCKWOOD Drive #F04
Shipping Address: 4812 lockwood drive #f04
(g) Strupr() function:
This function converts all characters in a string from lower case
to uppercase.
Syntax
strupr(string);
For example strupr(“hellow”) will convert the string to HELLOW.
Let us consider an example:
#include <stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char Drink[] = "100% Apple Juice";
char *SayItLoud;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
characters that the compiler would copy from the source string. int grades[3][4];
Here The first bracket ([3]) tells the compiler that we are declaring 3
is the syntax: pointers, each pointing to an array. We are not talking about a pointer
char* strncpy(char* Destination, const char* Source, int Number);
variable or pointer array. Instead, we are saying that each element of
The Number argument specifies the number of
characters that will be copied from the Source string. Here is an the first dimension of a two dimensional array reference a
example: corresponding second dimension. In this example, all the arrays
#include <stdio.h> pointed to by the first index are of the same size. The second index
#include<conio.h>
#include<string.h>
void main()
{
char CarName1[] = "Ford Escort";
char CarName2[] = "Toyota 4-Runner";

printf(“The String Copy


Operation"); printf("\nFirst Car:
%s",CarName1); printf("\nSecond
Car:%s " , CarName2);

strncpy(CarName2, CarName1, 8);


printf("\n\nAfter using strncpy()for
8 characters");
printf("\nFirst Car:%s
",CarName1); printf("\nSecond
Car:%s ",CarName2); getch();
}
Result:
The String Copy
Operation First Car:
Ford Escort Second
Car: Toyota 4-Runner

After using strncpy() for 8 characters


First Car: Ford Escort
Second Car: Ford Esc-Runner
8. What do you understand by row-major order and
column-major order of arrays? Derive their formulae for
calculating the address of an array element in terms of the
row-number, column-number and base address of array.
Ans: A two dimensional array is declared similar to the way we
declare a one-dimensional array except that we specify the
number of elements
in both dimensions. For example,
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …187 The largest(a,n):


Will pass all the elements contained in the array a of size n.
can be of variable size. For example, the previous statement declares a The called function expecting this call must be defined appropriately.
two-dimensional array where there are 3 elements in the first The largest function header might look like:
dimension and 4 elements in the second dimension.
float largest(array,size)
Two-dimensional array is represented in memory in following two float array[ ];
ways: int size;
1. Row major representation: To achieve this linear
representation, the first row of the array is stored in the first
memory locations reserved for the array, then the second row
and so on.
2. Column major representation: Here all the elements of the
column are stored next to one another. In row major
representation, the address is calculated in a two dimensional
array as per the following formula
The address of a[i] [j] =base (a) + (i*m+ j) * size where
base(a) is the address of a[0][0], m is second dimension of
array a and size represent size of the data type.
Similarly in a column major representation, the address
of two dimensional array is calculated as per the following
formula
The address of a[i] [j] = base (a) + (j*n +i) * size
Where base (a) is the address of a [0] [0], n is the first
dimension of array a and size represents the size of the data
type.
9. Why ‘&’ operator is not used with array names in a scanf
statement? Explain.
Ans: In scanf() statement, the “address of” operator (&) either on the
element of the array (e.g marks[i]) or on the variables (e.g &rate) are
used. In doing so, the address of this particular array element is passed
to the scanf() function, rather then its value; which is what scanf()
requires. BUT many times the address of zeroth element (also called
as base address) can be passed by just passing the name of the array.
10. Describe about array in functions.
Ans: It is possible to pass the values of an array to a function. To pass an
array to a called function, it is sufficient to list the name of the array
without any subscripts, and the size of the array as arguments.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

188 … A Complete Refresh Manual of C Programming


The function largest is defined to take arguments , the array
name and the size of the array to specify the number of elements in the
array. The declaration of the formal argument array is made as
follows:
float array[ ];
The pair of brackets informs the compiler that the argument is
an array of numbers. It is not necessary to specify the size of the array
here.
Consider the following example:
main()
{
float large();
static float value[5]={ 3.4,-12.78,1.23,5.67,8.90};
printf(“%f \n”, large(value,5));
}
float large(x,n)
float a[ ];
int n;
{
int j;
float max;
max=a[0];
for(j=1; j<n; j++)
if(max< a[j])
max=a[j];
return(max);
}

When the function call large(value,5) is made the value of all


elements of the array value are passed to the corresponding elements
of array a in the called function. The large function finds the largest
value in the array and returns the result to the main.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
getch();
C Programming Language …189 }
2.9 C Programmings -5 Result:
Enter age of 100 persons:
34 54 12 90 …………………………….23 45
1. Write a program to display the following numbers.
3,56,76,5,90 34 54 12 90 ……………………………23 35
Ans: #include <stdio.h>
#include <conio.h>
void main ( )
{
int i,num[5]={ 3,56,76,5,90};
printf(“List of number\n”);
for(i=0;i<=4;++i)
printf(“%d\t”,num[i]);
getch();
}

Result:
List of number
3 56 76 5 90

2. Write a C program to read age of 100 person from keyboard ,display


it in proper format.
Ans: #include<stdio.h>
#include<conio.h>
void main ( )
{
int i,num[100];
//Giving input from keyboard
for(i=0;i<100;++i)
{
printf(“Enter age of 100 persons:”):
scanf(“%d”,&num[i]);
}

//Displaying age of 100 persons


printf(“List of number\n”);
for(i=0;i<100;++i)
printf(“%d”,num[i]);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Enter a number:90
190 … A Complete Refresh Manual of C Programming Enter a number:87
3. Write a C program to read 10 numbers and print them in reverse Enter a number:76
order. Enter a number:65
Ans: #include<stdio.h> The number in reverse ordr are:
65 76 87 90 69 67 65 56
#include<conio.h>
34 43
void main()
{ 4. Write a C program to calculate the average of a set of N numbers.
int num[10],i; Ans: #include<stdio.h>
for(i=0;i<10;i++) #include<conio.h>
{ void main()
printf("Enter a number:"); {
scanf("%d",&num[i]); int i,a[1000],n,sum;
} float average;
printf("The number in reverse order are:\n"); clrscr();
for(i=9;i>=0;i--) printf("How many elements you want to enter");
printf("%d\t",num[i]); scanf("%d",&n);
getch(); printf("enter values: \n");
}
Result: for(i=0;i<n;i++)
Enter a number:43 scanf("%d",&a[i]);
Enter a number:34
Enter a number:56 sum=0;
Enter a number:65 for(i=0;i<n;i++)
Enter a number:67 {
Enter a number:69
sum=sum+a[i];
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …191 192 … A Complete Refresh Manual of C Programming


printf("\nSum=%d",sum); 6. The marks obtained by a student in a 7 different subjects are entered
average=(float)sum/n; through the keyboard. The student gets a division as per the
printf("\nAverage=%.2f",average); ………………………………………….
getch(); ………………………………………….
} Enter salary:24000
Result:
How many elements you want to enter 5 Total number of employees getting salaries between
5000-10000=50
12 2 23 34 35
Sum=116
Average=23.20

5. Write a 'C' program to read salaries of 200 employees and count the
number of employees getting salary between 5000-10000.
Ans: #include <stdio.h>
#include <conio.h>
void main ( )
{
int count = 0, salary [200], i;
// Reading salary of 200 employees
for (i = 0; i < 200; i + +)
{
printf ("Enter salary :");
scanf ("%d", & salary [i]);
}
/* counting number of employees getting salary
between 5000 - 10000 */
for (i = 0; i < 200; i++)
{
if (salary [i] > 5000 && salary [i] <
10000)count++;
}
printf ("Total number of employees getting salaries
between 5000-10000 = %d", count);
getch ( );
}
Result:
Enter salary:5600
Enter salary:9000
Enter salary :4500
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
following rules : Enter mark of a subject:90
Percentage greater or equal to 60 First division Name=Yogesh
Percentage between 45 and 59 Second division Total=477.000000
Percentage=68.142860
Percentage between 35 and 44 Third division
Percentage less than 35 Fail
Write a program using C language to process result of all students
based on specification stated above.
Ans: #include <stdio.h>
#include <conio.h>
void main ( )
{
char name [20];
int i;
float x [7], per, total = 0;
printf ("Enter name =");
scanf ("%s", name);
for (i = 0; i < 7; i + +)
{
printf ("Enter mark of a subject =");
scanf ("%f", &x [i]);
total = total + x [i];
}
printf ("\n\n");
per = total/7;
printf ("Name = %s\n", name);
printf ("Total = % f\n", total);
printf ("Percentage = %f\n", per);
if (per>60)
printf ("First division\n");
else if (per > = 45)
printf ("Second division\n");
else if (per > = 35)
printf ("Third division");
else
printf ("Fail\n");
getch ( );
}
Result:
Enter name:Yogesh
Enter mark of a subject:34
Enter mark of a subject:56
Enter mark of a subject:65
Enter mark of a subject:67
Enter mark of a subject:76
Enter mark of a subject:89
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …193 194 … A Complete Refresh Manual of C Programming


First division {
7. Write a program to count and find the sum of all the numbers in the void main()
array which are exactly divisible by 7 but not by 5. {
int a[20],sum=0,i,count=0;
Ans: #include<stdio.h>
#include<conio.h> for(i=0;i<20;++i)
#define MAX 500
{
void main()
printf("Enter nos:");
{
scanf("%d",&a[i]);
int a[MAX],sum=0,i,count=0,n;
if(a[i]%2==1)
printf(“How many number?:”);
scanf(“%d”,&n);

for(i=0;i<n;++i)
{
printf("Enter number:");
scanf("%d",&a[i]);
if(a[i]%7==0 &&a[i]%5!=0)
{
sum=sum+a[i];
count=count+1;
}
}
printf("\nSum of numbers=%d",sum);
printf("Total nos stored=%d",count);
getch();
}
Result:
How many number?5

Enter number:21
Enter number:1
Enter number:7
Enter number:20
Enter number:35

Sum of numbers=28
Total nos stored=2
8. Write a program to read an array of 20 elements and find sum of
squares of odd numbers contained in the array. Also, find the
numbers of elements stored.
Ans: #include<stdio.h>
#include<conio.h>
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
count=count+1; count + +;continue;
sum=sum+a[i]*a[i]; }
} printf ("Total number of persons in the age
}
group between 50 and 60 are : %d", count);
printf("\nSum of squares of odd
nos=%d",sum); getch ( );
printf("Total nos stored=%d",count);

getch();
}
Result:
Enter nos:20
Enter nos:3
Enter nos:5
…………………………….
…………………………..
Enter nos:35
Enter nos:70

Sum of squares of odd nos=1289


Total nos stored=9

9. Write a program using C language to read the age of 100 persons


and count number of persons in the age group between 50 and 60.
Use "For" and "Continue" statements.]
Ans: #include <stdio.h>
#include <conio.h>
void main ( )
{
int age [100];
int i, count = 0;
// Reading the age of 100 persons
for (i = 0; i < 100; i + +)
{
printf ("Enter age of a person :");
scanf ("%d", & age [i]);
}
// Comparing age group between 50 & 60
for (i = 0; i < 100; i + +)
{
if (age [i] > = 50 && age [i] <=60)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …195 196 … A Complete Refresh Manual of C Programming


} scanf ("%d", &n);
Result: // Reading numbers
Enter age of a person :45 for (i = 0; i < n; i + +)
Enter age of a person :56 {
Enter age of a person :90 printf ("Enter numbers :");
………………………………………………………….. scanf ("%d", &a [i]);
………………………………………………………….. }
Enter age of a person :12
Enter age of a person :45 /* Finding the greatest and smallest
Number*/
Total number of persons in the age group between smallest number, sum and average.
50 and 60 are:23 Ans: #include <stdio.h>
10. Write a program to find whether the given number is palindrome or #include <conio.h>
not. void main ( )
Ans: #include <stdio.h> {
#include <conio.h> int n,i,max,a[100],min,sum=0 ;
void main ( ) float avg;
{ printf ("How many nos ?");
int a[10],num,i=0,result=0,n;
printf(“Enter the number:”);
scanf(“%d”,&n);
num=n;

while(num!=0)
{
result=result*10;
a[i]=num%10;
num=num/10;
result=result+a[i];
++i;
}
if(result==n)
printf(“The number is palindrome.”);
else
printf(“Not”);
getch();
}
Result:
Enter the number:121

The number is palindrome.


11. Write a 'C' program to input 'n' numbers and find out the greatest,
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
max=a[0];
min=a[0];

for (i = 0; i <n; i + +)
{
sum=sum+a[i];
if (a [i] > max)
max = a[i];
else if( a[i]<min)
min = a[i];
else
;
}
svg=sum/n;
printf ("\nThe greatest number = %d",max);
printf ("\nThe smallest number = %d",min);
printf(“\n Sum of numbers=%d”,sum);
printf(“\n Average=%.2f”,avg);
getch ( );
}

Result:
How many nos?5

Enter numbers:500
Enter numbers:5
Enter numbers:20
Enter numbers:901
Enter numbers:51

The greatest number=901


The smallest number=5
Sum of numbers=1431
Average=286.20
12. Write a program, which reads marks of N students in an array and
add a grace of 10 marks to every element of the array.
Ans: #include<stdio.h>
#include<conio.h>
void main()
{
int n,i,mark[10],sum[10];
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …197 198 … A Complete Refresh Manual of C Programming


printf("Enter how many students:"); {
scanf("%d",&n); temp = a[i];
printf("\n\n"); a [i] = a[j];
a [j] = temp;
for(i=0;i<n;i++) }
{ }
printf("Enter mark:"); }
scanf("%d",&mark[i]); printf ("Sorted array\n");
sum[i]=mark[i]+10; for (i = 0; i < n; i ++)
} printf ("%d\t", a[i]);
printf("\n\n"); getch ( );
printf(“After adding grace marks 10 are:\n”); }
Result:
for(i=0;i<n;i++) How many numbers ?5
printf("%d\t",sum[i]); Enter numbers =76
getch(); Enter numbers =3
} Enter numbers =80
Result: Enter numbers =5
Enter how many students:5 Enter numbers =1
Enter mark:45
Enter mark:54 Sorted array
Enter mark:78 3 5 76 80
Enter mark:82
Enter mark:23 14. Write a program to generate fibonacci series using array up to nth
After adding grace marks 10 are: terms.
55 64 88 92 33 Ans: #include<stdio.h>
scanf ("%d",& a [i]);
13. Write a program to enter ’n’ numbers into one dimensional array }
and sort and display them in ascending order.
[T.U. 2063 Baisakh]
Ans: #include <stdio.h>
#include <conio.h>
#define MAX 500
void main ( )
{
int a [MAX], i, j, n, temp;
printf ("How many numbers ?");
scanf ("%d", &n);
// Entering set of numbers
for (i = 0; i <n; i + +)
{
printf ("Enter numbers =");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
#include<conio.h> for(i=2;i<=n;++i)
void main() {
{ a[i]=a[i-2]+a[i-1];
int a[100],i,n; printf("Enter } for(i=0;i<=n;++i)
number:"); scanf("%d",&n); printf("%d\t",a[i]);
a[0]=0; getch();
a[1]=1; }
// sorting in ascending order Result:
for (i = 0; i < n; i + +) Enter number:5
{
for (j = i+1; j < n; j + +) 0 1 1 2 3 5
{
if (a [i] > a [j])
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …199 200 … A Complete Refresh Manual of C Programming


15. Write a program to read a set of ’n’ numbers from the standard 16. Write a C program to insert an element in the array.
input device and to sort them in descending order. Ans: #include<stdio.h>
Ans: #include <stdio.h> #include<conio.h>
void insert(int n[],int,int,int);
#include <conio.h>
int num,len,pos,a;
void main ( ) void main()
{ {
int a [100], i, j, n, temp; int n[100];
printf ("How many numbers ?"); printf("Enter data to be read:");
scanf ("%d", &n); scanf("%d",&len);
printf("Enter integers:");
// Entering set of numbers for(a=0;a<=len-1;++a)
{
for (i = 0; i <n; i + +)
scanf("%d",&n[a]);
{ }
printf ("Enter numbers ="); printf("Enter integer to be inserted:");
scanf ("%d" ,&a [i]); scanf("%d",&num);
} printf("Enter position in the array
forinsertion:");
// sorting in ascending order scanf("%d",&pos);
--pos;
for (i = 0; i < n; i + +)
insert(n,len,pos,num);
{ getch();
for (j = i+1; j < n; j + +) }
{ void insert(int n[],int,int,int)
if (a [i] < a [j]) {
{ for(a=len;a>=pos;--a)
temp = a[i]; {
a [i] = a[j]; n[a+1]=n[a];
a [j] = temp; }
} n[pos]=num;
if(pos>len)
}
{
}
printf("Insertion outside the array.");
}
printf ("Sorted array\n"); Enter numbers=1
for (i = 0; i < n; i ++) Enter numbers=5
printf ("%d\t", a[i]); Enter numbers=89
getch ( ); Enter numbers=76
}
Result: Sorted array
How many numbers 5 89 76 56 5 1
Enter numbers=56
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
len++;
printf("New array\n");
for(a=0;a<len;++a)
{
printf("%d\t",n[a]);
}
}
Result:
Enter data to be read:5
Enter integer:10
11
12
13
14
Enter integer to be inserted:5
Enter position in the array for
insertion:3
New array
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
13
C Programming Language …201 14
10 11 12 5 13 14 Enter position to delte element:2
17. Write a C program to delete an element in an array. New array
Ans: #include<stdio.h> 10
11
#include<conio.h> 13
void del(int num[],int,int); 14
int n,a;
void main()
{
int num[100],pos;
printf("How many elements in the array?:");
scanf("%d",&n);
printf("Enter integers:");
for(a=0;a<=n-1;++a)
{

scanf("%d",&num[a]);
}
printf("Enter position to delte element:");
scanf("%d",&pos);
del(num,pos,n);
getch();
}
void del(int num[],int pos,int n)
{
int j,item;
item=num[pos];
for(j=pos;j<=n-1;++j)
{
num[j]=num[j+1];
}
n=n-1;
printf("New array.\n");
for(a=0;a<=n-1;++a)
printf("%d\n",num[a]);
}
Result:
How many elements in the array?:5
Enter integer:10
11
12
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

202 … A Complete Refresh Manual of C Programming students and prints them in tabular format.
Ans: #include<stdio.h>
#include<conio.h>
18. Write a program to search a number from the list of N numbers. void main()
You should read the number to be searched from the user. {
[T.U. 2066 Jestha] char name[10][10];
Ans: #include<stdio.h> int mark[10],i;
#include<conio.h>
void main() for(i=0;i<10;i++)
{
int a[100],i,n,x,flag=0;
printf("How many numbers:");
scanf("%d",&n);
for(i=0;i<n;++i)
{
printf(“Enter numbers:”):
scanf(“%d”,&a[i]);
}
printf(“Enter the number to searched:”);
scanf(“%d”,&x);
for(i=0;i<n;++i)
{
if(x==a[i])
{
printf(“Number found”):
flag=1;
break;
}
}
if(flag==0)
printf(“Number not found”);
getch();
}
Result:
How many numbers: 5
Enter numbers=56
Enter numbers=1
Enter numbers=5
Enter numbers=89
Enter numbers=76

Enter the number to searched:5


Number found
19. Write a C program that reads name and mark of 10 different
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …203 204 … A Complete Refresh Manual of C Programming


{ break;
printf("Enter name:"); sum+=value[i];
scanf("%s",&name[i]); n+=1;
printf("Enter mark:"); }
scanf("%d",&mark[i]); mean=sum/(float)n;
} for(i=1;i<=n;i++)
printf("\nName\tMark\n"); sum=sumsqr=n=0;
printf("\n------\t------\n"); clrscr();
for(i=0;i<10;i++) printf("\n Input values : input -1 to end
printf("%s\t%d\n",name[i],mark[i]); \n");
getch(); for(i=1;i<MAXSIZE;i++)
} {
Result: scanf("%f",&value[i]);
Enter name:Mahesh if(value[i]==-1)
Enter mark:400
Enter name:Ram
Enter mark:360
……………………………………..
…………………………………………
Enter name:Manish
Enter mark:410

Name Mark
Mahesh 400
Ram 360
………………………………………
………………………………………
Manish 410

20. Write a C program to calculate the standard deviation of an array of


values. The array elements are read from the terminal. Use
functions to calculate standard deviations and mean Standard
Deviation
Ans: #include<math.h>
#include<conio.h>
#include<stdio.h>
#define MAXSIZE 100
void main()
{
int i,n;
float value[MAXSIZE],deviation,sum,sumsqr,
mean,variance,stddeviation;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
{
deviation=value[i]-mean;
sumsqr+=deviation*deviation;
} variance=sumsqr/(float)n;
stddeviation=sqrt(variance);
printf("\n Number of items : %d\n",n);
printf(" Mean : %f\n",mean);
printf("Standard Deviation :%f\n",
stddeviation);
getch();
}

Result:
Input values : input -1 to end
2
3
8
78
-1

Number of items:4
Mean:22.750000
Standard Deviation:31.979486

21. Write a program that reads two matrices A[ ] m x n and B[ ] m x n and


compare them for equality.
Ans: #include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
int matA[10][10],matB[10][10],i,j,m,n;

printf("Enter the order of matrix:");


scanf("%d%d",&m,&n);

printf("Enter the elements of first matrix:\n");


for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
scanf("%d",&matA[i][j]);
}
printf("Enter the elements of second matrix:");
for(i=1;i<=m;i++)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …205 206 … A Complete Refresh Manual of C Programming


{ {
for(j=1;j<=n;j++) printf(“%d\t”,a[i][j]);
scanf("%d",&matB[i][j]); }
} printf(“\n”);
}
for(i=1;i<=m;i++) getch ( );
{ }
for(j=1;j<=n;j++) Result:
{ Display contents of a matrix:
if(matA[i][j]==matB[i][j]) 1 23
{ 4 56
printf("They are equal matrix."); 7 89
getch();
exit(0);
} 23. Write a program to obtain transpose of a 3X 3 matrix.
else Ans: #include <stdio.h>
{
printf("Not equal"); #include <conio.h>
} void main ( )
} {
} int mat[3] [3], i, j;
printf("They are equal matrixes."); int i, j;
getch(); int a[m][n]={ {1,2,3},
} {4
,5
Result:
Enter the order of matrix: 2 2 ,6
Enter the elements of first matrix:1 },
2 {
3 7
4 ,
Enter the elements of aecond matrix:1 8
2 ,
3 9
4 }
They are equal matrices. }
;
22. Write a program to display a square matrix. printf(“Display contents of a
Ans: #include<stdio.h> matrix:\n”);
#include<conio.h> for (i = 0; i <m; i++)
#define m 3 {
#define n 3 for (j = 0; j <
void main ( ) n; j++)
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
// Entering elements of a matrix
Printf(“Enter elements of a matrix:”): for (i
= 0; i <3; i + +)
{
for (j = 0; j < 3; j + +)
scanf ("%d", & mat [i] [j]);
}
printf ("\nThe entered matrix is\n");
// The entered matrix is
for (i = 0; i <3; i + +)
{
for (j = 0; j <3; j + +)
printf ("%d \t", mat [i] [j]);
printf ("\n");
}
// Finding transpose
Printf(“The transepose of a matrix
is\n”):
for (j = 0; j < 3; j + +)
{
for (i = 0; i <3; i + +)
printf ("%d \t", mat [i] [j]);
printf ("\n");
}
getch ( );
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …207 208 … A Complete Refresh Manual of C Programming


Result: Result:
Enter elements of a matrix: else
1 sum2=sum2+a[i][j];
2 }
3
4 }
5 printf("Total of element above
6 %d\n",sum1); printf("total of
7 element below %d",sum2); getch();
8 }
9
The entered matrix is
1 23
4 56
7 89
The transepose of matrix is
1 47
2 58
3 69

24. Write a program to find sum of elements above and below the
diagonal element.
Ans: #include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],i,j,sum1=0,sum2=0;
// Entering the elements of matrix
printf("Enter the elements of matrix =");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
scanf ("%d", &a [i] [j]);
}
for (i = 0; i < 3; i ++)
{
for (j = 0; j < 3; j ++)
{
if(i>j)
sum1=sum1+a[i][j];
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Enter elements of a matrix=1 Result:
2 1 00
3 0 10
4 0 01
5
6
7
8
9
Total of element above:19
Total of element below:26
25. Write a program to convert square matrix into a unit matrix.
Ans: #include<stdio.h>
#include<conio.h>
#define m 3
#define n 3 void
main ( )
{
int i, j;
int a[m][n]={ {1,2,3},
{4,5,6},
{7,8,9}
};

for (i = 0; i <m; i++)


{
for (j = 0; j < n; j++)
{
if(i==j)
a[i][j]=1;
else
a[i][j]=0;
}
}
for (i = 0; i <m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
getch ( );
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …209 210 … A Complete Refresh Manual of C Programming


26. Write a C program to read elements of any two matrices and sum of Result:
them. Enter the elements of matrix A=1
2
Or, Write a program to add two matrices. 3
Or, Write a program that reads two matrices A[ ] m x n and B[ ] m x n, 4
add them as C (i, j) = A (i, j) + B (i, j) and prints the result in matrix 5
form. 6
7
Ans: #include <stdio.h> 8
#include <conio.h> 9
void main ( ) Enter the elements of matrix A=1
{ 2
3
int a[3][3], b[3][3], c[3] [3], i, j;
4
// Entering the elements of matrix A 5
Printf("Enter the elements of matrix A=”); 6
for (i = 0; i < 3; i + +) 7
{ 8
9
for (j = 0; j < 3; j + +)
scanf ("%d", &a [i] [j]); 2 46
} 8 10 12
14 16 18
// Entering the elements of matrix B
printf ("Enter elements of matrix B ="); 27. Write a C program to subtract matrix B from A.
for (i = 0; i < 3; i + +) Ans: #include <stdio.h>
#include <conio.h>
{
void main ( )
for (j = 0; j < 3; j + +) {
scanf ("%d", &b[i] [j]); int a[3][3], b[3][3], c[3] [3], i, j;
} // Entering the elements of matrix A
Printf("Enter the elements of matrix A=”);
// Finding sum of matrices for (i = 0; i < 3; i + +)
{
for (i = 0; i < 3; i + +)
for (j = 0; j < 3; j + +)
{ scanf ("%d", &a [i] [j]);
for (j = 0; j <3; j + +) }
c [i] [j] = a[i] [j] + b[i] [j]; // Entering the elements of matrix B
} printf ("Enter elements of matrix B =");
for (i = 0; i < 3; i + +)
{
// Printing the results
for (j = 0; j <3; j + +) printf
for (i = 0; i <3; i + +)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
("%d\t", c[i][j]); printf {
("\n"); for (j = 0; j < 3; j + +)
} scanf ("%d", &b[i] [j]);
}
getch ( );
} // Finding subtraction of matrices
for (i = 0; i < 3; i + +)
{
for (j = 0; j <3; j + +)
c [i] [j] = a[i] [j] - b[i] [j];
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
i,j,k,l,d;
C Programming Language …211
// Printing the results printf("Enter the order of 1st matrix:");
Printf(“The result is\n”); scanf("%d%d",&m,&n);
for (i = 0; i <3; i + +)
{ printf("Enter the element of first matrix:-------
for (j = 0; j <3; j + +) \n");
printf ("%d\t", c[i][j]); for(i=1;i<=m;i++)
printf ("\n"); {
}
getch ( );
}
Result:
Enter the elements of matrix A=9
9
9
9
9
9
9
9
9
Enter the elements of matrix A=1
1
1
1
1
1
1
1
1
The result is
8 88
8 88
8 88
28. Write a program that reads two matrices A[ ] m x r and B[ ] r x n
and prints the result of the product of two matrices such that C[ ]
m x n = A[ ] m x r * B[ ] r x n.
Ans: #include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a[10][10],b[10][10],c[10][10],m,n,
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
printf("\n");
212 … A Complete Refresh Manual of C Programming }
for(j=1;j<=n;j++) getch();
scanf("%d",&a[i][j]); }
}
printf("\n\n");

printf("Enter the order of 2nd matrix:");


scanf("%d%d",&l,&d);

printf("Enter the element of second matrix:--------


-\n");
for(i=1;i<=l;i++)
{ for(j=1;j<=d;j++)
scanf("%d",&b[i][j]);
}
printf("\n\n");

printf("The first matrix is------------\n");


for(i=1;i<=m;i++)
{ for(j=1;j<=n;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
printf("\n\n");
printf("The second matrix is----------\n");
for(i=1;i<=l;i++)
{ for(j=1;j<=d;j++)
printf("%d\t",b[i][j]);
printf("\n");
}
printf("\n\n");

for(i=1;i<=m;i++)
{
for(j=1;j<=d;j++)
{
c[i][j]=0; for(k=1;k<=l;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
printf("The resultant matrix is---\n");
for(i=1;i<=m;i++)
{
for(j=1;j<=d;j++)
printf("%d\t",c[i][j]);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …213 214 … A Complete Refresh Manual of C Programming


Result: for(i=1;i<=m;i++)
Enter the order of 1st matrix:2 2 {
Enter the element of first matrix:--- for(j=1;j<=n;j++)
1 printf("%d\t",mat[i][j]);
2 printf("\n");
3 }
4 printf("\n\n");
Enter the order of end matrix:2 2
Enter the element of second matrix:---
1
2
3
4
The first matrix is---------
1 2
2 4
The second matrix is---------
1 2
2 4
The resultant matrix is------
7 10
5 22
29. Write a program which finds row sum and column sum of a matrix
A[ ]m x n and prints the matrix along with row sum and column sum.
Ans: #include<stdio.h>
#include<conio.h>
void main()
{
int mat[10][10],m,n,i,j,rsum[10],csum[10];

printf("Enter the order of matrix:");


scanf("%d%d",&m,&n);
printf("\n");

printf("Enter the element of matrix-----\n");


for(i=1;i<=m;i++)
{ for(j=1;j<=n;j++)
scanf("%d",&mat[i][j]);
}
printf("\n");

printf("The entered matrix is------\n");


for(i=1;i<=m;i++)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
{ void main()
rsum[i]=0; {
for(j=1;j<=n;j++) int mat[10][10],n,i,j,flag;
rsum[i]=rsum[i]+mat[i][j];
printf("%d\n",rsum);
}

for(j=1;j<=n;j++)
{ csum[j]=0;
for(i=1;i<=m;i++)
csum[j]=csum[j]+mat[i][j];
}

printf("The matrix with row and colomn sum is- ----


---\n");
for(i=1;i<=m;i++)
{ for(j=1;j<=n;j++)
printf("%d\t",mat[i][j]);
printf("%d\n",rsum[i]);
} for(j=1;j<=n;j++)
printf("%d\t",csum[j]);
getch();
}

Result:
Enter order of matrix:2
2
Enter the element of matrix-----
1
2
3
4
The entered matrix is-----
1 2
3 4
The matrix with row and colomn sum is- ----
1 2 3
3 4 7
4 6

30. Write a program to find whether a matrix is upper triangle or not. A


matrix is said to be upper triangle matrix only when its elements
below the diagonal elements are same.
Ans: #include<stdio.h>
#include<conio.h>
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …215 216 … A Complete Refresh Manual of C Programming


{
printf("Enter the order of matrix:"); for(j=0;j<=n-1;j++)
scanf("%d",&n); scanf("%d",&mat[i][j]);
printf("\n"); }

printf("Enter the element of matrix-----\n"); flag=1;


for(i=0;i<=n-1;i++)
{ for(i=0;i<=n-1;i++)
for(j=0;j<=n-1;j++) {
scanf("%d",&mat[i][j]); for(j=i+1;j<=n-1;j++)
} {
if(mat[i][j]-mat[i][j]!=0)
flag=1; flag=0;
for(i=0;i<=n-2;i++) break;
{ }
for(j=i+1;j<n;j++) }
{ int mat[10][10],n,i,j,flag;
if(mat[i][j]!=0)
flag=0; printf("Enter the order of matrix:");
break; scanf("%d",&n);
} printf("\n");
}
if(flag) printf("Enter the element of matrix-----\n");
printf("Upper triangle matrix"); for(i=0;i<=n-1;i++)
else
printf("Not upper triangular matrix.");
getch();
}
Result:
Enter order of matrix:2
Enter the element of matrix--------
1
2
3
4
Not upper triangular matrix.

31. Write a program to input a matrix, determine if it is symmetrical


matrix. A matrix is said to be symmetrical if A=A’.
Ans: #include<stdio.h>
#include<conio.h>
void main()
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
if(flag)
printf("Symmetric matrix");
else
printf("Not symmetric matrix.");
getch();
}
Result:
Enter order of matrix:2
Enter the element of matrix--------
1
2
3
4
Symmetric matrix.
32. Write a program to compute the determinant of a square matrix of
nth order and then check whether the given matrix is singular or
not. You need to have two function as read() and process().
[T.U. 2065 Shrawan]
Ans: #include<stdio.h>
#include<conio.h>
int check(float [][],int);
float process(float[][],int);
void read(float[][],int);
void main()
{
float a[10][10],value;
int i,j,order;
printf(“Enter order of determinant:”0;
scanf(“%d”,&order);
read(a,order);
if(check(a,order==0)
value=0;
else
value=process(a,order);
printf(“Determinant value:%f”,value);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …217 218 … A Complete Refresh Manual of C Programming


if(value==0) k=j;
printf(“Matrix is singular”); for(i=0;i<forder;++i)
else {
printf(“Matrix is not singular”); if(array[i][j]==0)
getch(); {
} for(i=0;i<forder;++j)
void read(float [][],int order) {
{ if(array[i][j]!=0)
int I,j; {
for(i=0i<order;++j)
{
for(j=0;jorder;++j)
{
printf(“Enter elements:”0;
canf(“%d”,&a[i][j]);
}
}
}
float process(float a[][],int order)
{
int I,j,k;
float mul,det=1;
for(i=0;i<forder;++i)
{
for(j=0;j<forder;++j)
{
mult=a[j][i]/a[i][i];
for(k=0;k<forder;++k)
{
if(i==j)
break;
a[j][k]=a[j][k]-a[i][k]*mult;
}
}
}
for(i=0;i<forder;++i)
det=det*a[i][j];
}
return(det);
}
int check(float array[][10],int order)
{
int i,j,k;
float nonzero;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
b elements in ascending order using a function.
r Ans: #include<stdio.h>
e #include<conio.h>
a #define MAX 100
k int a[MAX];
; void main ( )
} {
i void input( ); // function declaration
f input( );
( getch( );
j }
= void input ( )
= {
( void output (int a [ ], int n);
f int sort (int a [ ], int n);
o int a [MAX];
r int n;
d printf ("How many nos ?");
e scanf ("%d", &n);
r // Entering elements of array
) printf ("Enter elements \n");
) for(int i = 0;i<n;i++)
r {
e scanf ("%d", &a[i]);
t }
u printf ("Unsorted array\n");
r output (a, n);
n sort (a, n);
printf ("Sorted array \n");
0 output (a, n);
; }
} void output (int a[ ], int n)
{
for(j=0;j<forder;++j) printf ("\n");
{ for (int i=0;i<n;i++)
array[i][j]=array[j
][i]-array[j][k];
}
}
}
return 1;
}
33. Write a program to read a set of numbers from
keyboard and to sort out the given array of
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …219 220 … A Complete Refresh Manual of C Programming


{ }
printf ("%d\t", a[i]); Result:
} Enter value of n:5
} Enter number= 900 3 45 9 10
int sort (int a[ ], int n)
{ Maximum no=900
int temp;
for(int i=0;i<n;++i)
{
36. Read the maximum and minimum temperature of 7 days of
for(int j =i+1;j<n;++j) Kathmandu Valley and creates a function to calculate minimum and
if (a[i]>a[j]) maximum temperature, also find the average temperature.
{ Ans: #include<stdio.h>
temp = a [i]; #include<conio.h>
a [i] = a[j]; int maximum (int max[7]);
a [j] = temp; int minimum (int min[7]);
} void main ( )
} {
} int maxm [7], minm [7];
Result: int avgmaxm=0,avgminm=0,avg, maxtemp,
How many nos ?5 void arrayfunction(int x[],int n)
Enter elements {
900 1 5 78 9 int j,max=0;
Unsorted array for(j=0;j<n;j++)
900 1 5 78 9 {
Sorted array if(x[j]
1 59 78 900 >max)
max=
35. Write a C program to pass ‘n’ different numbers to the function x[j]
named “array function”, find maximum number among them . ;
}
Ans: #include<stdio.h> printf("maximum no:%d\t",max);
#include<conio.h>
void arrayfunction(int[],int);
void main()
{
int i,a[100],n;
printf("Enter value of n:");
scanf("%d",&n);
printf("Enter number=");
for(i=0;i<n;++i)
scanf("%d",&a[i]);
arrayfunction(a,n);
getch();
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

mintemp,i;
printf ("Enter temperature \n");
for (i = 0; i < 7; i ++)
{
printf ("Maximum temperature of day
%d=",i + 1);
scanf ("%d", &maxm[i]);
printf ("Minimum temperature of day
%d=",i + 1);
scanf ("%d", &minm[i]);

avgmaxm = avgmaxm + maxm [i];


avgminm = avgminm + minm [i];
}
maxtemp = maximum(maxm);
mintemp = minimum(minm);

printf ("\n maximum temperature : %d",


maxtemp);
printf ("\n minimum temperature : %d",
mintemp);
avg = (avgmaxm + avgminm)/2;
printf (" \n average temperature :
%d",avg);
getch ( );
}
int maximum (int max[7])
{
int i, maxt;
maxt = max[0];
for (i = 0; i <7; i ++)
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …221 222 … A Complete Refresh Manual of C Programming


if(max[i]>maxt) getch ( );
maxt = max[i]; }
} void check (int n)
return maxt; {
} if (n% 2 == 0)
int minimum (int min [7]) printf ("Even");
{ else
int i, mint; printf ("odd");
mint = min [0]; }
for (i = 0; i < 7; i ++)
{ Result:
if (min[i]<mint) Enter 1 number :34
mint = min[i]; Even
} Enter 2 number :5
return mint; Odd
} Enter 3 number :90
Result: Even
Maximum temperature of day=20 Enter 4 number :7
Maximum temperature of day=5 Odd
Minimum temperature of day=21 Enter 5 number :13
Minimum temperature of day=34 Odd
Maximum temperature of day=54
Minimum temperature of day=56
Maximum temperature of day=65 38. Write a program to enter first name, last name and telephone number
Minimum temperature of day=56 between 20000 - 799999 of 5 different students and print them in
Maximum temperature of day=76 tabular form.
Minimum temperature of day=9
Maximum temperature of day=45 Ans: #include <stdio.h>
Minimum temperature of day=12 #include <conio.h>
Maximum temperature of day=12 void main ( )
Minimum temperature of day=-1 {
int i, num [5];
Maximum temperature:76 // Entering 5 different
Minimum temperature:-1 numbers
Average temperature:232 for (i = 0; i < 5; i ++)
{
printf ("Enter %d number :\n", i +
37. Design a program to enter 5 different numbers in array variable and 1);
find out whether individual number is even or odd. scanf ("%d \n", &num[i]);
Ans: #include<stdio.h> check (num[i]);
#include<conio.h> }
void check (int n);
void main ( )
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
char fname [5] [15], lname [5] [15];
int phone [5], i;
// Entering data
for (i = 0; i < 5; i + +)
{
printf ("\nEnter first name:");
scanf ("%s", fname [i]);
printf ("\nEnter last name:");
scanf ("%s", lname [i]);
do
{
printf ("\nEnter phone number : \n");
scanf ("%d", &phone [i]);
}
while (phone [i] < 20000 || phone [i] >
799999);
printf ("\n\n");
}
// printing in tabular form printf ("\n
First name \t last name \t phone number \n");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
sentence : %d", count);
C Programming Language …223
getch ( );
printf(" .....\t ....\t ...........\n"); }
for (i = 0; i < 5; i + +) Result:
printf ("%s \t% s \t% d \n", fname [i], We are a student.
lname [i], phone [i]);
getch ( ); Total no.of alphabet ‘a’ occurred in a sentence:2
}
Result:
Enter first name:Ramesh
Enter last name: Thapa
Enter phone number:2525
Enter phone number:34345
……………………………………………………………
……………………………………………………………
……………………………………………………………
Enter first name:Niruta
Enter last name: Thapa
Enter phone number:63525

First name last name phone number


…………………………………………………………………………………………………………………
Ramesh Thapa 34345
……………… …………….. ……………..
Niruta Thapa 63525

39. Write a program to enter a string and count total number of


alphabet "A" occurred in the string.
Ans: #include<stdio.h>
#include<conio.h>
void main ( )
{
char sen [50];
int count = 0,i;
printf ("Enter a sentence:");
gets (sen);
// Counting total member of A
for (i=0; sen[i]!=’\0';i++)
{
if(sen[i]== 'A' || sen[i]=='a')
count = count + 1;
}
printf ("Total no. of alphabet ‘a’ occured in a
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
else if (str [i] >= 97 && str [i] <123)
224 … A Complete Refresh Manual of C Programming {
40. Write a program to read a line and replace space by "*". str [i] = str [i] - 32;
Ans: #include <stdio.h> printf("%c",str[i]);
#include <conio.h> }
void main ( ) else;
{ }
char line [20]; getch ( );
int i; }
printf ("Enter a line :");
gets (line);
// Replacing space by *
for (i = 0; line [i]! ='\0'; i++)
{
if (line[i]= =' ' ||line[i]==’\t’)
line[i]='*';
printf(“%c”,line[i]);
}
getch ( );
}
Result:
Enter a line:We are student of engineering.

We*are* student*of*engineering.

41 . Write a program to enter a string and convert it into uppercase and


vice-versa.
Ans: #include<stdio.h>
#include<conio.h>
void main ( )
{
char str [40];
int i;
printf ("Enter a string :");
gets(str);
/* Converting uppercase to lowercase &
vice Versa*/
for (i = 0; str[i]!='\0'; i++)
{
if (str [i] >= 65 && str [i] < 97)
{
str [i] = str [i] + 32;
printf("%s",str[i]);
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …225 226 … A Complete Refresh Manual of C Programming


Result: char sen[100],sen1[100];
Enter a string:universe int i,k,j=0;

UNIVERSE printf(“Enter a word:”);


scanf(“%s”,sen);
42. Write a C program that reads the text and counts all occurrences of
a particular word. (6) k=strlen(sen);
Ans: #include<string.h> for(i=0;i<k;++i)
#include<stdio.h> {
#include<conio.h> if(sen[i]>=’a’ && sen1[i]<=’z’||
void main() sen[i]>=’A’ && sen[i]<=’Z’)
{ {
char a[100],b[20],c[20]; sen1[j]=sen[i];
int i,count=0,k=0,len; j++;
clrscr(); }
printf ("\nEnter a string:-> "); }
gets(a); sen1[j]=’\0’;
printf("\nEnter the word to be searched:->"); printf(“After filtration the new string
gets(b); is %s\n:”,sen1);
len=strlen(a); getch();
for(i=0;i<=len;i++) }
{
/*Assuming Space , Tab and NULL as word separator*/ Result:
if(a[i]==32 || a[i]=='\t' || a[i]=='\0') Enter a word:Hell23ow
{ c[k]='\0';
if(strcmp(b,c)==0)count++; After filtration the new string is
k=0;
Hellow
} Occurance of is is =1
else
{ 43. Write a program to filter only the alphabets from a string and store
c[k]=a[i]; them in another string.
k++;
Ans: #include<stdio.h>
}
#include<conio.h>
}
#include<string.h>
printf("Occurance of %s is = %d",b,count);
void main()
getch();
{
}

Result:
Enter a string:->Computer is an electronic device
Enter the word to be searched:->is
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

44. Input names of 'n' number of students and sort them in alphabetical
order. [T.U. 2066 Jestha]
Ans: #include<stdio.h>
#include<conio.h>
#include<string.h>
void main ( )
{
char name [100] [100], temp[100];
int i, j, n;
printf ("Enter number of students =");
scanf ("%d",&n);
// Data putting for n students
for (i = 0; i < n; i ++)
{
printf ("Enter name :");
scanf ("%s", name [i]);
fflush (stdin);
}
// sorting methods
for (i = 0; i<n; i ++)
{
for (j = i+ 1; j < n; j ++)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …227


printf("Enter name and address:\n");
{ for(i=0;i<5;i++)
if (strcmpi(name[i],name [j]) > 0) scanf("%s%s",name[i],add[i]);
{
strcpy (temp,name [i]);
for(i=0;i<5;i++)
strcpy (name [i], name [j]);
strcpy (name [j], temp); {
} for(j=i+1;j<5;j++)
}
}

// Printing sorted list in alphabetical order


printf(“\n”):
for (i = 0; i < n; i ++)
{
printf ("%s\n", name[i]);
}
getch ( );
}
Result:
Enter number of students =5
Enter name:Umesh
Enter anme:Om
Enter name:Amar
Enter name:kamal
Enter anme:Janak

Amar
Janak
Kamal
Om
Umesh

45. Write a C program to read name and address of 5 different students,


sort them in alphabetical order.
Ans: #include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[5][80],add[5][80],temp[80],
temp1[80];
int i,j;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
void main()
228 … A Complete Refresh Manual of C Programming {
if(strcmp(name[i],name[j])>0) int i,j,k,l,flag=0;
{ char a[50];
strcpy(temp,name[i]); clrscr();
strcpy(name[i],name[j]); printf("Enter the characters in the array:\n");
strcpy(name[j],temp); gets(a);
l=strlen(a);
strcpy(temp1,add[i]); for(i=0;i<l-1;i++)
strcpy(add[i],add[j]);
strcpy(add[j],temp1);
}
}
printf("The result is\n");
printf("\nName\tAddress\n");
printf("...............\n");
for(i=0;i<5;i++)
printf("%s\t%s\n",name[i],add[i]);

getch();
}
Result:
Enter name and address:
Harish LTP
Kamal PTN
Niraj BKT
Om Baneshwor
Arun Naxal

The result is
Name Address
…………………………………………………
Arun Naxal
Harish LTP
Kamal PTN
Niraj BKT
Om Baneshwor

46. Write a function to remove duplicates from an ordered array. For


example, if input is: a,a,c,d,q,q,r,s,u,w,w,w,w; then the output should
be a,c,d,q,r,s,u,w.
Ans: #include<stdio.h>
#include<conio.h>
#include<string.h>
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …229 230 … A Complete Refresh Manual of C Programming


for(j=i+1;j<l;j++) l1=len2;
{ l2=len1;
if(a[i]==a[j]) }
{ l=l-1; else
for(k=j;k<l;k++) printf("\n\n Please enter one string smaller
a[k]=a[k+1]; than the other!!!");
flag=1;
j=j-1; for(i=0;i<l1;i++)
} {
} n=i;
if(flag==0) for(j=1;j<=l2;j++)
printf("No duplicates found"); strcpy(b,str2);
else l1=len1;
for(i=0;i<l;i++) l2=len2;
printf("%c",a[i]); }
getch(); else if(len2>len1)
} {
strcpy(a,str2);
Result: strcpy(b,str1);
Enter the characters in the array :
We are student.

We arestudn.

47. Write a C program that reads two strings str1 and str2 and finds the
number of occurrence of smaller strings in large string.
Ans: #include<conio.h>
#include<string.h>
#include<stdio.h>
void main()
{
char str1[100],str2[100],a[100],b[100],c[100];
int len1,len2,l1,l2,k=0,i,j,count=0,n;
clrscr();
printf("\n Enter the first string : ");
gets(str1);
printf("\n Enter the second string : ");
gets(str2);
len1=strlen(str1);
len2=strlen(str2);
if(len1>len2)
{
strcpy(a,str1);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
c[k++]=a[n++];
c[k]='\0';
if(strcmp(b,c)==0)
++count;
k=0;
}
printf("\n The number of occurences is :
%d",count);
getch();
}
Result:
Enter the first string : We are a student.
Enter the second string:We

The number of occurences is :1

48. Write a C program to concatenate two strings without using string


function.
Ans: #include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[100],b[100],c[100];
int i=0,j=0,k;
clrscr();
printf("\nEnter the first string:");
scanf(“%s”,a);
printf("\nEnter the second string:");
scanf(“%s”,b);

i=strlen(a);
j=strlen(b);
for(k=0;k<i;k++)
c[k]=a[k];
for(k=0;k<i;k++)
c[i+k]=b[k];
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …231 232 … A Complete Refresh Manual of C Programming


c[i+j]=’\0’; 50. Write a program to input a message from keyboard and display the
printf(“The new string is %s”,c); Result:
getch(); Enter the set of lines:
} Ram is a student.
Result:
Ramisastudnet.
Enter the first string : Hellow
Enter the second string:Ram

The number of occurences is :HellowRam

49. Write a C program to read a sentence. Remove all the space and
combine all the string at one.
Ans: #include<stdio.h>
#include<conio.h>
void main()
{
char a[100],b[100];
int i=0,j=0;
clrscr();
printf("Enter the set of lines:\n");
gets(a);
while(a[i]!='\0')
{
while(a[i]!=' '&&a[i]!='\t'&&a[i]!='\0')
{
b[j]=a[i];
j++;
i++;
}
while(a[i]==' '||a[i]=='\t')
i++;
} b[j]='\0';
printf("%s",b);
getch();
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
menu scanf("%s",&str);
1. Print message length in terms of characters printf ("%s", strupr (str));
break;
2. Print the message in reverse order
case 4 :
3. Print the message in capital letters printf ("Enter a string \n");
4. Copy the message from one location of screen to another
location
5. Check the palindrome
6. Exit
Ans: #include<stdio.h>
#include<conio.h>
#include<string.h>
#include<process.h>
void main ( )
{
char str[40],dest[40],dest2[40];
int choice,l;
printf ("Main menu \n");
printf ("1. Print message length \n");
printf ("2. Print message in reverse
order\n");
printf ("3. Print the message in capital
letters \n");
printf ("4. Copy the message from one
location to another\n");
printf ("5. Check the palindrome \n");
printf ("6. Exit \n\n");
printf ("Enter your choice(1/2/3/4/5/6):");
scanf ("%d",& choice);
switch (choice)
{
case 1 :
printf("Enter a string:");
scanf("%s",&str);
l=strlen(str);
printf ("Length of message = %d",l);
break;
case 2 :
printf ("Enter a string \n");
scanf("%s",&str);
printf ("String in reverse order
\n");
printf ("%s", strrev (str));
break;
case 3 :
printf ("Enter a string \n");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …233 234 … A Complete Refresh Manual of C Programming


scanf("%s",&str); for (i = 0; i < 10; i++)
strcpy (dest, str); scanf ("%d", & num [i]);
printf ("copied string : %s", str); printf(“\n”);
break; printf ("\t\tMain menu \n");
case 5 : printf ("1. Reverse order \n");
printf ("Enter a string : \n");
printf ("2. Ascending order \n");
scanf("%s",&str); strcpy
(dest, str); strcpy(dest2, printf ("3. Descending order \n");
strrev(dest)); if (strcmp printf ("4. Exit \n");
(str, dest2) == 0) printf ("Enter your choice (1/2/3/4):");
printf ("Palindrome \n"); scanf ("%d", & ch);
else switch (ch)
printf ("Not palindrome"); {
break; case 1 :
case 6 : for (i = 9; i > 0; i -- )
exit (0); printf (" % d\t", num [i]);
default : break;
printf ("You aren't allowed to type case 2 :
others\n"); for (i =0; i <= 9; i ++)
exit (0); {
} for (j = i + 1; j <= 9; j ++)
getch ( ); if (num [i] > num [j])
} {
temp = num [i];
Result: num [i] = num [j];
Main menu num [j] = temp;
1. Print message length }
2. Print message in reverse order printf ("%d\t", num [i]);
3. Print the message in capital letters }
4. Copy the message from one break;
location to another case 3 :
5. Check the palindrome for (i = 0; i <= 9; i ++)
6. Exit {
3. Descending order
Enter your choice 1/2/3/4/5/6):2 Ans: #include<stdio.h>
Enter a string: Programming #include<conio.h>
#include<process.h>
String in reverse order void main ( )
gnimmargorp {
int i,j, num [10], ch, temp;
51. Write a menu driven program which has the following options: printf ("Enter 10 numbers \n");
1. Reverse order
2. Ascending order
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
for (j = i + 1; j <= 9; i ++)
if (num [i] < num [j])
{
temp = num [i];
num [i] = num [j];
num [j] = temp;
}
printf ("%d \t", num [i]);
}
break;
case 4 :
exit (0);
default :
printf ("\n Not allowed to type other");
exit (0);
}
getch ( );
}
Result:
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …235 236 … A Complete Refresh Manual of C Programming


Enter 10 numbers clrscr();
12 printf("enter any word:\n");
32 scanf("%s",a);
45
i=0;
67
90 while(a[i]!='\0')
93 i++;
100 k=i;
101 for(j=0;j<k/2;)
102
{
110
}
Main Menu Without using function
1.Reverse Order #include<stdio.h>
2.Ascending Order #include<conio.h>
3.Descending order void main()
4.Exit {
int i,j,k,flag=1;
Enter your choice(1/2/3/4):1
char a[20];
110 102 101 100 93 90 67 45 32 12
52. Write a program to enter a string and check whether the entered
string is palindrome or not using library function.
[Palindrome : A string is said to be palindrome if it remains same if
we reverse it. e.g. ADA, MALAYALAM]
Ans: #include <stdio.h>
#include <conio.h>
#include <string.h>
void main ( )
{
char str [30], temp [30];
printf ("Enter a string\n");
scanf ("%s", str);
strcpy (temp, str);
strrev (temp);
if (strcmp (temp, str) = = 0)
printf ("String is palindrome");
else
printf ("String is not palindrome");
getch ( );
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
if(a[j]!=a[i-1])
{
flag=0;
break;
}
if(a[j]==a[i-1])
{
j++;
i--;
}
}
if(flag==0)
printf("it is a not palindrome");
else
printf("it is a palindrome");
getch();
}
Result:
Enter a string:
ada

String is palindrome.
53. An organization has 5 stores and it deals in items. The stock position
of these items shown below :
Item 1 Item 2 Item 3 Item 4
Store 1 30 35 0 45
Store 2 24 35 12 0
Store 3 0 34 8 19
Store 4 12 0 34 18
Store 5 10 10 17 45
Develop a computer program in C to input this table and indicate the
items that are completely out of stock at store i, where the value of i
may be input from the keyboard.
Your program should calculate the total stock of each item, in the
organization and total items in store number 5.
Ans: #include <stdio.h>
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …237 238 … A Complete Refresh Manual of C Programming


#include <conio.h> Item1 Item2 Item3 Item4
#include <ctype.h> Store1 30 35 0 45
void main ( ) Store2 24 35 12 0
{ Store3 0 34 8 19
int stock [5] [4] = {30, 35, 0, 45, 24, 35,12, Store4 12
sum); 0 34 18
0, 0, 34, 8, 19, 12, 0, 34, 18, 10,10, 17, 45}; Store5 10 10
for (j = 0; j < 4; j + +) 17 45
int i, j, csum [4], sum; printf ("Total stock of item %d is %d
// Displaying items \n", j+1, csum[j]);
printf ("\t Item1 \ t Item 2\ t Item 3\ t getch ( );
Item 4\n"); }
for (i = 0; i < 5; i + +) Result:
{
printf ("Store %d \t", i + 1);
for (j = 0; j < 4; j + +)
printf ("%d\t", stock [i] [j]);
printf ("\n");
}
printf ("\n\n Enter the store no ");
scanf ("%d", &i);
i = i – 1;
for (j = 0; j < 4; j + +)
{
if (stock [i] [j] = = 0)
printf ("\n Item %d of store %d is out of
stock \n",j+1, i+1);
}
printf ("\n None of item is out of stock");
// Finding total item in columnwise
for (j = 0;j < 4; j + +)
{
csum [j] = 0;
for (i = 0; i < 5; i + +)
csum [j] = csum [j] + stock [i] [j];
}
// Finding total stock in store 5
i = 4;
sum = 0;
for (j = 0; j < 4; j + +)
sum = sum + stock [i][j];
printf (" \n Total stock in store 5 is %d\n",
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
se
ccount = ccount + 1;
}
Enter stoe no:2 lcount = ccount + vcount;
Item 4 of store 2 is out of stock.
printf ("No. of vowels = %d\n", vcount);
Total stock in store 5 is 82 printf ("No. of consonants = %d\n",
Total stock of item 1 is 76 ccount);
Total stock of item 2 is 114 printf("No. of words = %d\n", wcount + 1);
Total stock of item 3 is 71
Total stock of item 4 is 127

54. Write a program to calculate the number of vowels,


consonants, character, digits and space in a line of text.
Ans:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main ( )
{
char sen [100];
int i,
n,vcount=0,ccount=0,wcount=0,
scount=0,lcount=0;
printf ("\n Enter a sentence:\n");
gets (sen);
n = strlen (sen);

for (i = 0; i < n; i ++)


{
if(sen[i]=='a' || sen[i]=='e' || sen[i]
=='o' || sen[i]=='u' ||
sen[i]=='A' ||
sen[i]=='E' || sen[i]=='I' || sen[i]
=='O' || sen[i]=='U' || sen[i]=='i')
vcount = vcount
+ 1;
else if (sen [i]=='
'||sen[i]=='\t')
{
scount = scount + 1;
wcount = wcount + 1;
}
e
l
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …239 240 … A Complete Refresh Manual of C Programming


printf("No. of space = %d\n", scount); 1. UPPER CASE
printf("No. of letters = %d\n", lcount); 2. Sentence case
getch ( ); 3. Title Case
}
4. toGGLE cASE
Ans: #include<stdio.h>
Result: #include<conio.h>
Enter a sentence:
#include<process.h>
C is a programming language.
#include<ctype.h>
#include<string.h>
No. of vowels =9 void main ( )
No. of consonants =15 {
No. of words =5 int i, n, ch, j;
No. of space =4 char sen [50];
No. of letters =24 printf ("Enter a string : \n");
gets (sen);
55. Write a program which will ask the user to input a single character n = strlen (sen);
and then a string and will count the occurrence of that character in printf ("Main Menu : \n");
that string. printf ("1. UPPER CASE \n");
printf ("2. Sentence case \n");
Ans: #include<stdio.h> printf ("3. Title Case \n");
#include<conio.h> printf ("4. toGGLE cASE \n");
void main( ) printf ("\n\n");
{
char sen [40], ch; printf ("Enter your choice (1/2/3/4/):
int count = 0, i; \n");
printf ("Enter a sentence : \n"); scanf ("%d", &ch);
scanf ("%s", sen); switch (ch)
printf ("Enter a character \n"); {
scanf ("%c", ch);
case 1 :
/* comparing and counting the occurrence {
of entered character */ for (i = 0;i<n;i++)
for (i = 0; sen [i] ! = '\o' ; i++) {
{ sen [i] = toupper(sen[i]);
if (sen [i]==ch) printf ("%c",sen[i]);
}
count = count + 1;
}
} break;
printf ("The total number of entered character
in a sentence = %d", count); case 2:
getch ( ); {
} for(i=0;i<n;i++)
Result: sen[i]=tolower(sen[i]);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Enter a sentence : sen[0]=toupper(sen[0]);
We are a student. printf ("%s",sen);
Enter a character:e }
break;
The total number of entered character in a case 3:
sentence =3 {
for (i = 0;i<n;i++)
sen[i]=tolower(sen[i]);
56. Write a program that reads a string and prints the string in
sen[0]=toupper(sen[0]);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …241 242 … A Complete Refresh Manual of C Programming


for(i=0;i<n;i++) 57. Write a program that will print all the rotations of a word typed into
{ it. [e.g. space, paces, acesp, cespa, espac]
putsif(sen[i]=='
(sen); ')
}
Ans: #include
char<stdio.h>
name [15];
sen[i+1]=toupper(sen[i+1]); int <conio.h>
#include i, j, n;
breaelse;
; printf
#include ("Enter name :");
<string.h>
case 4: } gets ((name);
void main )
{ { n = strlen (name);
for (i = 0; i < n; i++) for (i = 0; i < n; i + +)

3. Title Case
sen [i] = toupper (sen [i]); 4. toGGLE cASE
sen [0] = tolower(sen[0]);
for (i=0;i<n;i++) Enter your choice (1/2/3/4/):
{ 1
WE ARE STUDENT.
if(sen[i]==' ')
sen[i+1]=tolower(sen[i+1]);
else;
}
puts (sen);
}
break;
default :
{
printf ("Wrong choice \n");
getch ( );
exit (0);
}
}
getch ( );
}

Result:
Enter a string :
We are student.

Main Menu
1. UPPER CASE
2. Sentence case
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
{ }
temp = name [0]; temp[j]='\0';
for (j = 0; j < n – 1; j + +) i=0,j=0;
name [j] = name [j + 1); while(str2[i]!='\0'){
name (n – 1) = temp; str1[j++]=str2[i++];
puts (name); }
printf (" \n"); str1[j]='\0';
} i=0,j=0;
getch ( );
}
Result:
Enter name: space
Space paces acesp cespa espac

58. Write a
program to swap
string.
Ans:
#include<
stdio.h>
int main()
{
int i=0,j=0,k=0;
char
str1[20],str2[20],
temp[20];
puts("Enter first
string");
gets(str1);
puts("Enter second string");
gets(str2);
printf("Before swaping the strings
are\n");
puts(st
r1);
puts(st
r2);
while(s
tr1[i]!
='\0'){
temp[j+
+]=str1
[i++];
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …243 244 … A Complete Refresh Manual of C Programming


while(temp[i]!='\0'){ char str1[20],str2[20];
str2[j++]=temp[i++]; int m,i,flag=0,j;
} clrscr();
str2[j]='\0'; printf("Enter the 1st string:");
printf("After swaping the strings are\n"); 60. Write a C program that reads two strings and copies the
puts(str1); smaller
puts(str2); string into the bigger string.
return 0;
}
(6)
59. Write a program to check whether the two strings are equal or not.
Ans: #include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20],str2[20];
int i=0,d;
clrscr();

printf("Enter the 1st string:");


gets(str1);
printf("Enter the 2nd string:");
gets(str2);
do
{
d=str1[i]-str2[i];
if(d!=0)
break;
i++;

}while(str1[i]!=0 || str2[i]!='\0');
if(d==0)
printf("Both are equal");
else
printf("Not");
getch();
}
Result:
Enter the 1st string:We
Enter the 2nd string:We

Both are equal


F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
gets(str1); }
printf("Enter the 2nd string:"); if(flag==1)
gets(str2); str1[i]='\0';
printf("%s",str1);
if(strlen(str1)<strlen(str2)) getch();
{ }
char *str; strcpy(str,str2);
strcpy(str2,str1); strcpy(str1,str); Result:
} Enter the 1st string:We
printf("Enter the index after which u want to insert Enter the 2nd string:Student
2nd string in 1st : ");
scanf("%d",&m); Enter the index after which u want to insert 2nd
i=0; string in 1st :2
while(i<=m)
{ Stuwet
i++;
} j=0; while(str2[j]!='\0')
{
str1[i]=str2[j];
i++; j++; if(str1[i]=='\0') flag=1;
Ans: #include<stdio.h> 61. Write a program that reads the name, roll number and marks in 5
#include<conio.h>
different subjects of 10 students, and prints name, roll and total
#include<string.h>
void main() marks obtained by each student in tabular form.
{ Ans: #include<stdio.h>
#include<conio.h>
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …245 246 … A Complete Refresh Manual of C Programming


void main ( ) Umesh 100 325
{
int i,j,roll[10],total[10],mark[10][5]; 62. An array J has numeric elements J(i) held in ascending order in the
char name [10] [20]; memory of computer, when J ranges from 1 to thousand (1000).
// Reading data Describe either in flowchart or write a program, if any, element has
for (i = 0; i < 10; i++) value N using method known as binary search (binary loop).
{
Ans: #include<stdio.h>
fflush(stdin); #include<conio.h>
printf ("Enter name :"); #define max 1000
scanf ("%s", name[i]); void main ( )
printf ("Enter roll number :\n"); {
scanf ("%d", &roll[i]); int j[max], n, i, first, last, pos=0, x,
printf("Enter marks in 5 different subjects mid, temp, k;
:"); printf ("Enter n:");
total[i]=0; scanf ("%d", &n);
for (j = 0; j < 5; j++)
{ // Entering the elements
scanf ("%d",&mark[i][j]); printf ("Enter elements :");
total [i] = total [i] + mark[i] [j]; for (i = 0; i < n; i ++)
} scanf ("%d", & j [i]);
}
// Displaying results // Arranging in ascending order
for (i = 0; i < n; i ++)
printf ("\n Name \t Roll number \t Total \n");
{
printf("...................................
for (k = i + 1; k < n; k ++)
\n"); if (j [i] > j [k])
for (i = 0; i < 10; i++) {
printf ("% s \ t % d \ t% d\n", name [i], roll temp = j [i];
[i], total [i]); j [i] = j [k];
getch ( ); j [k] = temp;
} }
}
Result: Enter roll number :100
Enter name :Ram Enter marks in 5 different subjects :
Enter roll number :10 80 50 55 60 80
Enter marks in 5 different subjects :
45 54 55 60 90 Name Roll number Total
……………………………………………….. ……………………………………………………………………………
Ram 10 304
………………………………………………..
…………… ……………..
…………………………………………………. ………………
Enter name :Umesh
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
printf ("Enter the number to be searched
printf ("The numbers entered in :\n");
ascending order are:\n"); scanf ("%d",&x);
for (i = 0; i < n; i ++)
printf ("%d \t", j[i]); first = 1;
printf (" \n \n"); last = n;
while((first <= last) && (pos== 0))
// Process for searching a number {
mid = (first + last)/2;
if (j [mid] == x)
pos = mid;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …247 248 … A Complete Refresh Manual of C Programming


else if (j [mid] < x) scanf("%d",&choice);
first = mid + 1; printf("\n\n\n");
else switch(choice)
last = mid - 1; {
} case 1:
{
if (pos > 0) for(i=0;i<n;i++)
printf ("Position is %d", pos); {
else printf("Enter name,roll,marks:");
printf ("Not found"); scanf("%s%d%d",name[i],&roll[i],
getch ( ); &marks[i]);
} }

Result: //Alphabetical sorting


Enter no :5 for(i=0;i<n;i++)
Enter elements:20 {
30 for(j=i+1;j<=n;j++)
40 {
50 if(strcmp(name[i],name[j])>0)
60 {
The numbers entered in ascending order are: strcpy(temp1,name[i]);
20 30 40 50 60 strcpy(name[i],name[j]);
strcpy(name[j],temp1);
Enter the number to be searched:50
Position is 3 temp=roll[i];
roll[i]=roll[j];
63. Develop a program that will read and store the details of a list of roll[j]=temp;
students in tabular format and produce the following output lists:
1. Alphabetical list of names, roll number and marks obtained. temp=marks[i];
marks[i]=marks[j];
2. List sorted on roll numbers.
marks[j]=temp;
3. List sorted on marks. }
Ans: #include<stdio.h> }
#include<conio.h> }
#include<string.h> scanf("%d",&n);
#define MAX 100
void main() printf("\n\n");
{ printf("1.Alphbetically
char name[MAX][20],temp1[20]; sorting\n"); printf("2.List
int i,j,roll[MAX],marks[MAX],temp; sortd on roll number\n");
int choice,n; printf("3.List sorted on
marks\n");
printf("Enter number of students:"); printf(".......................
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
....\n"); printf("Enter ur choice"); printf("The data in namewise orders
are:\n\n");
for(i=0;i<n;++i)
printf("%s\t%d\t%d\n",name[i],roll[i],
marks[i]);
}
break;

case 2:
{
for(i=0;i<n;i++)
{
printf("Enter name,roll,marks:");
scanf("%s%d%d",name[i],&roll[i],
&marks[i]);
}
//Rollwise sorting
for(i=0;i<n;i++)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …249 250 … A Complete Refresh Manual of C Programming


{ strcpy(name[i],name[j]);
for(j=i+1;j<=n;j++) strcpy(name[j],temp1);
{ }
if(roll[i]>roll[j]) }
{ }
printf("The data in markswise
temp=roll[i]; are:\n\n");
roll[i]=roll[j]; for(i=0;i<n;i++)
roll[j]=temp; printf("%d\t%s\t%d\n",marks[i],name[i]
,roll[i]);
strcpy(temp1,name[i]); }
strcpy(name[i],name[j]); break;
strcpy(name[j],temp1); default:
printf("Wrong choice");
temp=marks[i]; break;
marks[i]=marks[j]; }
marks[j]=temp; getch();
} }
} Result:
} Enter the number of students:3
printf("The data in
rollnumberwise:\n"); 1.Alphbetically sorting
for(i=0;i<n;i++) 2.List sortd on roll number
printf("%d\t%s\t%d\n",roll[i],name[i], 3.List sorted on marks
marks[i]); ...........................
} Enter ur choice:2
break;
Enter name,roll,marks:om 2 400
case 3: Enter name,roll,marks:ayush 1 450
{ Enter name,roll,marks:Deepu 6 300
for(i=0;i<n;i++) The dat in rollnumberwise:
{
printf("Enter name,roll,marks:");
scanf("%s%d%d",name[i],&roll[i], 1 ayush 450
&marks[i]); 2 om 400
} 6 Deepu 300
//Markswise sorting
for(i=0;i<n;i++) 64. Write a computer program to raise the power of Q each element of
{
for(j=i+1;j<=n;j++) marks[i]=marks[j]; marks[j]=temp;
{
temp=roll[i]; roll[i]=roll[j];
if(marks[i]>marks[j])
roll[j]=temp;
{
temp=marks[i];
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
strcpy(temp1,name[i]); given matrix of order P x Q by 3. Display the resultant matrix.
[T.U. 2057 Chaitra]
Ans: #include<stdio.h>
#include<conio.h>
#include<math.h>
#define P 3
#define Q 4
void printmatrix(int a[P][Q]);
void main()
{
int i,j,a[P][Q],b[P][Q];
for(i=0;i<P;++i)
for(j=0;j<Q;++j)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
printf("Enter elements:");
C Programming Language …251 scanf("%d",&b[i]);
{ }
printf(“a[%d][%d]=”,i,j); c=(int*)malloc(sizeof(int)*(M+N));
scanf(“%d”,&a[i][j]);
} for(i=0;i<P;++i) for(i=0;i<M;++i)
for(j=0;j<Q;++j) *(c+i)=a[i];
b[i][j]=pow(a[i][j],3);

printf(“Entered matrix is\n”);


printmatrix(a);

printf(“Resulted matrix is\n”);


printfmatrix(b);
getch();
}
void printmatrix(int a[P][Q])
{
int i,j;
for(i=0;i<P;++i)
{
for(j=0;j<Q;++j)
printf(“%d\t”,a[i][j]);
printf(“\n”);
}
}
65. Write a program that reads two one-dimensional arrays of order m
and n respectively and merge the content of first and second array to
third array of order (m+n) and display it.
Ans: #include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define M 5
#define N 10
void main()
{
int *c,i,a[M],b[N];

for(i=0;i<M;++i)
{
printf("Enter elements:");
scanf("%d",&a[i]);
}
for(i=0;i<M;++i)
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

252 … A Complete Refresh Manual of C Programming }


for(i=0;i<N;++i) Result: N
*(c+i+M)=b[i]; EE
printf("\nFirst array"); PPP
for(i=0;i<M;++i) AAAA
printf("%d\t",a[i]);
printf("\nSecond array");
L LLLL
for(i=0;i<N;++i)
printf("%d\t",b[i]);
printf("\nThird array");
for(i=0;i<M+N;++i)
printf("%d\t",*(c+i));
getch();
}
66. Write a program to display the following patters:
[Pokhara University 2009 - Fall]
N
EE
PPP
AAAA
LLLLL
Ans: #include<stdio.h>
#include<conio.h>
void main()
{
char str[]="NEPAL";
int i,j;
for(i=0;i<=5;i++)
{
for(j=0;j<=i;j++)
{
printf("%c",str[i]);
}
printf("\n");
}
getch();
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
#include<conio.h>
C Programming Language …253 void sen(char str[80],int,int,int);
67. Write a program to display the following patters: void main()
H {
char str[80];
HE
int v,c,d;
HEL
HELL printf("Enter a string:");
HELLO gets(str);
HELLOW
Ans: #include<stdio.h>
#include<conio.h>
void main()
{
char str[]="HELLOW";
int i,j;
for(i=0;i<6;i++)
{
for(j=0;j<=i;j++)
{
printf("%c",str[j]);
}
printf("\n");
}
getch();
}

Result:
H
H E
H E L
H E L L
H E L L O
H E L L O W

68. Write a function that takes a string as input and counts the number
of vowels,consonants, numeric characters and other characters. The
calling function should read the string and pass it to the function.
After the function call, the count of vowels, consonants, numeric
characters and other characters should be displayed in the calling
function. [T.U. 2061 Poush]
Ans: #include<string.h>
#include<stdio.h>
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
if(a[i]==32 || a[i]=='\t' || a[i]=='\0')
254 … A Complete Refresh Manual of C Programming { c[k]='\0';
sen(str,v,c,d); if(strcmp(b,c)==0)count++;
//,int v,int c,int d) k=0;
getch(); }
} else
void sen(char str[80],int v,int c,int d) {
{
int i; v=0;c=0;d=0;
for(i=0;str[i]!=0;++i)
{
if (ch = = 'a' || ch = = 'e' || ch = = 'i' || ch
= = '0' || ch = = 'u' || ch = = 'A' || ch = =
'E' || ch = = 'O' || ch = = 'I' || ch = = 'U')
++v;
else if(str[i]>='0' && str[i]<='9')
++d;
else
++c;
}
printf("\nTotal number of Vowel=%d",v);
printf("\nTotal no. of digits=%d",d);
printf("Total no. of consonat=%d",c);
}
69. Write a C program that reads the text and counts all occurrences of
a particular word.
Ans: #include <string.h>
#includ<stdio.h>
#include<conio.h>
void main()
{
char a[100],b[20],c[20];
int i,count=0,k=0,len;
clrscr();
printf ("\nEnter a string:-> ");
gets(a);
printf("\nEnter the word to be searched:->
");
gets(b);

len=strlen(a);
for(i=0;i<=len;i++)
{
/*Assuming Space , Tab and NULL as word
separator*/
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …255 256 … A Complete Refresh Manual of C Programming


c[k]=a[i]; k++;
k++; }
} if(a[i]>b[j])
} {
printf("Occurance of %s is = %d",b,count); void merge(int *a,int *b,int n,int m)
getch(); {
} int i=0,c[20],j=0,k=0,count=0;
Result: while(i<=n&&j<=m)
Enter a string:->We are student. {
i
f
Enter the word to be searched:->are (
a
Occurrence of are is=1 [
70. Given are two one dimensional arrays A and B which are stored in i
ascending order. Write a program to merge them into a single ]
sorted array C that contains every element of A and B in ascending <
order. (8) b
[
Ans: #include<stdio.h>
j
#include<conio.h>
]
void merge(int*,int*,int,int);
)
void main()
{
{
c[k]=a[i];
int a[10],b[10];
i++;
int i,j,m,n;
clrscr();
printf("How many numbers u want to enter in
1st array : ");
scanf("%d",&n);
printf("Enter numbers in ascending order
:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("How many numbers u want to enter in
2nd array : ");
scanf("%d",&m);
printf("Enter numbers in ascending order
:\n");
for(i=0;i<m;i++)
scanf("%d",&b[i]);
merge(a,b,n,m);
getch();
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
c[k]=b[j];
j++;
k++;
}
if(a[i]==b[j])
{
c[k]=a[i];
k++; i++; j++;
count++;
}
}
if(i<=n && j==m)
{
while(i<=n)
{
c[k]=a[i];
i++;
k++;
}
}
if(i==n&&j<=m)
{
while(j<=m)
{
c[k]=b[j];
i++;
j++;
}
}
Printf(The elements are:\n”);
for(i=0;i<m+n-count;i++)
printf("%d\t",c[i]);
}
Result:
How many numbers u want to enter in 1st array :3
Enter numbers in ascending order:
12
13
14
15
How many numbers u want to enter in 2nd array :3
Enter numbers in ascending order :
16
17
18
The elements are
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …257 258 … A Complete Refresh Manual of C Programming


12 13 14 15 16 17 18 scanf(“%d”,&n);
p=(int *)malloc(n*sizeof(int));
71. Write a program that adds the individual rows of a two dimensional
array of m by n and store the sum of rows into a single dimensional printf(“Enter array elements:”);
for(i=0;i<n;++i)
array using functions. Write a function that takes a two dimensional scanf(“%d”,(p+i));
array and one dimesional array and process the result and store in sumdiff(p,&sum,&diff,n);
one-dimensional array. [T.U. 2062 Baisakh] printf(“Sum=%d”,sum);
Ans: #include<stdio.h> printf(“\nDifference=%d”,diff);
#include<conio.h> getch();
void check(int[][10],int[],imt,int); }
void main() void sumdiff(int *a,int *s,int *d,int n)
{ {
int a[10][10],s[10],m,n,i,j; int max=*a,min=*a,i;
clrscr(); for(i=1;i<n;++i)
printf(“Enter order of array:”); {
scanf(“%d%d”,&m,&n); if(max<*(a+i))
printf(“Enter elements of array”); max=*(a+i);
for(i=0i<m;++i) if(min>*(a+i))
{ min=*(a+i);
for(j=0;j<n;++j) }
{ *s=max+min;
scanf(“%d”,&a[i][j]); *d=max-min;
} }
} 73. Write a C program to rearrange the elements of an array so that
check(a,s,m,n); those originally stored at odd suffixes are placed before those at
for(i=0;i<m;++i) even suffixes.
printf(“%d\n”,s[i]);
getch();
Ans: #include<stdio.h>
#include<conio.h>
}
main()
void check(int a[][10],int s[],int m,int n)
{
{
char a[25],ch,temp;
int i,j;
for(i=0;i<m;++i) to main function. [T.U. 2062 Poush]
{ Ans: #include<stdio.h>
s[i]=0; #include<conio.h>
for(j=0;j<n;++j) void sumdiff(int *,int *,int *,int);
s[i]=s[i]+a[i][j]; void main()
} {
} int *p,sum,diff,n,i;
72. Write a program to read an array of n elements .Allocate the memory printf(“\n Enter number of elements:”);
space of the array dynamically. Use the function that returns the
sum and difference of the largest and smallest elements of the array
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
int i;
clrscr();
printf ("\nEnter the string:-> ");
gets(a);
for (i=0;a[i]!='\0';i++)
{
if (a[i+1]=='\0')break;
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
i++;
}
puts(a);
getch();
}
74. Write a C function strend(s, t), which returns 1 if the string t occurs
at the end of the string s, and zero otherwise.
Ans: #include<conio.h>
#include<string.h>
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …259 260 … A Complete Refresh Manual of C Programming


strend () }}
{ }
char s[100],t[20],c[20]; void process(int a[][],int b[][],int m)
int i,j,k=0,len1,len2; {
clrscr(); int c[][],I,j,k;
printf("\n Enter the string : "); {
gets(s); int i,j;
printf("\nEnter the string to be searched for : "); for(i=0;i<m;i++)
gets(t); {
len1=strlen(s); for(j=0;j<m;j++)
len2=strlen(t); {
for(i=len1-(len2);i<=len1;i++) printf(“Enter elements of a matrix:”);
{ scanf("%d",&x[i][j]);
c[k++]=s[i];
} c[k]='\0';
if(strcmp(t,c)==0)
return 1;
else
return 0;
getch();
}
76. Write a program that performs the matrix multiplication of a square
matrix of order nxn with its own transposed matrix. You have check
three functions read(), process() and display() to read, process and
display the matrices. [T.U. 2064 Falgun]
Ans: #include<stdio.h>
#include<conio.h>
void read(int [][10],int);
void process(int [][10],int[][10],int);
void display(int [][10],int);
void main()
{
int a[10][10],b[10][10],m;

printf("Enter the order of 1st matrix:");


scanf("%d",&m);

read(a,m);
process(a,b,m);
display(b,m);
getch();
}
void read(int x[][10],int m)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
c[i][j]=a[i][]j];
}

for(i=1;i<m;i++)
{
for(j=0;j<m;j++)
{
b[][]=0; for(k=1;k<m;k++)
b[i][j]=b[i][j]+a[i][k]*b[k][j];
}
}
}
void display(int [][10],int m)
{
int I,j;
for(i=0;i<m;++i)
{ printf(“\n”); for(j=0;j<m;++j)
printf(“%d\t”,x[i][j]);
}
}
75. Program to calculate standard deviation using function.
Ans: #include<math.h>
main()
{
float value[5], stddev();
int i;
printf(“Enter the values\n”);
for(i=0;i<5;i++)
scanf(“%f”, &value[i]);
printf(“Std.deviation is %f\n”, stddev(value,5);
}
float stddev(x,n)
float x[ ];
int n;
{
int i;
float mean(),y,sum=0.0;
y=mean(x,n);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …261 262 … A Complete Refresh Manual of C Programming


for(i=0;i<n;i++) 2.10 Function
{
sum=sum+(y-x[i])*(y-x[i]); 1. What is a function ? What are its advantages. [T.U. 2059]
return(sqrt(sum/(float)n)); Ans: Function
} A function groups a number of statements into a unit and gives
float mean(x,n) it a name. Then the unit can be invoked from some other parts of the
float x[ ]; program. We can avoid rewriting of a group of codes by defining them
int n; within a function block and use them by simply calling the function
{ name.
int i; Advantages of function :
float sum=0.0; a. It makes possible top down modular programming. In this style
for(i=0;i<n;i++) of programming, the high level logic of the overall problem is
sum=sum+x[i]; solved first while the details of each lower level functions is
return(sum/(float)n); addressed later.
} b. The length of the source program can be reduced by using
functions at appropriate places.
c. It becomes uncomplicated to locate and separate a faulty
function for further study.
d. A function may be used later by many other programs this
means that a c programmer can use function written by others,
instead of starting over from scratch.
e. A function can be used to keep away from rewriting the same
block of codes which we are going use two or more locations
in a program. This is especially useful if the code involved is
long or complicated.
2. What do you understand by function in C? How functions are
categorized in C? Explain. [T.U. 2061 Poush]
Ans: Function:Function,Questions no (1).
Category of function
a. Library functions
b. User defined functions
a. Library functions
Library functions are the built in functions within the C
programs.Library functions can not be modified.
A library function is accessed simply by writing the function
name, followed by a list of arguments that represent information being
passed to the function. The arguments must be enclosed in parentheses
and separated by commas. The arguments can be constants, variable
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
names or more complex
expressions. Examples:
sqrt(),strcmp(),pow() etc.
b
.

U
s
e
r

d
e
f
i
n
e
d

f
u
n
c
t
i
o
n
The functions developed
by the user in any programming
language is called user defined
language.The user defined
function
name must not be same as
library functions.User defined
function consists following
statements:function declaration
,function call and
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …263 printf ("\nThere are numbers from 1 to 100\n");


printnumb ( );
function definition.User defined function can be called any number of printf ("You got the result");
times as the user need. getch ( );
Types of user defined functions are: }
i. Functions without arguments and no return value void printnumb ( )
ii. Functions without arguments and return value {
iii. Functions with arguments and no return value
ii. Functions with argument and return value
3. Give the example of “Functions without arguments and no return
value” type of function.
Ans: #include<stdio.h>
#include<conio.h>
void print( );
void main ( )
{
print( );
printf ("\nChecking function without argument.");
printf ("\nwith no returnable.");
print( );
getch ( );
}
void print( )
{
int a;
for (a = 1;a<=80;a++)
printf ("*");
}
Result:
****************……………..*****
Checking function without argument.
with no returnable.
****************…………….*****

4. Give example of “Functions with arguments and no return value”


type of function.
Ans: #include<stdio.h>
#include<conio.h>
void printnumb ( );
void main ( )
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

264 … A Complete Refresh Manual of C Programming int x,y,z;


printf(“Enter value of x and y:”);
int a; scanf(“%d%d”,&x,&y);
for (a = 1;a<=100;a++) z=sum(x,y);
printf ("%d\t", a); printf(“Sum of two numbers=%d”,z);
} getch();
Result:
There are numbers from 1 to 100.
1 2 3 4………………………………..
………………………………….98 99 100
You got the result
5. Give example of “Functions with arguments and no return Value”
type of function.
Ans: #include<stdio.h>
#include<conio.h>
int product();
void main()
{
int z; z=product();
printf(“Product=%d",z);
getch();
}
int product()
{
int x,y,z;
printf("Enter value of x and y:");
scanf("%d%d",&x,&y);
z=x*y;
return z;
}
Result:

Enter value of x and y:2 3


Product=6
6. Give the example of “Functions with argument and return value”
type of function.
Ans: #include <stdio.h>
#include <conio.h>
int sum(int,int);
void main()
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …265 266 … A Complete Refresh Manual of C Programming


} Disadvantages
int sum(int x,int y) (a) Since separate modules map repeat certain functions, the
{ modular programming often need extra time and memory.
int z; 9. Why programmer want to do program in modular style? Explain.
z=x*y; Ans: There are many good reasons to program in a modular style:
return z; – Don’t have to repeat the same block of code many times in
} your code. Make that code block a function and call it when
Result: needed.
Enter value of x and y:4 5 convenient. The division of a long program into a smaller programs
Sum of two number=9 (or modules) is called modular programming.
7. Why user-defined function is needed? Explain. Advantages
Ans: User defined function is needed because of (a) It is easier to design, test and debug a single modules as
(a). A programmer may have a block of code that he has repeated compared to an entire program.
forty times throughout the program. A function to execute that (b) Usually, a module of general nature is prepared so that it can be
code would save a great deal of space, and it would also make used elsewhere.
the program more readable.
(b) It is easy to locate and isolate a faulty function. Having only
one copy of the code makes it easier to make changes.
(c ) Another reason for functions is to break down a complex
program into logical parts. For example, take a menu program
that runs complex code when a menu choice is selected. The
program would probably best be served by making functions
for each of the actual menu choices, and then breaking down
the complex tasks into smaller, more manageable tasks, which
could be in their own functions. In this way, a program can be
designed that makes sense when read. And has a structure that
is easier to understand quickly. The worst programs usually
only have the required function, main, and fill it with pages of
jumbled code.
(d). A function may be used by many other programs. A
programmer can use already compiled function instead of
starting over from scratch.
8. What is modular programming? What are the advantages of
modular programming?
Ans: When a program becomes very large and complex, it becomes very
difficult task for the programmer to design, test and debug such a
program. Therefore, a long program can be divided into a smaller
programs called modules. As the modules can be designed, tested and
debugged separately, the task of programmer becomes easy and
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
– Function portability: useful functions can be used in a number
of programs.
– Supports the top-down technique for devising a program
algorithm. Make an outline and hierarchy of the steps needed to
solve your problem and create a function for each step.
– Easy to debug. Get one function working well then move on to
the others.
– Easy to modify and expand. Just add more functions to extend
program capability
– For a large programming project, you will code only a small
fraction of the program.
– Make program self-documenting and readable.
10. What do you know about function declaration, function call and
function definition? Explain clearly.
Or, Explain various parts of functions.
Ans: Function declaration OR,
Function prototype [T.U. 2058]
It specifies function name, argument types and return value. Alerts
computer (and programmer) that function is coming up later.
Examples : void display( );
int sum (int, int, int); etc.
Function call
It is also a component of the function and causes the function to be
executed.
Examples : display ( );
result = sum(a, b, c); etc.
Function definition
The function itself contains the lines of code that constitute the
function.
Examples : void display( )
{
for (int i = 0; i < 9; i + +)
printf ("+");
}
int sum(int x, int y, int z)
{
res = x+ y + z;
return res;
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
{
C Programming Language …267
int factorial;
11. What do you know about function parameter and function return ? if(n==1||n==0)
Ans: Function parameter : The parameter specified in function call are return(1);
known as actual parameter and those specified in function declaration else
are known as formal parameter. factorial=n*fact(n-1);
Example : res = sum(a, b, c); return (factorial);
Here a, b, c are actual parameter
int sum (int x, int y, int z)
Here x, y, z are formal parameter.
Function return : Function can be organized into two type.
(a) Function that do not have a return type i.e. void function.
(b) Function that do have a return value (i.e. return (res);)
12. What do you understand by return statement? Explain with suitable
examples about its advantages and disadvantages.
[T.U. 2060, 2061 Baisakh]
Or, What is recursion ? Give its example.
Or, Write about return statement clearly stating different conditional
that may arise where returning from a function .
[T.U. 2058 Chaitra]
Ans: Recursion is a special case of function call where a function calls
itself. These are very useful in the situations where solution can be
expressed in terms of successively applying same operation to the
subsets of the problem.
Advantages
a. May be much easier to write.
b. To solve some problem which are naturally recursive such as
towers of Hanoi.
Disadvantages
a. Recursive functions are generally slower than non-recursive
function.
b. It is difficult to think recursively so one must be very careful
when writing recursive function.
c. May require lots of memory.
For example, a recursive function to calculate factorial of a number
n is given below:
fact(int n)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

268 … A Complete Refresh Manual of C Programming Call by value means sending the values of the arguments- The value
of each of the actual arguments in the calling function is copied into
} corresponding formal arguments of the called function. The changes
Assume n=4, we call fact(4)
made to the formal arguments have no effect on the values of actual
Since n 1or 0, factorial=n*fact(n-1)
Factorial=4*fact(3)(again call fact function with arguments in the calling function. This technique of passing
n=3) arguments is called call by value illustrated by swapv(int x, int y)
=4*3*fact(2)(again call fact function with n=2) function in the following example.
=4*3*2*fact(1)(again call fact function with n=1)
=4*3*2*1 (terminating condition)
=24
We should always have a terminating condition with a
recursive function call otherwise function will never return.
Example : To calculate factorial using recursion
#include <stdio.h>
#include <conio.h>
int factorial (int);
void main ( )
{
int n;
printf ("Enter a number =");
scanf ("%d", &n);
printf ("Factorial no = %d", factorial (n));
getch ( );
}
int factorial (int n)
{
if (n < = 1)
return 1;
else
return (n * factorial (n - 1));
}
13. Explain the difference between 'call by reference' and 'call by
value'.
Or, In how many ways,we can pass arguments to a function? Explain
with examples. [T.U. 2061 Shrawan, 2066 Jestha]
Or, Distinguish between call by value and call by reference with
examples. [T.U. 2064 Falgun]
Or, How can you differentiate between call by value and call by
reference with examples in C programming. [T.U. 2067 Asadh]
Or, Differentiate between pass by value and pass by reference
arguments. Describe both with meaningful example.
[T.U. 2069 Ashad]
Ans: Differentiation between 'call by reference' and 'call by value':
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …269 270 … A Complete Refresh Manual of C Programming


Call by reference means sending the addresses of the arguments- the 14. Distinguish between recursion and iteration.
addresses of actual arguments in the calling function are copied into [T.U. 2064 Falgun, 2067 Ashwin]
formal arguments of the called function. Using these addresses we are Ans: Differences between recursion and iteration:
actually working on actual argument so changes will be reflected in Iteration Recursion
the calling function. This technique of passing arguments is called call It is process of executing a Recursion is the technique of
by reference, illustrated by swapr(int *x,int *y) in following example. statement or a set of statements defining anything in terms of
#include<stdio.h> repeatedly,until some specific itself.
#include<conio.h> condition is satisfied.
#include<math.h> Iteration involves four clear cut There must be an exclusive if
void main() steps initiallization statement inside the recursive
condition,execution and function,specifying stopping
{
updation. condition.
int i=10,j=20; Any recursive problem can be Not all problems have recursive
clrscr(); solved iteratively. solution.
printf("The values before swap is i: %d, Iterative counterpart of a Recursion is generally a worse
j:%d\n",i,j); problem is more efficient in option to go for simple problems
swapv(i,j); terms
*x=*y;of memory utilization and not recursive in nature.
printf("The values after swap is i: %d, execution speed.
*y=temp;
j:%d\n",i,j); }
printf("\n"); The value of i and j is 10 and 20 only after calling function swapv,
swapv(&i,&j); that is call by value. However the result of calling swapr(), call by reference is
printf("The values after swap is i: %d, i=20 and j=10
j:%d\n",i,j);
printf("\n");
getch();
}
swapv(int x,int y)
{ int temp;
temp=x;
x=y;
y=temp;
}
swapr(int *x,int *y)
{
int temp;
temp=*x;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

15. Differentiate between macro and functions. Write their


advantages and disadvantages.
[T.U. 2058 Poush]
Or, What is a macro? How is it different from a C variable
name? What are the advantages of using macro definitions in
a program.
Ans: A macro is a pre-processor directive which is a program that
processes
the source code before it passes through the compiler. These are
placed in the source program before the main. To define a
macro, # define statement is used. This statement, also
known as macro definition takes the following general form:
#define
identifier string
The pre-processor replaces every occurrence of the identifier in
the source code by the string. The preprocessor directive
definition is not terminated by a semicolon. For example
#define COUNT 100 will replace all occurrences of COUNT
with 100 in the whole program before compilation.
16. What do you mean by storage class of variables? Write down
about static, local and global variables in terms of lifetime
and scope with example. [T.U. 2062
Baisakh]
Or, Classify the variables according to the scope and extent
(storage class) with examples.
[T.U. 2063]
Ans: Storage classes in C
There are four storage
classes in C:
a. Automatic storage class: The features of variables
are as follows
• Storage: Memory
• Default initial value: Garbage value
• Scope: Local to the block in which defined
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
void main()
C Programming Language …271 {

Life: till the control remains within the block in which register int x,y,z;
defined. x=0; y=0;
do
Example:Demonstration of automatic variable in function {
#include<stdio.h>
z=function1(x,y);
#include<conio.h>
int function1(int);
void main()
{
int i; for(i=1;i<=10;++i)
printf("%d\t%d\n",i,function1(i));
getch();
}
int function1(x)
int x;
{
int s=10; //Automatic variable
return s+=x;
}
Result:
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
10 20

b. Register storage class: The features of variables are as follows


• Storage: CPU registers
• Default initial value: Garbage value
• Scope: Local to the block in which defined
• Life: till the control remains within the block in which
defined
Example:Demonstration of ergister variable in function
\#include<stdio.h>
#include<conio.h>
int function1(int,int);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
#include<conio.h>
272 … A Complete Refresh Manual of C
Programming int function1(int);
void main()
printf("%d\t%d\n",x,z);
++x; {
++y; int i; for(i=1;i<=5;++i)
}while(x<=5); printf("%d\t%d\n",i,function1(i));
getch(); getch();
} }
int function1(x,y) int function1(x)
register int x,y;
int x;
{
register {
temp; static int s=100;
temp=x*y return s+=x;
; return
temp; }
}
Result:
0
0
1
1
2
4
3
9
4
18
5
25

c. Static storage class: The features of variables are as


follows
• Storage: Memory
• Default initial value: Zero
• Scope: Local to the block in which defined
• Life: value of variable persists between different
function calls.
Example:Demonstration of static variable in function
#include<stdio.h>
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …273 274 … A Complete Refresh Manual of C Programming


Result: 17. What is a pre-processor? Which pre-processor is used to define a
1 101 macro?
2 103 Ans: A pre-processor is a program that processes the source code before it
3 106
passes through the compiler. It operates under the control of
4 110
5 115 preprocessor directive. These are placed in the source program before
the main.
d. External storage class: The features of variables here are as } Result:
follows Inside the main() I am
• Storage: Memory C program.
…………………
• Default initial value: Zero
…………………
• Scope: global Inside the main() I am
• Life: As long as program execution does not come to an C program.
end.
Example:Demonstration of external variable in function
#include<stdio.h>
#include<conio.h>
void function1();
int x=10,y;
void main()
{
for(y=0;y<=x-1;++y)
{
printf("Inside the main()\n");
printf("I am C program.\n");
}
function1();
getch();
}

void function1()
{
for(y=0;y<=x-1;++y)
{
printf("Inside the main()\n");
printf("I am C program.\n");
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

To define a macro, # define statement is used. This Ans: Size of any function is calculated as:
statement, also known as macro definition takes the following Size of function = Size of all local variable which has declared in
general form: function + Size of those global variables which has used in function+
#define identifier string Size of all its parameter+ Size of returned value if it is an address.
The pre-processor replaces every occurrence of the Example:
identifier in the source code by the string. The preprocessor
directive definition is not terminated by a semicolon. For
example
#define COUNT 100 will replace all occurrences of
COUNT with
100 in the whole program before compilation.
18. What is a subroutine? How do subroutines help in program
writing? Ans: Subroutine [T.U.
2062 Baisakh] A subroutine is a named, independent section of C
code that
performs a specific task and optionally returns a value to the
calling
program. Some of the important characteristics of subroutine
that help in program writing are:
• A subroutine is named, each have a unique name. By
using that name in another part of the program, one can
execute the statements contained in the subroutine.
• A subroutine is independent that can perform its task
without interference from or interfering with other parts
of the program.
• A subroutine performs a specific task. A task is a
discrete job that a program must perform as part of its
overall operation, such as sending a line of text to a
printer, sorting an array into numerical order, or
calculating a cube root.
• A subroutine can return a value to the calling program.
When a program calls a subroutine, then statements it
contains are executed. These statements can pass
information back to the calling program.
19. How to calculate size of a function in c? Explain.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …275 276 … A Complete Refresh Manual of C Programming


20. What is size of calculate function? 2.11 C Programmings – 6
Ans: int x=2;
int* calculate
1. Write a program to calculate the area and circumference of a circle
void main()
using a function where radius of circle is input by user and define
{
‘ ’ as constant.
int *p,a=0,b=5;
Ans: #include <stdio.h>
p=calculate(a,b); #include <conio.h>
printf(“%d”,*p); #define pie 3.14
} void findarea (int);
int * calculate(int a,int b) void findcircum (int);
{ void main ( )
static int z; {
z=a+x+b; int r;
return &z; printf ("Enter the value of radius =");
scanf ("%d", &r);
} findarea (r);
Result: findcircum (r);
Size of calculate function= 2 (global variable x)+ 2 (local variable z) getch ( );
+2*2 (parameter a, b)+ 2 ( returning address of z)= 10 bytes }
void findarea (int r)
{
float a;
a = pie * r * r;
printf ("Area of a circle = %.2f", a);
}
void findcircum (int r)
{
float c;
c = 2*pie * r;
printf ("\n circumference of a circle =
%.2f",c);
}

Result:
Enter the value of radius =2

Area of a circle =12.56


circumference of a circle =12.56

2. Write a program to print all even numbers from 2-40 using non-
returnable function.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Ans: #include<stdio.h>
#include<conio.h>
void print_even ( );
void main ( )
{
printf ("Here are even numbers from 2 to
40\n");
print_even ( );
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
}
C Programming Language …277
printf ("You got the result");
getch ( );
}
void print_even ( )
{
int a;
for (a = 2;a<=40;a+=2)
printf ("%d\n", a);
}
Result:
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
You got the result

3. Write a program to find sum of ‘n’ different numbers using non-


returnable function.
Ans: #include<stdio.h>
#include<conio.h>
void sumofint(int);
void main()
{
int n;
printf("Enter,how many number?:");
scanf("%d",&n);
sumofint(n);
getch();
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
void main()
278 … A Complete Refresh Manual of C Programming {
sum=sum+num; printf ("Sum of square of first 10
} natural numbers.\n");
printf("Sum of integer=%d",sum); sum();
} printf ("You got sum of first 10 natural
numbers.\n");
Result: getch ( );
Enter,how many number?5 }
Enter number:2 void sum( )
Enter number:3 {
Enter number:4 int a, sum = 0;
Enter number:5 for (a = 1; a < = 10; a ++)
Enter number:6 sum = sum + a * a;
printf ("Sum of square of first 10
Sum of integer:20 natural numbers = %d\n",sum);
}
4. Write a program to find sum of square of first 10 natural numbers
using functions. Result:
Sum of square of first 10 natural numbers
Ans: #include <stdio.h> Sum of square of first 10 natural numbers=385
#include <conio.h>
You got sum of first 10 natural numbers
void sum();
void sumofint(int n) 5. Write a program to find multiplication table of any number using
{ function.
int x,sum=0,num; Ans: #include<stdio.h>
for(x=0;x<n;++x) #include<conio.h>
{ void numbers(int );
printf("Enter number:"); void main( )
scanf("%d",&num); {
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …279 280 … A Complete Refresh Manual of C Programming


int n; else
printf(“Enter any number=”); ncount = ncount + 1;
scanf(“%d”,&n); }
numbers(n); printf ("Total number of +ve no. =
getch(); %d\n", pcount);
}
printf ("Total number of -ve no. =
void numbers(int n)
{ %d", ncount);
int x,m; }
for(x=1;x<=10;++x)
{ Result:
m=n*x; Enter the value of n =5
printf(“%d x %d=%d\n”,n,x,m); Enter numbers :10
}
Enter numbers :-11
}
Enter numbers :12
Result:
Enter any number=4 getch ( );
4x1=4 }
4x2=8 void numbers(int no[100],int n)
4x3=12 {
4x4=16 int pcount=0, ncount=0;
4x5=20 for (int i = 1;i<n;i++)
…………… {
……………. if(no[i]> 0)
4x10=40 pcount = pcount + 1;

6. Write a program to count the positive and negative numbers from 'n'
entered numbers using functions.
Ans: #include<stdio.h>
#include<conio.h>
void numbers(int no[100],int n );
void main ( )
{
int n,no[100],i;
printf ("Enter the value of n =\n");
scanf ("%d", &n);
for (i = 1; i<n; i++)
{
printf ("Enter numbers :");
scanf ("%d", &no[i]);
}
numbers(no,n);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Enter numbers :20
Enter numbers :-25

Total number of +ve no. = 3


Total number of -ve no. = -2

7. Write a computer program to display a line of text “programming is


fun” 5 times using recursion. [T.U. 2058 Poush]
Ans: #include<stdio.h>
#include<conio.h>
void printstring();
void main ( )
{
clrscr();
printstring();
getch();
}
void printstring()
{
int i=0;
for(i=0;i<5;++i)
printf("programming is fun.\n");
}

Result:
programming is fun.
programming is fun.
programming is fun.
programming is fun.
programming is fun.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
void display(char
C Programming Language …281 name[20][20]);
8. Write a program to display all the prime numbers within the ranges void main()
specified by the users using functions. [T.U. 2063 Baisakh] {
char
Ans: #include<stdio.h>
name[
#include<conio.h>
20][2
void sum(int);
0];
void main( )
{ int
i;
int x;
printf("Enter,how many two numbers= for(i
=0;i<
");
scanf ("%d", &x); 20;++
i)
printf(“\n”);
printf(“The prime number are:\n”); {
sum(x);
getch ( );
}
void sum(int x)
{
int i,j;
for (i =1;i<=x;++i)
{
for(j=2;j<=i;++j)
{
if(i%j==0)
break;
} if(i==j)
printf("%d\t",i);
}

}
Result:
Enter,how many two numbers=20

The prime number are:


2 35 7 11 13 17 19

9. Write a program to read 20 name of students and sort the


alphabetically. the process must be done by the user defined
function. [T.U. 2063 Baisakh]
Ans: #include<stdio.h>
#include<conio.h>
#include<string.h>
void sort(char name[20][20]);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

282 … A Complete Refresh Manual of C Programming


printf("Enter name:");
scanf("%s",name[i]);
}
sort(name); display(name);
getch();
}
void sort(char name[20][20])
{
int i,j;
char temp[20];
for(i=0;i<20;++i)
{
for(j=i+1;j<20;++j)
{
if(strcmp(name[i],name[j])>0)
{
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}
}
}
void display(char name[20][20])
{
int i;
printf(“The name in ascending order are:\n”);
for(i=0;i<20;++i)
printf("%s\n",name[i]);
}

Result:
Enter name:Ram Enter name:Hari
Enter name:Umesh Enter
name:Pradip Enter name:Niruta

The name in ascending order are: Hari


Niruta Pradip Ram
Umesh
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
void main()
C Programming Language …283 {
10. Write a C program to generate fibonacci series up to nth terms. int ceount=0,ocount=0;
[T.U. 2063 Poush] long int n;
Ans: #include<stdio.h>
printf(“Enter value of n:”);
#include<conio.h> scanf(“%ld”,&n);
void fibonacci(int,int,int); count(n,&ecount,&ocount);
void main()
{
int n,f0=0,f1=1;
printf("Enter number of terms:");
scanf("%d",&n);

printf("%d\t%d\t",f0,f1);
fibonacci(f0,f1,n-2);
getch();
}
void fibonacci(int f0,int f1,int n)
{
int c;
if(a==0)
{
return a;
}
else
{ c=f0+f1;
printf("%d\t",c);
}
fibonacci(f0,f1,n-1);
}
Result:
Enter number of terms:5
1 12 3 5

11. Write a program to read an integer number, count the even and odd
digits present in the entered number. You must write a function for
calculating the result and result must be displayed in the main
function itself. [T.U. 2063 Poush]
Ans: #include <stdio.h>
#include <conio.h>
void count(lont int,int *,int *);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
for(i=0;i<n;++i)
284 … A Complete Refresh Manual of C Programming {
printf(“\nTotal no. of even digit.=%d”,ecount); if(*(x+i)%2==0)
printf(“\nTotal no. of odd digits.=%d”,ocount); *e=*e+1;
getch(); else
} *o=*o+1;
void count(int n,int *e,int *o) }
{ }
int r;
while(n!=0)
{
r= n%10;

if(r%2= =0)
*e=*e+1;
else
*o=*o+1;

n=n/10;
}
}
12. Write a program that reads ‘n’ positive integer numbers into an
array dynamically. Pass this to a function that counts the number of
even and odd numbers. Return the result to the calling function and
display the result. [T.U. 2064 Jestha]
Ans: #include <stdio.h>
#include <conio.h>
void count(int *,int *,int *,int);
void main()
{
int *x,ecount=0,ocount=0,i;
printf(“Enter value of n:”);
scanf(“%d”,&n);
x=(int *)malloc(n*sizeof(int));
printf(“Enter numbers:”);
for(i=0;i<n;++i)
scanf(“%d”,(x+i));
count(x,&ecount,&ocount,n);
printf(“\nTotal even nos.=%d”,ecount);
printf(“\nTotal odd nos.=%d”,ocount);
getch();
}
void count(int *x,int *e,int *o,int n)
{
int i;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …285 286 … A Complete Refresh Manual of C Programming


13. Write a c program to read any two different numbers x and y, find 15. Write a function which takes two numbers as parameters and
multiplication of them using function. returns maximum of those two numbers.
Ans: #include <stdio.h> Ans: #include <stdio.h>
#include <conio.h> #include <conio.h>
int multiplication (int,int);
void main() int greater (int,int);
{ void main()
int x,y,z; {
printf(“Enter value of and b:”); int a,b,c;
scanf(“%d%d”,&x,&y); printf(“Enter value of and b:”);
z=multiplication(x,y); scanf(“%d%d”,&a,&b);
printf(“Multiplicationof two nos.=%d”,z); c=greater(a,b);
getch(); printf(“Greater number=%d”,c);
} getch();
int multiplication(int x,int y)
{ }
int z; int greater (int x,int y)
z=x*y; {
return z; if(x>y)
} return x;
Result: else
Enter value of and b:2 5 return y;
Multiplication of two nos=10 }
14. Write a program in C to calculate the frequency (F) for different Result:
values of capacitances (c), for a certain electrical circuit with an Enter value of and b:5 2
inductance (L) and resistance (R), the damped natural frequency is
1 R2 Greater number=5
given by F = LC – 4C2 . It is required to study the variation of getch();
}
this frequency with capacitance starting from 0.01 in steps of 0.01
and calculation should be done using user defined function. float calc(float 1,float r,float c)
[T.U. 2068 Baisakh] {
Ans: #include<stdio.h> float f;
f=sqrt(1/(1*c)-(r*r)/(4*c*c));
#include<conio.h> return(f);
#include<math.h>
float calc(float,float,float);
{
float I,e,r,f;
clrscr();
printf(“\nEnter the value of inductance and resistance.”)
scanf(“%f”,&1,&r);
for(c=0.01;c<=0.1;c=c+0.01)
{
f=calc(l,r,c);
printf(“\nFrequency=%f”,f);
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
getch ( );
16. Write a function to calculate factorial of an integer. }
Ans: #include <stdio.h> long int factorial (int n)
#include <conio.h> {
long int factorial (int); long int fact = 1;
void main ( ) for (int i = 1;i<=n; i ++)
{ fact = fact * i;
int n; return fact;
long int fact; }
printf ("Enter a number ="); Result:
scanf ("%d", &n); Enter a number =5
fact = factorial (n); Factorial number of 5 = 120.
printf ("Factorial number of %d = %ld.",
n,fact);
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …287 288 … A Complete Refresh Manual of C Programming


17. Write a complete program that reads numerical values for x and n printf ("Sum of digits using recursion =
and evaluate the formula y=xn. Your program must have a function %d\n", rs);
getch ( );
to calculate the result and return it. Assume both x and n are integer
}
and you can not use pow() function. [T.U. 2058] int wsum (int n)
Ans: #include<stdio.h> {
#include<conio.h> int r, sum = 0;
int pow1(int,int); while (n > 0)
void main ( ) {
{ r = n%10;
int x, n; sum = sum + r;
int power1; n = n/10;
printf ("Enter two numbers = "); }
scanf ("%d %d",&x,&n); return sum;
power1 = pow1(x,n); }
printf ("\n %d to the power %d = %d", x, int rsum (int n)
n,power1); {
getch ( ); int r, sum = 0;
} if (n! = 0)
int pow1(int x, int n) {
{ r = n%10;
int i; sum = r + rsum (n/10);
int p = 1; }
for (i = 1;i<=n;i++) return sum;
p = p * x; }
return p;
}
Result:
Enter number =123
Result:
Enter two numbers =2 3 Sum of digits without recursion=6
Sum of digits using recursion=6
2 to the power 3=8

{
18. A digit positive integer is entered through the keyboard, write a int s, rs;
function to calculate sum of digits of number. int n;
(a) Without using recursion. printf ("Enter number =");
(b) Using recursion. scanf ("%d", &n);
s = wsum (n);
Ans: #include <stdio.h> printf ("Sum of digits without recursion
#include <conio.h>
=
int wsum (int);
%d\n",s);
int rsum (int);
rs = rsum (n);
void main ( )
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
19. Write a program to print 10 positive integers and their factorials.
Ans: #include<stdio.h>
#include<conio.h>
long int factorial (int);
void main ( )
{
int i;
printf ("\nFactorial numbers are:\n");
for(i=1;i <=10; i++)
{
printf ("%d=%ld\n",i,factorial(i));
}
getch ( );
}
long int factorial(int n)
{
long int fact = 1;
int i;
for (i = 1; i <= n; i++)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …289 290 … A Complete Refresh Manual of C Programming


fact = fact * i; 21. Write a program to find the value of f(x) when x is given and
return fact; satisfies the followings:
} F(x)=2x.x+3x+4 when x<2
=0 when x=0
Result: = -2x.x+3x+4 when x>2
1=1 Ans: #include<stdio.h>
2=2 #include<conio.h>
3=6 #include<math.h>
float f1(float);
4=24 float f2(float);
5=120 void main ( )
6=720 {
float x;
7=5040 printf("Enter the value of x:");
8=40320 scanf("%f",&x);
9=362880 if(x<2)
printf("\nThe value of the
10=3628800 function=%f",f1(x));
else if(x==2)
20. Write a C program to find sum of ‘n’ numbers which is divisible by 5 printf("\nThe value of function for x=2
using function. is 0\n");
else
Ans: #include<stdio.h> printf("The value for x=%f is
#include<conio.h> %f\n",x,f2(x));
int sum(int); getch();
void main ( ) }
{ float f1(x) //if x<2
int x, y; float x;
printf ("Enter any number = "); {
scanf ("%d", &x); return (2*x*x+3*x+4);
y=sum(x); }
float f2(x) //if x>2
printf("sum=%d",y);
float x;
getch ( ); {
} return (-2*x*x+3*x-4);
int sum(int x) }
{ return s;
int i,s=0; }
for (i =1; i<=x; i++)
{ Result:
if(i%5==0) Enter any number =10
s=s+i;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
} 22. Write a program that passes an array to a function and print the
Result: largest and smallest element. [T.U. 2069 Ashad]
Enter the value of x:5 Ans: #include<stdio.h>
#include<conio.h>
The value for x=5.000000 void numbers(int no[100],int n );
is -39.000000. void main ( )
{
int n,no[100],i;
Sum=15 printf ("Enter the value of n =");
scanf ("%d", &n);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …291 292 … A Complete Refresh Manual of C Programming


for (i = 0; i<n; i++) r=n%10;
{ rev=rev*10+r;
printf ("Enter numbers :"); n=n/10;
scanf("%d",&no[i]); }
} return rev;
numbers(no,n); }
getch ( ); Result:
} Enter an integer:567
void numbers(int no[100],int n)
{ Reversed numbers=765
int max,min;
max=no[0]; 24. Write a program to evaluate the series until the term becomes less
min=no[0];
for (int i=0;i<n;i++) than 10-6.
{ sn=1+x/1!+x2/2!+x3/3!.................... [T.U. 2062 Baisakh]
if(no[i]> max) Ans: #include<stdio.h>
max=no[i]; #include<conio.h>
if(no[i]<min)
#include<math.h>
min=no[i];
} long int series(int);
printf(“\nMaximum no=%d”,max); void main()
printf(“\nMinimum no=%d”,min); {

Minimum no=10 printf(“Reversed


numbers=%d”,reverse(n));
getch();
23. Write a function that takes an integer number of any digits and }
int reverse(int n)
returns the number reversed. In the calling function read a number, {
pass it to the function, and display the result. int rev=0,r;
[T.U. 2061 Poush] while(n!=0)
Ans: #include <stdio.h> {
#include <conio.h>
int reverse(int);
void main()
{
int n;
printf(“Enter an integer:”);
scanf(“%d”,&n);
} int i=0;
F -X C h a n ge F -X C h a n ge
PD PD
Result: float a;

!
W

W
Enter the value of n =5 double term=0,s=0;
O

O
N

N
y

y
bu
Enter numbers:50 10 15 20 25

bu
printf("Enter the value of a:");
to

to
ww

ww
om

om
k

k
lic

lic
scanf("%f",&a);
C

C
.c

.c
w

w
tr re tr re
Maximum no=50
.

.
ac ac
k e r- s o ft w a do{ k e r- s o ft w a

s=s+term;
term=pow(a,i)/series(i);
printf("Term=%lf\n",term);
++i;
}while(term>0.000001);
printf("Sum=%lf",s);
getch();
}
long int series(int n)
{
long int fact=1;
int j;
if(n==0)
return 1; else
{
for(j=1;j<=n;++j)
fact=fact*j; return
fact;
}
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …293 294 … A Complete Refresh Manual of C Programming


Result: void main()
Enter the value of a:1.25 {
Term=1.000000 char str1[20],str2[20];
Term=1.250000 int n;
Term=0.781250 clrscr();
Term=0.325521 printf("Enter the 1st string:");
Term=0.101725 gets(str1);
Term=0.025431 printf("Enter the 2nd string:");
Term=0.005298 gets(str2);
Term=0.000946
Term=0.000148 printf("Enter the index after which u want to
Term=0.000021 insert the string : ");
Term=0.000003 scanf("%d",&n);
Term=0.000000 insert(str1,str2,n);
Sum=3.490343 printf(“New sstring is:”);
puts(str1);
25. Write a program that takes a string from user and pass it to 26. Write a complete program to insert a string into another string in the
function. The function finds and returns number of words int the location specified by the user. Read the string in main function, pass
string. In the main program, display the number of words. them to another function along with inserting position and returns
[T.U. 2061 Baisakh] the resulting string. [T.U. 2067 Ashwin]
Ans: #include <stdio.h> Ans: #include<stdio.h>
#include <conio.h> #include<conio.h>
int wordcount(char []); #include<string.h>
void main() void insert(char [],char[],int);
{
Char str[80];
int i;
Printf(“Enter the string:\n”);
gets(str);
I=wordcount(str);
Printf(“Total number of words=%d”,i);
getch();
}
Int wordcount(char str[])
{
Int i,j=0;
For(i=0;str[i]!=’\0’;++i)
{if(str[i]==’ ‘)
++i;
}
Return i;
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
getch();
}
void insert(char str1[20],char str2[20],int n)
{
int i,j;
char temp[20];
for(i=n-1;j=0;str1[i]!=’\0’;++i;++j)
temp[i]=str1[i];
temp[j]=’\0’;
for(i=n-1;j=0;str2[j]!=’\0’;++i;++j)
str1[i]=[str2[j];
for(i=n-1;j=0;str1[i]!=’\0’;++i;++j)
str2[i]=temp[j];
str2[i]=’\0’;
}
27. Write a recursive function to find the sum of natural numbers. Test
the function in your main program. [T.U. 2062 Poush]
Ans: #include <stdio.h>
#include <conio.h>
void main ( )
{
int n;
static int i=1,sum=0;

if(i==1)
{
printf ("How many terms to add:-");
scanf ("% d",&n);
}
if(i<=n)
{
sum=sum+i;
i++;
main();
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …295 296 … A Complete Refresh Manual of C Programming


printf(“\n Sum=%d”,sum); {
getch(); int pro=1;
} if (n == 1)
Result: return pro;
How many terms to add:-5 else
pro= n * product(n – 1);
Sum of non-negative nos=15 return pro;
}
28. Write a program to print particular term of fibonacci series.
Ans: #include<stdio.h> Result:
#include<conio.h> Enter how many terms :-5
int fibonacci (int n);
void main ( ) Sum of non-negative nos=120
{
int n, res; 30. Write a program to generate multiplication table of a number
printf ("Enter number:"); entered by user using recursive function.
scanf ("%d", &n); Ans: #include<stdio.h>
res = fibonacci (n);
#include<conio.h>
printf ("Particular term is= %d",res);
getch ( ); int table (int,int);
} void main ( )
int fibonacci (int n) {
{ int n,p;
if (n == 1 || n==0) printf ("Enter nunmbers :-");
return 0; scanf ("%d", & n);
else if(n==2) for(p=1;p<=10;++p)
return 1; printf("%d x%d=%d\n",n,p,table(n,p));
else getch ( );
return(fibonacci(n-1)+fibonacci(n- 2));
}
} printf ("Enter how many terms :-");
Result: scanf ("% d", & n);
result = product (n);
Enter number:5 printf ("Sum of non-negative nos=%d",
The particular=3. result);
getch ( );
29. Write computer program to find the product of all numbers from 1 }
int product
to n using recursive function. [ T.U. 2057 Chaitra]
(int n)
Ans: #include <stdio.h>
#include <conio.h>
int product (int);
void main ( )
{
int n, result;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

int table(int n,int p)


{

if (p== 1)
return n; else
return(table(n,p-1)+n);
}
Result:
Enter nunmbers :-5
5x1=5
5x2=10
5x3=15
5x4=20
5x5=25
5x6=30
5x7=35
5x8=40
5x9=45
5x10=50
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …297 298 … A Complete Refresh Manual of C Programming


31. Write a program to find sum of given non-negative integer numbers getch();
using a recursive function. [T.U. 2064 Falgun] exit(1);
Ans: include <stdio.h> }
if(y==0 || y==x)
#include <conio.h>
{
int sum(int);
return 1;
void main ( )
{ }
else
int n, result;
{
printf ("Enter how many terms :-");
return (binarycoeff(x-1,y-1)+
scanf ("% d", & n);
binarycoeff(x-1,y));
result = sum(n);
}
printf ("Sum of non-negative nos=%d",
}
result);
getch ( ); Result:
} Enter the values of n and r:6 2
int sum(int n) Binomial coefficient of C(6,2) is 15.
{
int pro; 33. Write a program to find the greatest common divisior between two
if (n == 0) number.
return 0;
Ans: #include<conio.h>
else
pro= n + sum(n – 1); #include<stdio.h>
return pro; int recgcd(int,int);
} void main()
{
Result: int a,b,gcd;
Enter how many terms :-5 %d",n,r,ncr);
getch();
Sum of non-negative nos=15 }
int binarycoeff(int x,int y)
32. Write a program to calculate the binary coefficient of nCr of two {
numbers. Which can be calculated as n!/((n-r)!*r!). if(y>x)
Ans: #include<conio.h> {
#include<stdio.h> printf("The values of n can
#include<process.h> not be less than r.");
int binarycoeff(int,int);
void main()
{
int n,r,ncr;
printf("Enter the values of n and r:");
scanf("%d%d",&n,&r);
ncr=binarycoeff(n,r);
printf("Binary coefficient of C(%d,%d)is
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
printf("Enter two number:");
scanf("%d%d",&a,&b);
gcd=recgcd(a,b);
printf("GCD of %d and %d is=%d",a,b,gcd);
getch();
}
int recgcd(int x,int y)
{
int r;
if(y==0)
{
return x;
}
else
{
r=x%y;
return recgcd(y,r);
}
}
Result:
Enter two number:5 8
GCD of 5 and 8 is 1.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
clrscr();
C Programming Language …299 printf (" Value of m : ");
34. Write a C program to ask the user to enter the value of a number scanf ("%d",&m);
and power to be calculated for that number. Use recursive method. printf (" Value of n : ");
scanf ("%d",&n);
Ans: #include<conio.h>
#include<stdio.h>
sum=sum_recursive(m);
int power(int,int);
printf ("\n\n\n\n%d",sum);
void main()
{
int n,p,result;
printf("Enter the value of n and p:");
scanf("%d%d",&n,&p);
result=power(n,p);
printf("Base %d to power %d is %d.",
n,p,result);
getch();
}
int power(int n,int p)
{
static int r=1;
if(p==0)
{
return 1;
}
else
{ r=r*n;
power(n,p-1);
}
return r;
}
Result:
Enter the value of n and p:2 3
Base 2 to power 3 is 8.

35. Write a recursive code to compute the sum of squares as shown in


the series
m2 + (m+1)2 +…. + n2 for m, n integers 1 m n
Ans: #include<conio.h>
#include<stdio.h>
int n;
void main()
{
int m,sum;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
int n,s;
300 … A Complete Refresh Manual of C Programming printf(“Enter number of terms:”);
} scanf(“%d”,&n);
int sum_recursive(int m) s=sum(n);
{ printf(“\n Sum=%d”,s);
int sum; getch();
if (m == n) }
return (n*n); int sum(int n)
else {
sum = (m*m) + sum_recursive(m+1);
printf ("\t%d",sum);
return sum;
}

36. Write a nested macro that gives the minimum of three values.
Ans: #include<conio.h>
#include<stdio.h>
#define min(a,b) ((a>b)?b:a)
#define minthree(a,b,c) (min(min(a,b),c))
void main()
{
int x,y,z,w;
clrscr();
printf("Enter three numbers :\n");
scanf("%d%d%d",&x,&y,&w);
z=minthree(x,y,w);
printf("Minimum of three value is %d",z);
getch();
}
Result:
Enter three numbers :20 3 8

Minimum of three value is 3.

37. Write aprogram using recursion to compute the sum of following


series:
12-22+32-42…………………+(-1)a+1 n2 without using pow()
function.You should read the value of n from the user.
[T.U. 2065 Shrawan]
Ans: #include<conio.h>
#include<stdio.h>
int sum(int);
void main()
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …301 302 … A Complete Refresh Manual of C Programming


int s=1,i; calculates the sum. Your program should have more then two
if(n==0) functions. [T.U. 2067 Ashwin]
return 0; (2*3/5)+(4*5/7)+(6*7/9)+………………………..
else
{ Ans: #include<conio.h>
for(i=1;i<n;i++) s=s+n;
s=s*-1; c=c+1;
return (s*n*n+sum(n-1)); avg=(float)s/c;
} return avg;
}
}
38. Write a program to read number and call a function till ‘yes’ is 39. Write a code in C to calculate the sum of following series up to n
entered by the user. You should count and sum the numbers using terms specified by the user where n is passed to the function that
static variables in the function and return the average to the main
function. [T.U. 2065 Shrawan]
Ans: #include<conio.h>
#include<stdio.h>
float average(int);
void main()
{
int n;
float a;
char ch[5];
do
{
printf(“Enter value of n:”):
scanf(“%d”,&n);
a=average(n);
printf(“Do you want to continue(y/n)?”);
scanf(“%s”,ch);
}while(strcmp(ch,”yes”)==0);
printf(“Average=%f”,a);
getch();
}
float average(int n)
{
static int s=0,c=0;
float avg;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
#include<stdio.h> scanf(“%d”,&n);
float sum(int);
int fun(int);
void main()
{
int n;
float s;

printf(“Enter value of n:”):


scanf(“%d”,&n);
s=sum(n);
printf(“Sum=%f”,s);
getch();
}
float sum(int n)
{
int i,t=2,num;
float s=0;
for(i=0;i<n;++i)
s=s+(float)num/(t+3);
t=t+2;
}
return s;
}
int fun(int t)
{
return (t*(t+1));
}

40. Write a program to read the marks obtained by the students of a


class in one subject. You should use malloc() so that only required
memory is occupied. Pass the numbers to a function that calculates
average. Display the average from the calling function.
[T.U. 2066 Jestha]
Ans: #include<conio.h>
#include<stdio.h>
float marks(float *,int);
void main()
{
float *m,avg;
int n,i;
printf(“How many students?:”);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …303 304 … A Complete Refresh Manual of C Programming


m=(float*)malloc(n*sizeof(float)); 2.12 Structure
for(i=0;i<n;++i)
{ 1. What is a structure ? How structure is declared?Explain.
printf(“Enter marks of students:”): Or, What is a structure? When do we use the structure?
scanf(“%f”,(m+i)); [T.U. 2058 Chaitra]
} Ans: Structure [T.U. 2066 Jestha, 2067 Ashwin]
avg=marks(m,n); A structure is a collection of one or more variables grouped
getch(); under a single name for easy manipulation. The variables in a
} structure, unlike those in an array, can be of different variable types. A
float marks(float *m,int n) structure can contain any of C's data types, including arrays and other
{ structures. Each variable within a structure is called a member of the
float a=0; int i; structure.
for(i=0;i<n;++i) It is a data type which help us to collect various types of data
a=a+*(m+i)); items having same name.It is the tool which help the programmer for
a=a/n; handling a group of logically related data items.
return a;
} Declaration of a structure
syntax > struct user_defined_name
{ tag or structure name
data_type member 1;

};
data_type member 2;

}
..................................
..................................
data_type member n;
structure members
structure type variables
structure user_defined_name var1, var2, ........;
e.g. struct student
{
char name [20];
int class;
int age;
};
struct student a;
In the above example,
struct =keyword
student = structure data type name
name[20],class and age =Member name
a=declaring structure variable
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
The data members are accessed by structure variables with followed
by a . (period sign), called dot operator.
The data of structure can be accessed in the way
a . name;
a . class;
a . age;
with the help of dot operator.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …305 306 … A Complete Refresh Manual of C Programming


Example: int age; {
/* Declare a structure and instance together */ printf ("Enter name:"); char name [20];
struct date { gets (name); int age;
char month[2]; printf ("Enter age \n"); } one;
char day[2];
char year[4]; scanf ("%d", &age); printf ("Enter name :\n");
} current_date; printf("\n Name :%s", name); scanf ("%s", one.name);
printf ("Age:%d", age); printf ("\n Enter age:");
2. Differentiate between array and structure with examples. getch ( ); scanf ("%d", &one.age);
[T.U. 2061 Poush, 2066 Jestha, 2068 Mangsir] } printf ("\n Name : %s",
Ans: Differentiation between array and structure : one.name);
Array Structure printf ("Age :%d", one.age);
(a) Array is the collection of (a) It is a kind of user defined getch ( );
data items which will have data type which can store the }
the same name. data of various type such as 3. Define a structure. How it is different from union? Write a C
character, integer etc. program to illustrate a structure.
(b) The individual array (b) Structure is not represented Ans: Structures and union
elements are distinguished by index or subscript. A structure contains an ordered group of data objects. Unlike
from one another by value the elements of an array, the data objects within a structure can have
that is assigned to a subscript varied data types. Each data object in a structure is a member or field.
or index. A union is an object similar to a structure except that
(c) Array has its type and these (c) Structure has no type 1. In union, one block is used by all the member of the union but
are : in case of structure, each member has their own memory space.
(i) one dimensional array All of union members start at the same location in memory. A
(ii) multi dimensional array union variable can represent the value of only one of its
(d) The syntax of array : (d) Syntax of structure : members at a time.
(i) One dimensional array : struct user_defined_name
data_type array_name [size of { 2. The size of the union is equal to the size of the largest member
array]; data_type member1; of the union where as size of the structure is the sum of the size
It consists only rows or columns data_type member2; of all members of the structure.
For example
i.e. char name [20]; .................................... struct book
data_type membern; {
(ii) Multi-dimensional array : }; char name;
data_type array_name[exp1] struct user_defined_name int pages;
[exp2 ]; var1, var2, ..................... float price;
e.g. char name [5] [25]; e.g. struct student { };
It contains rows and columns. char name [20]; Now if we define struct book book1, then it will assign 1+2+4=7
int age; bytes of memory for book1.
}; If we define it as union like
struct student one ; union book
(e) Example : Display name & (e) Example : Display name &
age: age:
#include <stdio.h> #include <stdio.h>
#include <conio.h> #include <conio.h>
void main ( ) void main ( )
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
{
char name;
int pages;
float price;
};
The compiler allocates a piece of storage that is large enough to
store the largest variable types in union. All three variables will share
the same address and 4 bytes of memory is allocated to it. This
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
printf("%s",stu[i].name);
C Programming Language …307 printf("\nroll no");
program of structure will read name, roll no and marks in 6 subject of printf("%d",stu[i].roll_no);
3 students & then display name and roll of student who scored more for(j=0;j<6;j++)
{
than 70% marks in total.
printf("\nmarks in %d
#include<stdio.h> subject\t",j+1);
#include<conio.h> printf("%d",stu[i].marks[j]);
struct student
{
char name[10];
int roll_no;
int marks[6];
int total;
int per;
};
void main()
{
struct student stu[3];
int i,j,req;
clrscr();
for(i=0;i<3;i++)
{
stu[i].total=0;
printf("enter data for %d students
:",i+1); printf("\nenter name");
scanf("%s",stu[i].name);
printf("\nenter roll no ");
scanf("%d",&stu[i].roll_no);
printf("\nenter marks in subjects\t");
for(j=0;j<6;j++)
{
printf("\nenter marks in %d
subject\t",j+1);
scanf("%d",&stu[i].marks[j]);
stu[i].total=stu[i].total+stu[i].marks[j];
}
stu[i].per=stu[i].total/6;
printf("\n");
}
for(i=0;i<3;i++)
{
if(stu[i].per>70)
{
printf("\nSTUDENT %d",i+1);
printf("\nname :");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
int main()
308 … A Complete Refresh Manual of C Programming {
} company employee[MAX];
printf("\nTOTAL :%d",stu[i].total); int n;
} printf(“A program for collecting employee\n”);
} information";
getch(); printf(“And displaying the collected
} information");
4. What do you understand by structure? Explain about printf("How many employees:");
nested structure with examples. [T.U. scanf(“%d”,&n);
2061 Shrawan] void CollectInformtion(company
employee[MAX], int n);
Ans: void Display(company employee[MAX], int n);
Structure:Structure,Question no(1)
Nested structure // functions calling
When a structure is decleared as the member of CollectInformtion(employee, n);
another structue, it is called Structure within a structure. It is Display(employee, n);
also known as
nested
structure.
Example:
Write a program which can collect employee
information(such
as employee name, id, sex, date of birth etc.) of a
company and display the collected information t
#include<iostream.h>
#include<string.h>
#define MAX
1000 struct
date{
int
day;
int
month
; int
year;
};
struct company{
char name[20];
long int employee_id;
char sex[5];
int age;
struct date dob;
};
company employee[MAX];
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …309 310 … A Complete Refresh Manual of C Programming


cin.get(); Output of the program
return 0;
}
void CollectInformtion(company employee[MAX],
int n){
printf("Enter the following information:");

for (int i=1; i<=n; i++){


printf("Enter information for employee no:
%d",i); printf("Name :";
scanf(“%s”,employee[i].name);
printf("ID :");
scanf(“%d”,mployee[i].employee_id);
printf("Sex :");
scanf(%s”,employee[i].sex);
printf("Age :");
scanf(“%d”,employee[i].age);
printf("Date of Birth:\n”);
printf("Day :");
scanf(“%d”,employee[i].dob.day);
printf("Month :");
canf(“%d”,employee[i].dob.month);
printf("Year :");
scanf(“%d”,employee[i].dob.year);
}
}
void Display(company employee[MAX], int n){
printf("Employee entered information:\n");
printf( "Name ID Sex Age Date
of Birth\n");
for (int i=1; i<=n; i++){
printf(“%s\n”,employee[i].name);
printf(“%d\n”,employee[i].employee_id);
printf(“%s\n”,employee[i].sex; cout");
printf(“%d\n”,employee[i].age; cout");
printf(“%s\n”,employee[i].dob.day");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
printf(“%s\n”,employee[i].dob.month");
printf(“%s\n”,employee[i].dob.year);
}
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
char name [15];
C Programming Language …311 float price;
int pages;
2.13 C Programming - 7 } list [10];
int i;
1. Write a program to read roll number, name and age of a student and
display it in proper format. // Entering data from keyboard
Ans: #include<stdio.h> for (i = 0; i < 10; i + +)
#include<conio.h> {
struct student{
int rollno;
char name[20];
int age;
}a;
void main()
{
printf(“Enter roll number:”);
scanf(“%d”,&a.rollno);
printf(“Enter name:”);
scanf(“%s”,a.name);
printf(“Enter age:”);
scanf(“%d”,&a.age);

printf(“Name=%d\nAge=%s\nRoll
no=%d”,a.rollno,a.name,a.age);
getch();
}
Result:
Enter roll number:2
Enter name:manish
Enter age:25

Name=Manish
Age=25
Roll Number=2

2. Write a program to enter name, price and pages of 10 different


books and display them in tabular format.
Ans: #include<stdio.h>
#include<conio.h>
void main ( )
{
struct book
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
{
312 … A Complete Refresh Manual of C Programming int tot=0,per,i;
printf ("Enter name, price & pages of %d printf("Enter name:");
book:",(i + 1)); scanf("%s",list.name);
scanf ("%s %f %d", list [i].name, &list [i]. for(i=0;i<5;i++)
price,&list [i]. pages); {
} printf("Enter mark:");
scanf("%d",&list.mark[i]);
// Displaying data tot=tot+list.mark[i];
printf ("Name \t . price \t pages \n");
for (i = 0; i < 10; i + +)
{
printf ("%s \ t % f \t % d\n", list
[i].name, list [i].price, list [i]. pages);
}
getch ( );
}

Result:
Enter name, price & pages of 1 book:
Practical Physics 200 300
Enter name, price & pages of 1 book:
Practical Chemistry 344 500
………………………… ……………………… ………………………
Enter name, price & pages of 1 book:
C programming 300 400

Book Name Price Page


Practical Physics 200 300
Practical chemistry 344 500
………………………… ……………… ……………………
C programming 300 400

3. Write a C program to read name, marks in 5 different subjects of a


student, find total, percentage. Print name, marks, total and
percentage in tabular format.
Ans: #include<stdio.h>
#include<conio.h>
struct student{
char name[20];
int mark[5];
}list;
void main()
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …313 314 … A Complete Refresh Manual of C Programming


} list[i].phone>9777777);
per=tot/5; }
printf("NAME\tPHYSICS\tMATHS\tCHEM\tCOMP. // Displahing data
\tNEP\t TOTAL\t PER\n"); printf ("Name \t Address \t Phone number
printf("\n--------------------------------"); \n");
printf("%s\t",list.name); for (i = 0; i < 5; i + +)
for(i=0;i<5;i++) printf ("% s \ t% s \t% ld \n", list [i]. name,
printf("%d\t",list.mark[i]); list [i].address, list [i]. phone );
printf("%d\t%d\n",per,tot); getch ( );
getch(); }
}

Result: Enter name :Akash


Enter name:Ram Enter address:Patan
Enter mark:60 Enter phone number:544554
Enter mark:85 Enter phone number:5543593
Enter mark:76
Enter mark:89 Enter name :Minu
Enter mark:70 Enter address:Naxal

NAME PHYSICS MATHS CHEM COMP. NEP TOTAL PER …………………………………………………….


--------------------------------------------- {
Ram 60 85 76 89 70 380 76 printf ("Enter name :");
scanf(“%s”,list [i].name);
printf ("Enter address:");
4. Write a program in which you have to enter name, address and scanf(“%s”,list [i].address);
phone number of 5 different students and display all those do {
printf ("Enter phone number:");
information in tabular form. Phone number should be in between scanf ("%ld", & list [i].phone);
5000000 and 9777777. } while(list[i].phone<5000000||
Ans: #include <stdio.h>
#include <conio.h>
struct student
{
char name [20], address [15];
long int phone;
} list [5];
void main ( )
{
int i;
/* Entering name, address & phone number
of 5 diff. students */
for (i = 0; i < 5; i + +)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
…………………………………………………
…………………………………………………………
Enter name :Lila
Enter address:Kupondol
Enter phone number:5543344

Name Address Phone number


Akash Patan 5543596
Minu Naxal 5480800
………….. …………………. ………………………
Lila Kupondol 5543344

5. Write a structure containing processor, memory, HDD, monitor,


casing as members .Use this structure in a program to read
data(price) for five different computers and display the data as well
as total price of computer on the screen. [T.U. 2063 Baisakh]
Ans: #include <stdio.h>
#include <conio.h>
struct devices
{
int processor,memory,HDD;
int monitor,casing;
}a[5];
void main ( )
{
int i;
/* Entering data for 5 different
compuiters*/

for (i = 0; i < 5; i + +)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …315


SN Processor Memory HDD Monitor Casing Total
{ ………………………………………………………………………………………………………………………
printf ("\nEnter price of processor:"); 1 4500 1800 3000 10000 1500 20800
scanf(“%d”,&a[i].processor); …………………………………………………………………………………………………………………….
printf ("\nEnter price of memory:");
……………………………………………………………………………………………………………………1 10
scanf(“%d”,&a[i].memory);
printf ("\nEnter price of HDD:"); 4000 1600 3200 9500 2000 20300
scanf(“%d”,&a[i].HDD);
printf ("\nEnter price of monitor:");
scanf(“%d”,&a[i].monitor);
printf ("\nEnter price of casing:");
scanf(“%d”,&a[i].casing);
}
//Displaying all the data with price

Printf(“\nSN\tProcessor\tMemory\tHDD\t
Monitor\t Casing\t Total”);
Printf(“\n………………………………………………………………………”):
for (i = 0; i < 5; i + +)
{
Printf(“\n%d\t%d\t%d\t%d\t%d\t%d\t%d”,
i+1,a[i].pricessor,a[i].memory,a[i].HDD
,a[i].monitor,a[i].casing,a[i].processor
+a[i].memory+a[i].HDD+a[i].monitor+
a[i].casing);
}
getch();
}

Result:
Enter price of processor:4500
Enter price of memory:1800
Enter price of HDD:3000
Enter price of monitor:10000
Enter price of casing:1500
………………………………………………………………….
……………………………………………………………………
……………………………………………………………………
Enter price of processor:4000
Enter price of memory:1600
Enter price of HDD:3200
Enter price of monitor:9500
Enter price of casing:2000
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
mark [j];
316 … A Complete Refresh Manual of C Programming }
6. Write a program to read and display the }
name,address,telephone number and salary of an employee
// Displaying result
using structure. [T.U. 2057]
printf ("\ n Roll number \t Name \t
Ans: We can solve this as structure, question no (1). Total\n");
7. Write a computer program to read and display the name, printf("......................... \n");
address for (i = 0; i < 10; i + +)
,account number and balance of a person using structure. printf ("%d \t % s \t %f", list [i]. roll,
[T.U. 2058 list [i].name,
Poush] Ans: We can solve this as structure,question no(1). list [i].total);
8. Program that reads the name, roll number and marks in 5 getch ( );
different subjects of 10 students and prints name, roll }
and total marks obtained by each student.
Ans: #include
<stdio.h>
#include <conio.h>
struct student
{
int roll;
char name [20];
float mark [5], total;
};
void main ( )
{
int i, j;
struct student list [10];

// Entering data
for (i = 0; i < 10; i + +)
{
printf ("Enter name :");
scanf("%s”,list
[i].name); printf ("Enter
Roll number:"); scanf
("%d", &list [i]. roll);
list [i].total = 0;
printf ("Enter marks in 5
different subjects:\n");
for (j = 0; j < 5; j + +)
{
scanf ("%f", & list [i].
mark[j]); list [i].total =
list [i].total + list [i].
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …317 318 … A Complete Refresh Manual of C Programming


Result: printf("The result\n");
Enter name :Ramu printf(“Name\t\tAge\n”);
Enter Roll number:200 printf(“…………………………………………….\n”);
Enter marks in 5 different subjects: strcpy(a[i].temp,a[i].name);
40 35 45 50 70 strcpy(a[i].name,a[j].name);
…………………………………………………………. strcpy(a[j].name,a[i].temp);
a[i].temp1=a[i].age;
……………………………………………………………
a[i].age=a[j].age;
…………………………………………………………… a[j].age=a[i].temp1;
Enter name :Rajni }
Enter Roll number:203 }
Enter marks in 5 different subjects:
70 90 80 65 98

Roll number Name Total


……………………………………………………………………………………………………………
200 Ramu 240
……… ………. ……….
203 Rajni 403

9. Write a program that reads name and age of 10 different students


as two members of structure name “students”. Display the name and
corresponding age of the students stored in an alphabetical order.
[T.U. 2068 Baisakh]
Ans: #include<stdio.h>
#include<conio.h>
#include<string.h>
struct students{
char name[80],temp[80];
int age,temp1;
}a[10];
void main()
{

int i,j;
printf("enter name and age:");
for(i=0;i<10;i++)
scanf("%s%d",a[i].name,a[i].age);
for(i=0;i<10;i++)
{ for(j=i+1;j<10;j++)
if(strcmp(a[i].name,a[j].name)>0)
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
for(i=0;i<10;i++) {
printf("%s\t%d\n",a[i].name,a[i].age); int n, i, total = 0;
getch(); float average;
} printf ("\nEnter number of students:");
Result:
Enter name and age:Madan 27
Enter name and age:Kamal 24
Enter name and age:Laila 25
Enter name and age:Chhaila 45
Enter name and age:Pankaj 43

The result is
Name Age
…………………………………………………
Chhaila 45
Kamal 24
Laila 25
Madan 27
Pankaj 43

10. An engineering college has asked to write HLL program to help


them analyze their class test scores. The program must first ask for
the number of students 'n' and should have a looping structure that
loops through 'n' times to accept, validate and store the data in
array. The structure for each student is given below:
Field name Field type Size Validation rule
Roll numeric 2 1-99
Name alphanumeric 25
Marks numeric 2.1 0.0 – 10.0
The program must do :
(i) Print out the data for students who have failed (obtained
marks <4.0)
(ii) Print out the data for students scoring more than 7.9.
(iii) Print out the average class marks.
Ans #include<stdio.h>
#include<conio.h>
struct student
{
int roll;
char name [25];
float mark;
} list [100];
void main ( )
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …319 320 … A Complete Refresh Manual of C Programming


scanf ("%d", &n); 11. A graduation college in Kathmandu is in the process of computering
its examination system. The following is the data structure for
// Entering data students marks processing.
for (i = 0; i < n;i++)
{ Field Name Field Type Size Validation Rule
printf ("\nEnter roll number :"); Regno Numeric 6 030099-060099
do Name Alphabetic 20 -
{ Year Numeric 2 98-99
scanf ("%d", &list[i].roll); Enter name
Subject 1 :Ramesh
Numeric 3 0-100
}while(list[i].roll<1||list[i].roll> 99); Enter mark :5
Subject 2 Numeric 3 0-100
fflush (stdin); Subject 3 Numeric
Enter roll number :3 3 0-100
printf ("\nEnter name :"); Subject
Enter name4 :Rekha
Numeric 3 0-100
scanf ("%s", list [i]. name); Subject 5 Numeric 3 0-100
printf ("\nEnter mark :"); Enter mark :7
do Average marks =6.00
{
scanf ("%f", & list [i].mark);
}while (list [i].mark < 0 || list [i].mark
> 10);
total = total + list [i]. mark;
}
average = total/n;

// Displaying results
for (i = 0; i < n; i++)
{
if (list [i]. mark <4. 0)
printf("Roll = %d \n Name = % s \n Mark =
% f ",list[i].roll, list [i]. name, list
[i]. mark);
else if (list [i].mark > 7.9)
printf ("Roll = %d \n Name = %s \n Mark =
%f \n mark is more than 7.9", list [i].
roll, list [i]. name, list [i]. mark);
else;
}
printf ("Average marks = %.2f ", average);
getch ( );
}
Result:
Enter number of students:2

Enter roll number :4


F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
{
list [i]. total = 0;
printf ("Enter registration number =");
do
{

Develop a computer program in any of the high level


language you are taught in your class. The program should
produce the following outputs using menu system.
List all students with subjectwise marks, total mark,
percentage and result.
Conditional
Rules:
(a) Student must secure mark > or = 40 in order to
pass each subject, failure subject should be marked
with * adjacent to mark.
(b) Student securing > or = 50 and <65 percent marks
in aggregate but without failing in any subject
should be declared II division.
(c) Student securing > or = 65 percent in aggregate
should be declared in first division.
(d) Student securing > or = 40 and < 50 percent marks
should be declared as third division.
Ans:
#include<stdio.h>
#include<con
io.h>
#include<stri
ng.h>
struct
student
{
int regno, year;
char name [20], result [10], div [10];
float mark [5], total, per;
} list [50];
void
main ( )
{
int n, i, j;
printf ("How many students ?");
scanf ("%d", &n);
for (i = 0; i < n; i++)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …321 322 … A Complete Refresh Manual of C Programming


scanf ("%d", &list [i]. regno); printf ("\n Registration Number \t Name \t Year
}while (list [i].regno <30099 || list \t English \t Nepali \t Computer Science
[i].regno >60099); \t Maths \t Account \t Total \t Result \t
fflush (stdin); Percentage \t Division \n");
printf ("Enter name :"); printf(".......................\n");
gets (list [i].name); for (i = 0; i < n;i++)
printf ("Enter year:"); { printf ("%d \t %s \t %d", list
do [i].regno, list [i].name, list[i]. year);
{ for (j = 0; j <5; j++)
scanf ("%d", &list[i]. year); printf ("%f \t", list [i]. mark
}while (list [i]. year <98 || list [i]. year [j]);
> 99); printf (" \f \t %s \t %f \t %s \n", list
for (j = 0; j < 5;j++) [i]. total, list [i]. result, list [i].
{ per, list [i]. div);
printf ("Enter marks:"); }
do getch ( );
{ }
scanf ("%f ", &list [i]. mark [j]); Result:
}while (list [i].mark[j]<0|| list [i]. How many students ?2
mark [j]>100);
list [i].total = list [i]. total + list Enter registration number =40000
[i]. mark [j]; Enter name:Ramesh
} Enter year:98
for (j = 0; j < 5; j++) Enter marks:45 65 78 90 95
{
if (list [i]. mark [j] < 40) Enter registration number =40001
{ Enter name:janaki
strcpy (list [i]. result, Enter year:99
"fail"); Enter marks:55 66 77 90 85
goto down;
} RegNo.Name Year Eng Nep Comp Maths Acc Total Res Per Div
else 40000 Ramesh 98 45 65 78 90 95 373 pass 74 Fir
strcpy (list [i]. result, 40001 Janki 99 75 66 77 90 85 393 pass 78 Fir
"Pass");
} down: 12. Define structure to hold the records of a vechicle owner. Until the
if(strcmp(list[i].result,"passed")== 0) user wants to stop create a new record(dynamically) corresponding
list[i].per=list[i].total/5; to one vechicle owner,populate this record with the information
else entered by the user and add it to the end of the existing records.if the
list [i].per = 0; user wants to stop,then display the records entered.
[T.U. 2064 Jestha]
if (list [i].per==0||list [i]. per < 40) strcpy (list [i]. div, "third");
strcpy (list [i].div, "*"); else if (list [i]. per < 65)
else if (list [i]. per < 50) strcpy (list [i]. div, "second");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
else Ans: #include<stdio.h>
strcpy (list [i]. div, "fir"); #include<conio.h>
} struct vowner
{
// Displaying results char name[20];
char addr[20];
int vnum;
char phone[20];
}
void main()
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …323 324 … A Complete Refresh Manual of C Programming


struct vownr *r; printf("Enter first real and imaginary
int i=0; value:");
scanf("%f%f",&a.real,&a.imag);
char=ch; printf("Enter second real and imaginary
clrscr(); value:");
v=(struct vowner*)malloc(sizeof(struct {
float real,imag;
vowner));
};
do void add(struct complex,struct complex);
{ void sub(struct complex,struct complex);
void main ( )
{
printf(“\nEnter name of owner”); struct complex a,b;
scanf(“%s”,(v+i)->name);
printf(“\nEnter address of owner”);
scanf(“%s”,(v+i)->addr);
printf(“\nEnter vehicle number of owner”);
scanf(“%d”,&(v+i)->vnum);
printf(“\Enter phone no. of owner”);
scanf(“%s”,(v+i)=>phone);
prinf(“\n%s”(v+i)->addr);
i++;
printf(“\nDo you want to continue(y/n)?”);
ch=getche();
}while(ch=’y’);
for(j=0,j<i;j++)
printf(“\nName=% Address=%s Vehicle
Number=%d Phone no.=%s(v+i)=>name,(v+j)-
>addr,(v+i)->vnum,(v+i)->phone);
getch();
}

13. Write a program to manipulate complex numbers using structures.


The structure should contain real and imaginary part. Write
functions to add and subtract complex numbers.
Ans: #include<stdio.h>
#include<conio.h>
struct complex
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
scanf("%f%f",&b.real,&b.imag); void main()
add(a,b);
sub(a,b);
getch();
}
void add(struct complex a1,struct complex a2)
{
float rsum,isum;
rsum=a1.real+a2.real;
isum=a1.imag+a2.imag;
printf("Sum of complex numbers=%f+i(%f)\n",
rsum,isum);
}
void sub(struct complex b1,struct complex b2)
{
float rdif,idif;
rdif=b1.real+b2.real;
idif=b1.imag-b2.imag;
printf("Difference of complex number=
%f+i(%f)\n",rdif,idif);
}
Result:
Enter first real and imaginary value:5 6
Enter second real and imaginary value:7 8

Sum of complex numbers=


12.000000+i(14.000000)
Difference of complex number=
12.000000+i(-2.000000)

14. Create structure TIME containing hour,minute and second as its


member. Write a program that uses this structure to input start time
and stop time in a function which returns the sum and difference of
the start time and stop time in the main program.
[T.U. 2061 Poush, Baisakh]
Ans: #include<stdio.h>
#include<conio.h>
struct TIME
{
int hr,min,sec;
};
void adddiff(struct TIME,struct TIME,struct
TIME*,struct TIME*);
void displaytime(TIME t);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
void displaytime(TIME t)
C Programming Language …325 {
{ printf("%d:%d:%d",t.hr,t.min,t.sec);
struct TIME starttime,stoptime, }
sumtime,diftime; Result:
printf("\n\n Start Time.\n"); Start Time
Enter hour:
printf("Enter hour:\n"); 8
scanf("%d",&starttime.hr);
printf("Enter minute:\n");
scanf("%d",&starttime.min);
printf("Enter second:\n");
scanf("%d",&starttime.sec);

printf("\nStop Time\n");
printf("Enter hour:\n");
scanf("%d",&stoptime.hr);
printf("Enter minute:\n");
scanf("%d",&stoptime.min);
printf("Enter second:\n");
scanf("%d",&stoptime.sec);

adddiff(starttime,stoptime,
&sumtime,&diftime);

printf("\nStart time\n");
displaytime(starttime);
printf("\nStoptime\n");
displaytime(stoptime);
printf("\nAdd time\n");
displaytime(sumtime);
printf("\nSubtract Time\n");
displaytime(diftime);

getch();
}
void adddiff(struct TIME t1,struct TIME t2,struct
TIME *t3,struct TIME *t4)
{
t3->sec=t1.sec+t2.sec;
t3->min=t1.min+t2.min;
t3->hr=t1.hr+t1.hr;
t4->sec=t1.sec-t2.sec;
t4->min=t1.min-t2.min;
t4->hr=t1.hr-t1.hr;
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

326 … A Complete Refresh Manual of C printf(“Enter name:”);


Programming gets(list.name);
Enter minute: printf(“Enter symbol number:”):
30 scanf(“%d”,&list.symb);
Enter second:
30 for(i=0;i<6;++i)
Stop Time {
Enter hour: fflush(stdin);
10 printf(“Enter subject name:”):
Enter hour: scanf(“%”,list.sname[i]);
10 printf(“Enter corresponding marks:”):
Enter hour: scanf(“%f”,&list.mark[i]);
10

Start Time
8:30:30
Stop Time
10:10:10
Add Time
16:40:40
Subtract Time
0:20:20

15. Create a structure STUDENT containing name, symbol


number, name of 6 subjects, marks of each subject and total
mark as its members. Write a program that uses this
structure and reads data for a student and give the total
marks as the output.
[T.U. 2062
Poush] Ans: : #include<stdio.h>
#include<conio.h>
struct
student
{
int symb;
char name[25],sname[6][25];
float mark[6],total;
} list;
void
main ( )
{
int i;
list.total=0;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …327 328 … A Complete Refresh Manual of C Programming


list.total=list.total+list.mark[i]; scanf ("%f", &student[i]. height);
} printf ("Enter weight : \n");
printf("\nSymbol Number\tName\tSub1\t scanf ("%f",&student[i]. weight);
Sub2\tSub3\tSub4\tSub5\tSub6\tTotal\n”); printf ("\n \n");
printf(".............................\n"); }
printf(“%d\t%s\t”,list.symb,list.name); // Calling function
for (i = 0;i<6;i++) printf ("Unsorted data \n");
printf("%f\t”,list.mark[i]);
output (student, n);
printf ("\t%f”,list.total);
getch(); printf ("Sorted data \n\n");
output (student, n);
}
getch ( );
16. Write a program to read a set of names, roll number, sex, height and }
weight of the students from the keyboard and to sort them in
ascending order using a structure within an array data type. // Displaying result
Ans: #include<stdio.h> void output (school student [MAX], int n)
#include<conio.h> {
#include<string.h> printf ("Name \t Roll no \t Sex \t Height \t
#define MAX 250 Weight \n");
int i, n; printf("..............................\n");
struct school for (i = 0; i < n; i++)
{ {
char name [25]; printf ("%s \t % d \t % s \t %f \t %f \t \n",
int rollno; student [i]. name, student [i]. rollno, student
char sex [7]; [i]. sex, student [i]. height, student [i].
float height; weight);
float weight; }
}student [MAX]; }
void main ( )
{ // Sorting
void output (school student [MAX], int n); void sort (school student [MAX], int n)
void sort (school student [MAX], int n); {
f din);
printf ("How many data ?"); f printf ("enter roll number
scanf ("%d", &n); l \n");
u scanf ("%d", &student[i].
// Reading data s rollno);
for (i = 0; i < n; i++) h flush(stdin);
{ ( printf ("Enter sex \n");
printf ("Record = %d \n", i + 1); s scanf ("%s", student
printf ("Enter name : \n"); t [i].sex);
scanf ("%s", student [i].name); printf ("Enter height:\n");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
struc rcmp(student[i].name,
t student[j].name)<=0)
schoo {
l temp = student[i];
temp; student [i] = student [j];
int student [j] = temp;
i, j; }
for }
(i =
0; i
< n;
i++)
{
f
} o
r
Result:
(
j

i
+
1
;

<

n
;
j
+
+
)

i
f
(
s
t
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
How many data ?3
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …329 330 … A Complete Refresh Manual of C Programming


}
Record = 1 Result:
Enter name :Yogesh Enter the donor's first and last names, separated
Enter roll number:4 by a space:Kamala Jha
Enter sex: Male
Enter height:5.6 Enter the donation amount:45000
Enter weight :76
Donor Kamala Jha gave Rs45000.00.
Record =2
Enter name : kamal
Enter roll number:6 18. Define structure to hold the roll number of a student and marks
Enter sex: male obtained by him in 5 different subjects. Declare an array to hold the
Enter height:5.7 data of 20 students. Pass this to a function that display the marks of
Enter weight : 65
student who has a highest total marks. [T.U. 2066 Jestha]
Record = 3 Ans: #include <stdio.h>
Enter name : Lila #include <conio.h>
Enter roll number: 9 struct student
Enter sex: Female {
Enter height:4.5 int roll;
Enter weight :65 float mark [5];
};
Name Roll no Sex Height Weight void decl(struct student[]);
........................................ void main ( )
Kamal 6 Male 5.7 65 {
Lila 9 Female 4.5 65 int i, j;
Yogesh 4 Male 5.6 76 struct student list [20];
printf("\nEnter the donation amount: ");
17. Write a C program to pass structure as parameter to function scanf("%f", &rec.amount);
Ans: #include<stdio.h> print_rec( rec );
#include<conio.h> getch();
struct data{ }
float amount; void print_rec(struct data x)
char fname[30]; {
char lname[30]; printf("\nDonor %s %s gave
} rec; Rs%.2f.\n", x.fname,
void print_rec(struct data x); x.lname,x.amount);
main()
{
printf("Enter the donor's first and last names,\n");
printf("separated by a space: ");
scanf("%s %s", rec.fname, rec.lname);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
// Entering data
for (i = 0; i < 20; i + +)
{
printf ("Enter Roll number:");
scanf ("%d",&list [i]. roll);
printf ("Enter marks in 5 different
subjects:\n");
for (j = 0; j < 5; j + +)
{
scanf ("%f", &list [i]. mark[j]);
} decl(list);
getch();
}
void decl(struct student list[])
{
float total[20],max;
struct student s; int
i,j; for(i=0;i<20;++i)
{
total[i]=0;
for(j=0;j<5;++j)
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …331 332 … A Complete Refresh Manual of C Programming


total[i]=total[i]+list[i].marks[j];
}
2.14 Pointer
max=total[0];
s=list[0]; 1. What is a pointer? What are the advantages of pointer?
for(i=0;i<20;++i) Ans: Pointer [T.U. 2066 Jestha]
{ A pointer is a variable which stores the address number of
if(total[i]>max) reference number of a cell, instead of storing the actual value of the
{ cell. It is really a very powerful variable which is used to directly deal
max=total[i];
with memory of computer. A pointer is denoted by '*' (indirection
s=list[i];
} operator) and has to be declared in the similar way as we declare other
} variables.
printf(“Marks of student having highest total”); e.g. int a; //A normal variable
for(i=0;i<5;++i) int *p; //A pointer that will point to an integer data
printf(“%f\t”,s.mark[i]); p = &a; //Assign address of 'a' to 'p', pointer 'p' will // Point
} //to the value of variable 'a'.
Advantages of pointers are : [T.U. 2069 Asadh]
(a) It allows us to pass variables, arrays, functions, string and
structures as function arguments.
(b) Pointers are more in handling the data table.
(c) They increase the execution speed.
(d) Pointer reduce the length and complexity of a program.
(e) It supports dynamic memory allocation and de allocation of
memory arguments.
(f) The use of a pointer array to character strings results in saving
of data storage space in memory.
2. What are the uses of pointer? How to declare pointer? Explain.
Ans: Uses of Pointers: [T.U. 2065 Shrawan]
• Pointers are more efficient in handling the data array. They are
used to manipulate arrays more easily by moving pointers to them
instead of moving the arrays themselves.
• Pointers reduce the length and complexity of a program.
• Pointers are used to return more than one values from a function
• Pointers are used to create complex data structures such as linked
lists, trees etc.
• Pointer increases the execution speed.
• Pointers are used to communicate information about memory,
which returns the location of free memory.
Eg. Using function like malloc();
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Declaration of pointer
variables
A pointer should be declared before its use like any other
variable. Data type of the pointer is the data type of the
variable to which it is pointing.
Pointer variable is defined by using an indirection
symbol ‘*’. Using this operator, it becomes possible to point
to the address of other variable. A pointer variable is declared
as follows;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …333 Or, Compare array and pointer with examples. [T.U. 2063 Baishakh]
Or, Compare with and pointer syntactically and physically.
Syntax: Data_type * variable_name; [T.U. 2065 Sheawan]
Eg; int *ptr; Ans: In fact, the compiler translate array notation into pointer notation
Here int indicates that the pointer will point to variables of when compiling. Since the internal architecture of the
integer type. ‘*’ indicates the pointer variable and ptr is the name of microprocessor understands pointers but doesn’t understand arrays.
pointer variable that points to integer variable. To make clear the relationships between pointer and arrays
When pointer is declared, it doesn’t points to anywhere. here is a simple program.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,*p,*q;
printf(“Enter the value of a:”);
scanf(“%d”,&a);
p=&a;
q=&p;
printf(“Value of a=%d\t Address=%d\n”,a,&a);
printf(“Value of a=%d\t Address=%d\n”,*p,p);
printf(“Value of a=%d\t Address=%d\n”,**q,*q);
getch();
}
3. Explain the meaning of each of the following declarations :
(i) int *p;
(ii) int *p [10];
(iii) int (*p) [10];
(iv) int *p [void];
(v) int *p [char *a];
Ans: Meaning of declared pointer statements are :
(a) int *p; = A printer that will point to an integer data.
(b) int *p [10]; = P is 10-element array of pointer to integer
data.
(c) int (*p) [10]; = P is a pointer to a 10-element integer data.
(d) int *p [void]; = P is a function that returns a pointer to an
integer data.
(e) int *p (char*a); = P is a function that accepts an argument
which is a pointer to a character and
returns a pointer to an integer data.
4. What is the relation of array and pointer? Explain.
[T.U. 2067 Ashwin]
Or, How do you relate array and pointer, illustrate with example.
[T.U.2057]
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

334 … A Complete Refresh Manual of C Programming indirection or dereference operator * gives the “contents of an object
pointed to by a pointer”.
/*Print values from array*/ A pointer is declared as follows:
#include<stdio.h> int *ptr;
#include<conio.h> where *ptr is a pointer of int type.
void main() //display the contents of an array using pointer
{
int i,num[5]={42,89,65,74,25};
[T.U. BBA Model Question 2009]
#include<conio.h>
for(i=0;i<5;i++)
printf(“Value=%d\\t”,num[i]);
getch();
}
This is straight forward program. Array notation is used to
access individual elements of the array in the expression num [i]. This
expression can be replaced by *(num+i) as:
#include<stdio.h>
#include<conio.h>
void main()
{
int *p,i,num[5]={42,89,65,74,25};
for(i=0;i<5;i++)
printf(“Value=%d\t”,*(num+i));
getch();
}
Since array elements are always stored in contiguous memory
location a pointer then incremented always points to an immediately
next location of its type.
Here, num[i]=*(num+i);
&num[i]=num+i;
42 89 65 74 25

4001 4003 4005 4007 4009


if each elements of the array is an integer it takes up to two
bytes.Here num points to the address,4001, which contains the value
42. On increasing num it points to the next memory location of its
type. (i.e. address 4003, which contains the value 89, and so on)
5. What is pointer variable? What are the various operators allowed on
a pointer variable? [T.U. 2064 Jrstha]
Or, What is pointer variable? Explain with examples.
Ans: Pointer Variable
A pointer is a variable which contains the address in memory
of another variable. We can have a pointer to any variable type. The
unary or monadic operator & gives the “address of a variable”. The
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …335 336 … A Complete Refresh Manual of C Programming


void main() 7. What is dynamic memory allocation? Explain the functions used
{ for dynamic memory allocation in details with examples.
int *p,sum,i;
static int x[5] = {5,9,6,3,7}; *ptr=25;
i=0; p=x; printf("\n Now k = %d\n",k);
sum=0; getch();
clrscr(); }
printf("\nElement Value Address\n\n"); Output: Value of k is 10
while(i<5) 10 is stored at addr 65524
{ 10 is stored at addr 65524
printf("x[%d]%d %u\n",i,*p,p); Now k=25
sum+=*p;
i++;
*p++;
}
printf("\n Sum = %d\n",sum);
printf("\n &x[0] = %u\n",&x[0]);
printf("\n p = %u\n",p);
getch();
}

6. Differentiate between pointer (*) and address (&) operator using


examples.
Ans: The indirection operator (*) gets the value stored in the memory
location whose address is stored in a pointer variable. The address of
(&) operator returns the address of the memory location in which the
variable is stored. The output of the following example shows the
difference between * and &.
//difference between * and &.
#include<conio.h>
void main()
{
int k;
int *ptr;
clrscr();
k=10;
ptr=&k;
printf("\n Value of k is %d\n\n",k);
printf("%d is stored at addr
%u\n",k,&k);
printf("%d is stored at addr
%u\n",*ptr,ptr);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
[T.U. 2062 Poush] an array of elements, initializes them to zero and then returns a pointer
Or, Describe three dynamic memory allocation functions available in C. to the memory. This function is normally used for requesting memory
[T.U. 2058 Chaitra] space at run time. While malloc allocates a single block of storage
Or, What is dynamic memory allocation? What library functions are
used for this and what type of values do these functions return?
[T.U. 2059 Poush]
Or, What is dynamic memory allocation?What are the various functions
available in C for dynamic memory allocation. [T.U. 2064 Jestha]
Ans: Direct Memory Allocation(DMA) [T.U. 2065 Shrawan]
The mechanism of allocating required amount of memory at
run time is called dynamic allocation of memory. Sometimes it is
required to allocate memory at runtime. When we declare array in any
program, the compiler allocates memory to hold the array. Now
suppose the numbers of items are larger than the defined size then it is
not possible to hold all the elements and if we define an array large
enough and data to be stored is less, in that case the allocated memory
is wasted leading to a need for dynamic memory allocation. In this
mechanism we use a pointer variable to which memory is allocated at
run time.
The various memory allocation functions are described below:
(i) malloc( ) [T.U. 2058 Poush]
It is a memory allocation function that allocates requested size
of bytes and returns a pointer to the first byte of the allocated space.
The malloc function returns a pointer of type void so we can assign it
to any type of pointer. It takes the the following form:
ptr= (cast type *) malloc(byte-size);
where ptr is a pointer of type cast-type. For example, the statement
x=(int *) malloc(10 *sizeof(int)) means that a memory space
equivalent to 10 times the size of an int byte is reserved and the
address of the first byte of memory allocated is assigned to the pointer
x of int type.
The malloc function can also allocate space for complex data
types such as structures. For example:
ptr= (struct student*) malloc(sizeof (struct student)); where ptr is a
pointer of type struct student.
(ii) calloc( ) [T.U. 2058 Poush, T.U. 2065 Shrawan]
It is another memory allocation function that allocates space for
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …337 338 … A Complete Refresh Manual of C Programming


space, calloc allocates multiple block of storage, each of the same Here ptr is a structure pointer not a structure variable and dot
size, and then sets all bytes to zero. It takes the following form: operator requires a structure variable on its left. C provides arrow
ptr= (cast type *) calloc(n,element-size); operator “->” to refer to structure elements. “ptr=stu” would assign the
This statement allocates contiguous space for n blocks, each of address of the zeroth element of stu to ptr. Its members can be
size element-size bytes. accessed by statement like “ptr->name”. When the pointer ptr is
(iii) realloc( ) incremented by one, it is made to point to the next record, that is
It is a memory allocation function that modifies the size of stu[1] and so on.
previously allocated space. Sometime it may happen that the allocated 9. Why are pointers used? Explain. [T.U. 2066 Jestha]
memory space is larger than what is required or it is less than what is Or, Write the importance of “pointer” in C programming.
required. In both cases, we can change the memory size already [T.U. 2068 Baisakh]
allocated with the help of the realloc function known as reallocation of Ans: Pointer are used because of the following reasons:
memory. For example, if the original allocation is done by statement a. It enables us to access a variable that is defined outside the
ptr= malloc(size); function.
then reallocation is done by the statement b. More than one value can be returned from the function
ptr=realloc(ptr,newsize); which will allocate a new memory space of logically by the use of pointer.
size newsize to the pointer variable ptr and returns a pointer to the first c. The use of a pointer array to character strings results in saving
byte of the new memory block of data storage space in memory.
8. Explain pointers and structures by giving an example ofpointer to d. It supports dynamic memory allocation and de allocation of
structure variable? memory arguments.
Ans: We can have a pointer pointing to a structure just the same way a e. They increase execution speed.
pointer pointing to an int, such pointers are known as structure f. Pointer reduce the length and complexity of a program.
pointers. For example consider the following example:
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int roll_no;
};
void main()
{
struct student stu[3],*ptr;
clrscr();
printf("\n Enter data\n");
for(ptr=stu;ptr<stu+3;ptr++)
{ printf("Name");
scanf("%s",ptr->name);
printf("roll_no");
scanf("%d",&ptr->roll_no);
}
printf("\nStudent Data\n\n");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
ptr=stu;
while(ptr<stu+3)
{
printf("%s%5d\n",ptr->name,ptr->roll_no);
ptr++;
}
getch();
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
34
C Programming Language …339 The array elements after storing:
Address=1245024 Value=12
2.15 C Programming – 8 Address=1245028 Value=21
Address=1245032 Value=23
Address=1245036 Value=32
1. Write a program to print values and addresses of 10 elements stored
Address=1245040 Value=34
in an array.
Ans: #include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
int *p,*q,a[10];
p=&a[0];
q=p;

printf("Enter the value of N:");


scanf("%d",&n);
printf("Enter the %d numbers:\n",n);
for(i=0;i<n;i++)
{
scanf("%d",p);
p++;
}
printf("The array elements after
storing:\n");
for(i=0;i<n;i++)
{
printf("Address=%d\tValue=%d\n",q,*q);
q++;
}
getch();
}
Result:
Enter the value of N:5
Enter the 5 numbers:
12
21
23
32
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
temp = *x;
340 … A Complete Refresh Manual of C Programming *x = *y;
2. Write a C program using pointers to compute the sum of all *y = temp;
elements stored in an array. ) }
Ans: #include<stdio.h> Result:
#include<conio.h> Enter two integers :4 5
void main()
{ Now,a=5 b=4
int i,*p,s;
static int a[10]={10,20,30,40,50,60,70,80,90,100};
clrscr();
i=0;
p=a;
s=0;
while(i<10)
{
s=s+ *p;
i++;
p++;
}
printf("sum=%d",s);
getch();
}
Result:
Sum=550

3. Write a program to swap the values of two members using functions.


Or, Using the concept of pointer, swap the values of two integer
variables.
Ans: #include <stdio.h>
#include <conio.h>
void fun (int *, int*);
void main ( )
{
int a, b;
printf ("Enter two integers :");
scanf ("%d%d", &a, &b);
fun (&a, &b);
printf ("Now, a = %d \t b = %d", a, b);
getch ( );
}
void fun (int *x, int *y)
{
int temp;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …341 342 … A Complete Refresh Manual of C Programming


4. Write a program that reads computer marks of N different students Result:
and prints them. [Use malloc( ) function] The message now is Hellow
Ans: #include<stdio.h> The message is now:I saw Ena
#include<conio.h>
#include<stdlib.h> 6. Write a program that reads N integers and prints them in ascending
void main() order using pointer and user defined function.
{
int n,*p,*q; strcpy(msg,"Hellow!");
printf("enter the value of n:"); printf("The message now is %s\n",msg);
scanf("%d",&n); msg=(char*)realloc(msg,30);
p=(int*)malloc(sizeof(int)*n); strcpy(msg,"I saw Ena");
q=p; printf("\n The message is now :%s",msg);
free(msg);
printf("enter the marks\n"); getch();
for(int i=0;i<n;i++) }
{
scanf("%d",p);
p++;
}
printf("the values are:\n");
for(int j=0;j<n;j++)
{
printf("%d\t",*q);
q++;
}
getch();
}
Result:
Enter the value of n:5
Enter the marks
45 54 60 70 75
The values are:
45 54 60 70 75
5. Write a program to illustrate the use of functions free() and
realloc().
Ans: #include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char *msg;
msg=(char *)malloc(30*sizeof(char));
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Ans: #include<stdio.h>
#include<conio.h>
void arr(int *);
int i,j,n;
void main()
{
int *p,*q,a[10];
p=&a[0];
q=p;
printf("Enter the value of N:");
scanf("%d",&n);

printf("Enter the %d numbers:\n",n);


for(i=0;i<n;i++)
{
scanf("%d",p);
p++;
}
arr(q);
printf("The array elements after
sorting:\n");
for(i=0;i<n;i++)
{
printf("%d\t",*q);
q++;
}
getch();
}
void arr(int *b)
{
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(*(b+i)>*(b+j))
{
int temp=*(b+i);
*(b+i)=*(b+j);
*(b+j)=temp;
}
}
}
return;
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …343 344 … A Complete Refresh Manual of C Programming


Result: printf("Enter the no. of student:");
Enter the value of N:5 scanf("%d",&n);
Enter the 5 numbers: p=(struct student *)malloc(sizeof(struct
23 student)*n);
500 q=p;
70 for(i=0;i<n;i++)
8 {
90 total[i]=0;
The array elements after sorting: printf("Enter the record of std[%d]:\n",i+1);
8 23 70 90 500 printf("Enter the roll:");
scanf("%d",&p->roll);
7. Write a C program to reverse a string using pointers.
Ans: #include<stdio.h> fflush(stdin);
#include<conio.h> printf("enter the name:");
void main() gets(p->name);
{
int i,j; printf("enter the marks in 5 subjects:\n");
char *a; for(j=0;j<5;j++)
clrscr(); {
printf("Enter a string:");
scanf("%s",a); i=0; scanf("%f",&p->mark[j]);
while(*(a+i)!='\0') total[i]=total[i]+p->mark[j];
i++; }
for(j=i-1;j>=0;j--)
p++;
printf("%c",*(a+j));
}//end of for i loop clrscr();
getch();
} printf("\nRoll\tName\tSUB1\tSUB2\tSUB3\tSUB4\tS
UB5\tTotal\n");
Result: printf(" \n");
Enter a string:you
for(i=0;i<n;i++)
uoy {
float mark[5];
8. Write a program that reads roll, name and marks in 5 different };
subjects of N different students and prints them in appropriate void main()
format [Use structure, pointer & malloc ( ) function] {
Ans: #include<stdio.h> struct student *q,*p;
int n,i,j;
#include<conio.h>
float total[5];
#include<stdlib.h>
struct student
{
int roll;
char name[25];
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
//to print the roll and name of student
printf("%d\t%s\t",q->roll,q->name);
//to print the marks of 5 subjsects
for(j=0;j<5;j++)
{

if(q->mark[j]<40)
printf("%0.1f*\t",q->mark[j]); else
printf("%.1f\t",q->mark[j]);

}
//to print the marks of particular student
printf("%0.1f\n",total[i]);
q++;
}
getch();
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …345 346 … A Complete Refresh Manual of C Programming


Result: Result:
Enter the no. of student:2 Enter a string :Yogesh
YYYYYY
Enter the record of std[1]: ogesh
Enter the roll:2 gesh
Enter the name:Mohan esh
Enter the marks in 5 subjects: sh
45 65 75 85 95 h

Enter the record of std[2]: 10. Write a program which concates a string to other [use pointer].
Enter the roll:9
Ans: #include<stdio.h>
Enter the name:Pintu
#include<conio.h>
Enter the marks in 5 subjects:
void preconcatenate(char str1[20],char str2[20]);
54 56 76 87 90
void main ( )
{
Roll Name SUB1 SUB2 SUB3 SUB4 SUB5 Total char str1[20], str2[20];
2 Mohan 45 65 75 85 95 365 int i;
9 Pintu 54 56 76 87 90 363 // Entering two strings
printf ("Enter two strings :");
scanf ("%s %s", str1, str2);
9. Write a program that will print out all the rotations of a string typed // Add two strings
into it. For example, the rotations of the word "empty" are : empty preconcatenate(str2,str1);
mptysptysm tysmp ysmpt [use pointer] printf (" \n \n After adding str2 to
Ans: #include<stdio.h> other");
#include<conio.h> printf (" \n The new string : %s", str2);
getch ( );
#include<string.h>
}
void main ( )
if (*s = = '\o')
{
s = str;
char str [20];
}
int i, j, n;
printf ("\n");
char *s;
}
printf ("Enter a string :");
printf ("\n \n");
scanf ("%s", str);
getch ( ):
n = strlen (str);
}
for (i = 0; i < n; i + +)
{
s = &str [i];
for(j = 1; j < = strlen (str); j + +)
{
printf ("%c", *s);
s++;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
void preconcatenate(char *i, char *s)
{
while (*i)
i ++;
while (*s)
*i ++ = *s ++;
* i ='\o' ;
}
Result:
Enter two strings:You
Me

After adding str2 to other


The new string :MeYou

11. Write a program to delete all vowel from a sentence. [Use


pointer]
Ans: #include <stdio.h>
#include <conio.h>
void main ( )
{
char str [80], str1 [80];
char *s, *p;
printf ("Enter a sentence:");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …347 348 … A Complete Refresh Manual of C Programming


gets (str); Result:
s = str; // Base address of string Enter three numbers: 4 5 6
p = str1; // Base address of new string The highest number is 6.
while (*s)
{
if (*s = = 'a' || *s = = 'e' || *s = = 'i' ||*s = = 13. Write a computer program that allocates memory space for n integer
'o' || *s = = 'u') numbers. Write a function to read n numbers, store them in the
s++; reversed memory space and find and return the average of them. In
else main program display all the numbers and average.
if (*s = = 'A'|| *s = = 'E' ||*s = = 'I' || *s [T.U. 2061 Poush]
= = 'O' || *s = = 'U')
Ans: #include<stdio.h>
s++;
#include<conio.h>
else #include<stdlib.h>
*p++ = *s++; int average(int *,int );
} void main()
*p = '\o'; {
printf (" \n Sentence removing after all
int *ptr,l,i;
vowels\n"); float s;
puts (str1);
printf("How many elements?:");
getch ( ); scanf("%d",&l);
}
Result: ptr=(int*)malloc(l*sizeof(int));
Enter a sentence:We are student. for(i=l-1;i>0;--i)
{
Sentence removing after all vowels printf("Enter the elemets\t%d:",i);
W r stdnt. scanf("%d",ptr+i);
12. Write a program to find the highest of three numbers using pointer } s=average(ptr,l);
to function. printf(“Number are\n”):
for(i=0;i<l;++i)
Ans: #include<stdio.h>
printf("\n%d",*(ptr+i));
#include<conio.h>
printf(“\n Average=%f”,s);
void highest(int*,int*,int*);
getch();
void main()
}
{
int sumofarray(int *p,int l)
int x,y,z;
{
clrscr();
int i,sum=0;
printf("\n Enter three numbers : ");
float avg;
scanf("%d %d %d",&x,&y,&z);
for(i=0;i<l;++i)
printf("\n\n The highest of the three
sum=*(p+i)+sum;
numbers is : ");
avg=(float)sum/l;
highest(&x,&y,&z);
return avg;
getch();
}
void highest(int *a,int *b,int *c) {
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
if(*a > *b && *a > *c) }
printf("%d",*a); Result:
else if(*b > *a && *b > *c) How many elements?5
printf("%d",*b); Enter the elements:1
else 2
printf("%d",*c); 3
} 4
5
Average=
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
if(i>j)
C Programming Language …349 return (1);
}
14. Write a function that accepts two strings str1 and str2 as arguments Result:
and finds which of the two is alphabetically greater (without using Enter 1st string:ram
the library functions). The function should return 1 if str1 is greater Enter 2nd string:hari
than str2, 0 if str1 is equal to str2, and -1 is str1 is smaller than str2.

Ans: #include<stdio.h>
#include<conio.h>
int comp(char a[10],char b[10]);
void main()
{
char a[10],b[10];
int k;
clrscr();
printf("Enter 1st string:");
gets(a);
printf("Enter 2nd string:");
gets(b);
k=comp(a,b);
if(k==1)
printf("%s is greater than %s",a,b);
if(k==-1)
printf("%s is less than %s",a,b);
if(k==0)
printf("%s is equal to %s",a,b);
getch();
}
int comp(char *a,char *b)
{
int i=0,j=0,k;
while(a[i]!='\0'&& b[j]!='\0’)
{ if (a[i]<b[j])
return (-1);
else if(a[i]>b[j])
return (1);
else
i++;
j++;
}
if(i==j)
return (0);
if (i<j)
return (-1);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
int is_palindrome(char *string)
350 … A Complete Refresh Manual of C Programming {
15. Write a program to enter a string and check whether the entered int check, length;
string is palindrome or not using library function. char *reverse;
length = string_length(string);
[Palindrome : A string is said to be palindrome if it remains same if
reverse = (char*)malloc(length+1);
we reverse it. e.g. ADA, MALAYALAM] copy_string(reverse, string);
Ans: #include <stdio.h> reverse_string(reverse);
int is_palindrome(char*); check = compare_string(string, reverse);
void copy_string(char*, char*); free(reverse);
void reverse_string(char*); if ( check == 0 )
int string_length(char*); return 1;
int compare_string(char*, char*); else
main() return 0;
{ }
char string[100]; int string_length(char *string)
int result; {
printf("Enter a string\n"); int length = 0;
gets(string); while(*string)
result = is_palindrome(string); {
if ( result == 1 ) length++;
printf("\"%s\" is a palindrome string.\n", string); string++;
else }
printf("\"%s\" is not a palindrome string.\n", return length;
string); }
return 0;
}
void copy_string(char *target, char *source)
Ram is greater than hari {
while(*source)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …351 352 … A Complete Refresh Manual of C Programming


{ printf("\nEnter the value of N:");
*target = *source; scanf("%d",&n);
source++; printf("Enter the %d numbers:\n",n);
target++; for(i=0;i<n;i++)
} {
*target = '\0'; scanf("%d",p);
} p++;
void reverse_string(char *string) }
{ arr(q);
int length, c; printf("The array elements after sorting:\n");
char *begin, *end, temp; for(i=0;i<n;i++)
length = string_length(string); {
begin = string; printf("%d\t",*q);
end = string; q++;
for ( c = 0 ; c < ( length - 1 ) ; c++ ) }
end++; getch();
for ( c = 0 ; c < length/2 ; c++ ) }
{ void arr(int *b)
temp = *end; {
*end = *begin; for(i=0;i<n;i++)
*begin = temp; {
begin++; for(j=i+1;j<n;j++)
end--; {
} if(*(b+i)>*(b+j))
} {
int temp=*(b+i);
int compare_string(char *first, char *second) *(b+i)=*(b+j);
{ *(b+j)=temp;
while(*first==*second) }
{ }
if ( *first == '\0' || *second == '\0' ) }
break; return;
first++; }
second++; Result:
} Enter the value of N:5
if( *first == '\0' && *second == '\0' ) Enter the 5 numbers:
return 0; 23
else 500
return -1; 70
} 8
90
16. Write a program that reads N integers and prints them in ascending The array elements after sorting:
order using pointer and user defined function. 8 23 70 90 500
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Ans: #include<stdio.h>
#include<conio.h> 17. Write a program that reads roll, name and marks in 5 different
void arr(int *); subjects of N different students and prints them in appropriate
int i,j,n; format [Use structure, pointer & malloc ( ) function]
void main() Ans: #include<stdio.h>
{ #include<conio.h>
int *p,*q,a[10]; #include<stdlib.h>
p=&a[0]; struct student
q=p; {
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …353 354 … A Complete Refresh Manual of C Programming


int roll; }
char name[25]; //to print the marks of particular student
float mark[5]; printf("%0.1f\n",total[i]);
}; q++;
void main() }
{ getch();
struct student *q,*p; }
int n,i,j; Result:
float total[5];
//to print the marks of 5 subjsects
printf("\nEnter the no. of student:"); for(j=0;j<5;j++)
scanf("%d",&n); {
p=(struct student *)malloc(sizeof(struct if(q->mark[j]<40)
student)*n); printf("%0.1f*\t",q->mark[j]); else
q=p; printf("%.1f\t",q->mark[j]);

for(i=0;i<n;i++)
{ total[i]=0;
printf("Enter the record of std[%d]:\n",i+1);
printf("\nEnter the roll:");
scanf("%d",&p->roll);

fflush(stdin);
printf("Enter the name:");
gets(p->name);

printf("Enter the marks in 5 subjects:\n");


for(j=0;j<5;j++)
{
scanf("%f",&p->mark[j]);
total[i]=total[i]+p->mark[j];
}
p++;
}
//end of for i loop

clrscr();
printf("\nRoll\tName\tSUB1\tSUB2\tSUB3\tSUB4\tSUB5\
tTotal\n");
printf(" \n");
for(i=0;i<n;i++)
{
//to print the roll and name of student
printf("%d\t%s\t",q->roll,q->name);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Enter the no. of student:2 other=%d”,o); getch();
Enter the record of }
std[1]: Enter the void count(char str[],int *v,int *c,int *n,int *o)
roll:2 {
Enter the name:Mohan Int I;
Enter the marks in 5 subjects: For(i=0;str[i]!=0;++i)
45 65 75 85 95 {
Enter the record of
std[2]: Enter the
roll:9
Enter the name:Pintu
Enter the marks in 5 subjects:
54 56 76 87 90

Roll Name SUB1 SUB2 SUB3 SUB4 SUB5


Total
2 Mohan 45 65 75 85 95
365
9 Pintu 54 56 76 87 90
363
18. Write a function that takes a string as the input and
count the number of vowels, consonants, numberic character
and other character. The calling function should read the
string and pass it to the function. After the function call,
the count of vowels, consonants, numeric character and
other character should be displayed in the calling function.
[T.U. 2061 poush]
Ans:
#include<stdio.h>
#include<conio.h>
void count(char [],int *,int *,int *,int *);
void main()
{
char str[80];
int v=0,c=0,n=0,o=0;
Printf(“Enter a
string:”); gets(str);
count(str,&v,&c,&n
,&o);
Printf(“\nTotal number of
vowel=%d”,v); Printf(“\nTotal number
of consonant=%d”,c); Printf(“\nTotal
number of number=%d”,n);
Printf(“\nTotal number of
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
{
C Programming Language …355 if(*(p+i)%2!=0)
if(toupper(sen[i])=='A' ||toupper(sen[i]) =='E' || {
toupper(sen[i])=='I' || toupper(sen[i]) a[c]=*(p+i);
=='O' || toupper(sen[i])=='U') c++;
*v= *v + 1; }
else }
return c;
if(toupper((sen[i])>=' A'||toupper(sen[i])<='Z')
}
*c=*c+1;
else if(str[i]>=’0’ && str[i]<=’9’)
*n=*n+1;
else
*o=*o+1;
}
}
19. Write a program that reads positive integers into an array
dynamically and pass them to a function where odd numbers are
filtered into another array and display the array containing odd
numbers in the main program. [T.U. 2065 Shrawan]
Ans: #include<stdio.h>
#include<conio.h>
void odd(int *,int[],int);
void main()
{
int *p,n,i,o;
printf(“Enter value of n:”):
scanf(“%d”,&n);

p=(int *)malloc(n*sizeof(int));
printf(“Enter element:”):
for(i=0;i<n;++i)
scanf(“%d”,(p+i));
o=odd(p,o,n);
printf(“Odd numbers are:”):
for(i=0;i<o;++i)
printf(“\n%d”,o[i]);
getch();
}
int odd( int *p,int a[],int n)
{
int I,c=0;
{
for(i=0;i<n;++i)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
for(i=0;*(s1+i)!=’\0’;++i)
356 … A Complete Refresh Manual of C Programming
{
20. Write a program that dynamically allocates two different strings and if(*(s2+i)!=*(s1+i-1-k)
pass them to function where the second string is compared with the return 1;
reverse of the first string on the character basis and display the }
message in main function. You are not allowed to use the string return 0;
functions. [T.U. 2065 Shrawan] }
Ans: #include<stdio.h>
#include<conio.h>
int compare(char*,char *);
void main()
{
char *s1,*s2;
int l,n;
printf(“Enter maxmimum length of string:”);
scanf(“$d”,&l);
s1=(char*) malloc(l*sizeof(char));
s2=(char*) malloc(l*sizeof(char));
printf(“First string:”):
gets(s1);
printf(“Enter second string:”):
gets(s2);
n=compare(s1,s2);
if(n==0)
printf(“\n Second string and reverse of
first string is same”):
else
printf(“\nSecond string and reverse of
first string is not same”);
getch();
}
int compare(char *s1,char *s2)
{
int i,j,k;
for(i=0;*(s1+i)!=’\0’;++i)
for(j=0;*(s1+j)!=’\0’;++j)
if(i==j)
return 1;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …357 Language places no constructs on the file, and it may be read from, or
written to, in any manner chosen by the programmer.\
2.16 Data File
It organizes data into blocks containing contiguous bytes of
1. What is data file ? Explain its type. Also, Write down its operation information.It contsists sound,images,graphical files etc.A binary file
mode. is made up of machine-readable symbols that represent 1’s and 0’s.
B. Low Level
Or, What is a file? What is the difference between a text file and binary
file? Explain with an example. [T.U. 2064 Jestha]
Or, Differentiate between text versus binary mode of file.
[T.U. 2065 Shrawan]
Ans: It is a data structure which help us to store our data permanently on
the secondary storage media (i.e. hard disk, floppy disks etc.) and to
access and alter information whenever necessary.C programming has
different types of library functions for creating and managing data
files.Types of data files are:
A. High Level
Types of high level files are:
a. Text files
A text file can be a stream of characters that a computer can
process sequentially. It is not only processed sequentially but only in
forward direction. For this reason a text file is usually opened for only
one kind of operation (reading, writing, or appending) at any given
time.
A text file file is a human-readable sequence of characters and
words they form that can be encoded into computer-readable formats
such as ASCII.A text file is also known as ASCII file and can be read
by any word processing package.There is no sound or video files or
graphical files.
b. Binary files
A binary file is no different to a text file. It is a collection of
bytes. In C Programming Language a byte and a character are
equivalent. No special processing of the data occurs and each byte of
data is transferred to or from the disk unprocessed. C Programming
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

358 … A Complete Refresh Manual of C Programming file pointer.


D. Formatted input/output
2. Write down syntax of character input/output, string input/output,
a. fscanf()
word input/output and formatted input/output. Also write the syntax
of block read and write. It is used to read a formatted data from a specified file.The
Or, What are the inputs and outputs functions used with data files? general format of fscanf () is fscanf(ptr,”control string”,&list);
[T.U. 2068 Baisakh] where ptr is file pointer,control is different format like %d,%f etc and
list is variable parameter list to be read from specified file.
Ans: Input and output functions are:
A. Character input/output
a. getc()
It is used to read a single character from a file and returns the
value of EOF.
The statement is ch=getc(fp);
b. putc()
It is used to write a single character into a file.The function
normally returns the character written but will return value of EOF if
error is encountered.
The statement is putc(ch,fp);
B. String input/output
a. fgets()
It is used to read a set of characters as a string from a given
file and copies the string to a given memory location normally in
array.The general format of fgets() is fgets(sptr,n,ptr);
Where sptr=pointer to the location to receive string n=count
maximum number of character to be in the string ptr=pointer to the
file to be read
b. fputs
It is used to write a string to a given file.The general format
of fputs() is fputs(sptr,ptr); where sptr=pointer to the string to be
written ptr=file pointer to file
C. Word input/output
a .getw()
It is used to read an integer value from a given file.The
format of getw() is getw(fp);
b. putw()
It is used to write an integer quantity on the specified file. The
syntax of putw() is putw(w,fp); where w is an integer value and fp is
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …359 360 … A Complete Refresh Manual of C Programming


b. fprintf() 5. Write the steps for writing a file.
It is used to write a formatted data into a given file.The general Ans: Steps for writing a file
format of fprintf() is fprintf(ptr,”control string”,list); where ptr is file (a) Create a FILE pointer
pointer,control string is a formatted command and list is variable list (b) Open file in write (w or a) mode
to be written on the file. (c) Perform general I/O operations
(d) Save I/O results using following syntax :
Block read and write(Binary files)
fprintf (file_pointer, "format specifier lists", variable lists);
a. fwrite() (e) close the file using fclose (file_pointer)
It is used to write a binary data to a given file.The general Example :
format is fwrite(ptr,size,nitems,fptr); where ptr=pointer that is first {
structure to be written. size=size in bytes of each structure int age;
nitems=number of structure to be written fptr=file pointer to the file char name[20];
FILE *fp;
b. fread() fp = fopen ("info.dat", "w");
It is used to read a block of binary data from a given file. printf ("Enter name:");
fread(ptr,size,nitems,fptr); gets (name);
printf ("Enter age:");
3. Explain the following file functions. scanf ("%d", &age);
(i) ftell (ii) rewind( ) (iii) fseek fprintf (fp,"%s %d", name, age);
Ans: (i) ftell( ): gives the current position in the file from the start. ftell fclose (fp);
takes a file pointer and returns a number of type long, that return o;
corresponds to the current position. }
For example:n=ftell(p); would give the relative offset n in 6. Write the steps for reading a file.
bytes of the current position. This means that n bytes have Ans: Steps for reading a file
already been read (or written). (a) create FILE pointer
(b) opened file in read mode (r mode)
(ii) rewind( ): sets the position to the beginning of the file. It also
(c) Read the data from file using following syntax :
takes a file pointer and reset the position to the start of the file. fscanf (file_pointer, "format specifier list", variable lists);
For example: (d) Display data as required
rewind(fp); e.g.
n=ftell(fp); would assign 0 to n because file pointer has been {
set to the start of the file by rewind. int age;
char name[20];
(iii) fseek( ): sets the position to a desired point in the file. fseek FILE *fp;
function is used to move the file position to a desired location fp = fopen ("info.dat", "r");
within the file. fscanf (fp, "%s %d", name, &age);
For example: fseek(fp,m,0); would move the file pointer to printf ("Your name : %s", name);
(m+1)th byte in the file. printf ("Your age : %d", age);
fclose (fp);
4. Explain different modes of file operation. [T.U. 2058 Poush] return o;
Ans: The different types opf file operaton are: }
(i) r : open file for reading or display
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
(ii) w : open file for writing
(iii) a : open file for appending
List of additional file modes are :
(i) r + : Existing file is opened to the beginning for both
reading and writing.
(ii) w+ : Same as w except both for reading and writing.
(iii) a+ : Same as a except both for reading & writing.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …361 362 … A Complete Refresh Manual of C Programming


while(ch!=EOF)
2.17 C Programming – 9 {
ch=getc(f1);
1. Write a program to read data from the keyboard, write it to a file printf("%c",ch);
called INFO, again read the same data from INFO file, and display }
it on the screen. fclose(f1);
Ans: #include <stdio.h> getch();
#include <conio.h> }
void main ( ) Result:
{ Enter your text here:Hellow.
FILE *fp;
char ch; Data output
printf (“\n\n Data input \n \n \n"); Hellow
fp = fopen ("INFO.TXT","w");
while (ch = getchar ( )! = EOF)
putc (ch, fp); 3. Write a program to store std_no, name and marks of ‘n’ students in
fclose (fp); a data file. Display the records in appropriate format reading from
file.
// Data output Ans: #include<stdio.h>
fp = fopen (“INFO.TXT", "r"); #include<conio.h>
while (ch = getc (fp) ! = EOF) #define MAX 500
printf ("%c", ch); void main()
fclose (fp); {
getch ( ): FILE *fp;
} int std_no[MAX],marks[MAX];
char name[MAX][20];
Result: int i,n;
Data input
We are learning C programming.^Z printf("How many data?");
scanf("%d",&n);
Data output
We are learning C programming. fp=fopen("record.dat","w+");
for(i=0;i<n;++i)
2. Write a program to create a data file, inserts the characters into the while(ch!='.')
file and prints the contents of file. [Use getc( ) and putc( ) functions]
Ans: #include<stdio.h>
#include<conio.h>
void main()
{
FILE *f1; char ch;
printf("Enter your text here:\n");
f1=fopen("input.txt","w");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
{ printf("Enter marks:");
printf("Enter roll number:"); scanf("%d",&marks[i]);
scanf("%d",&std_no[i]); fprintf(fp,"%d%s%d",std_no[i],name[i],
fflush(stdin); marks[i]);
printf("Enter name"); }
scanf("%s",name[i]);
{ rewind(fp);
ch=getchar(); printf("Roll number\tName\tMarks\n");
putc(ch,f1); printf("--------------------------\n");
}
fclose(f1); for(i=0;i<n;++i)
{
printf("\nData output\n"); fscanf(fp,"%d%s%d",&std_no[i],name[i],&marks[i]);
f1=fopen("input.txt","r"); printf("%d\t%s\t%d\n",std_no[i],name[i],
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …363 364 … A Complete Refresh Manual of C Programming


marks[i]); while((ch=getc(f1))!=EOF)
} printf("%c",ch);
fclose(fp); printf("\n");
getch(); fclose(f1);
}
Result: printf("ENTER UPPERCASE SENTENCE\n");
How many data?3 f2=fopen("lower.txt","w");
do
Enter roll number:2 {
Enter name:Maullik ch=getchar();
Enter marks:400 /*writing the lowercase character in
file*/
Enter roll number:20 putc(tolower(ch),f2);
Enter name:Mausami } while(ch!='\n');
Enter marks:410 fclose(f2);
Enter roll number:21 f2=fopen("lower.txt","r");
Enter name:Niras printf("\nData output\n");
Enter marks:415 while((ch=getc(f2))!=EOF)
printf("%c",ch);
Roll number Name Total Marks fclose(f2);
2 Maullik 400 getch();
20 Mausami 410 }
21 Niras 415 Result:
Enter lowercase sentence:
4. Develop a program that accepts a sentence for a data file. The hellow
program also reads the data from that file and changes it into
uppercase and lowercase text for uppercase file and lowercase file Data output
respectively. Finally, the program prints all the contents of different HELLOW
files. [Use getc( ) and putc( ) functions]
ENTER UPPERCASE SENTENCE
Ans: #include<stdio.h> HELLOW
#include<conio.h>
#include<string.h> Data output
#include<ctype.h> hellow
void main()
{
FILE *f1,*f2; /*writing the uppercase character in
char ch; file*/
printf("enter lowercase sentence:\n"); putc(toupper(ch),f1);
f1=fopen("upper.txt","w"); }while(ch!='\n');
do fclose(f1);
{
ch=getchar(); printf("\nData output\n");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
f1=fopen("upper.txt","r");
5. Write a program that reads 'n' integers for a file and reads every
integer from file to store in odd file (if odd) and even file (if even)
and finally prints all the file in console.
Ans: #include <stdio.h>
#include <conio.h>
void main ( )
{
FILE *fp, *fpo, *fpe;
int n, num, i;
fp = fopen ("MAIN.DAT","w");
printf ("How many numbers ?");
scanf ("%d", &n);

// Entering nos
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …365 366 … A Complete Refresh Manual of C Programming


printf ("Enter %d numbers, n); 6. Write a computer program to copy the contents of one text file to
for (i = 0, i < n; i++) another. The name of both files must be input by the user. Display
{
scanf ("%d", &num); appropriate message if source file does not exist.
putw (num, fp); [T.U. 2057, 2058 Poush]
} Ans: #include<stdio.h>
fclose (fp); #include<process.h>
#include<conio.h>
fp = fopen("MAIN.DAT","r"); void main()
fpo = fopen("odd.dat","w"); {
fpe = fopen("even.dat","w"); FILE *f1,*f2;
for (i = 0; i < n; i++)
char name1[15],name2[15],ch;
{
num =getw(fp);
if (num% 2 = = 0) printf("Enter source file name:");
putw (num, fpe); gets(name1);
else printf("Enter destination file name:");
putw (num, fpo); gets(name2);
} Content from MAIN.DAT
fclose (fp); 12 15 18 20 40 content from
fclose (fpo);
fclose (fpe); odd.dat
printf ("\nContent from MAIN.DAT\n");
fp=fopen("MAIN.DAT","r"); 15
while ((num = getw (fp))! = EOF) Content from even.dat
printf ("%d \t", num); 12 18 20 40
fclose (fp);
printf ("\ncontent from odd.dat\n");
fpo = fopen ("odd.dat", "r");
while ((num = getw (fpo))! = EOF)
printf ("%d \t", num);
fclose (fpo);
printf ("\nContent from even.dat\n");
fpe = fopen ("even.dat", "r");
while ((num = getw (fpe))! = EOF)
printf ("%d \t", num);
fclose (fpe);
getch ( );
}
Result:
How many numbers?5
Enter 5 numbers
12 15 18 20 40
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
EOF) break;
f1=fopen(name1,"r"); else
if(f1==NULL) fputc(ch,f2);
{ }
puts("Source file does not printf(“Files copied.”);
exist"); fclose(f1);
exit(0); fclose(f2);
} getch();
f2=fo }
pen(n
ame2, Result:
"w"); Enter source file name: main.dat
if(f2 Enter destination file name:record.dat
==NUL
L) Files copied.
{
puts("Does not open target file");
exit(0);
}
while(1)
{

c
h
=
f
g
e
t
c
(
f
1
)
;

i
f
(
c
h
=
=
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …367 368 … A Complete Refresh Manual of C Programming


7. Write a program to read name and roll number of 24 students from 8. Write a program to create a data file named “info1.dat” and write
the user and store them in a file. If the file already contains data, the even numbers from 2 to 100. Display all the numbers after
your program should add new data at the end of file. reading the numbers.
[T.U. 2059] Ans: #include<stdio.h>
Ans: #include<stdio.h> #include<conio.h>
#include<conio.h> #include<process.h>
void main()
void main()
{
{ int i,num;
char name[20],ch; FILE *f1;
int rollno,i;
f1=fopen(“info1.dat”,”w+”);
FILE *f1; if(f1==NULL)
f1=fopen(“record.dat”,”a”); {
for(i=0;i<24;++i) printf(“File does not exist”);
{ exit(0);
fflush(stdin); }
for(i=2;i<100;i+=2)
printf(“Enter students name:”);
{
gets(name); fprintf(f1,”%d\t”,i);
printf(“Enter rollno:”); } rewind(f1);
scanf(“%d”,&rollno); for(i=2;i<=100;i+=2)
fprintf(f1,”%s%d”,name,rollno); {
} fscanf(f1,”%d”,&num);
fclose(f1); printf(“%d\t”,num);
}
f1=fopen(“record.dat”,”r”);
while(1) fclose(f1);
getch();
{
}
ch=fgetc(f1);
if(ch==EOF)
break;
Result:
2 4 6 8 10 12 14 16
else 18 20 22 24 26 28 30 32
putchar(ch); 34 36 38 40 42 44 46 48
50 52 54 56 58 60 62 64
} 66 68 70 72 74 76 78 80
fclose(f1); Enter rollno:2
getch(); ……………………………………
} ……………………………………
Enter students name:hari
Enter rollno:3
Result:
Enter students name:ram
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Ram:2………hari:3 82 84 86 86 90 92 94 96
98

9. Write a program to open a file named “inventory.dat” and store in it


the following data
Particulars Quantity Rate
DVD 20 100
DDR2 180 1800
Woofer 67 1500
Ans: #include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
{
C Programming Language …369 char ch;
char str[3][15]={"DVD","DDR2","Woofer"}; int c=0;
int qty[3]={20,180,67},i;
int rate[3]={100,1800,1500}; FILE *f1;
float total[3]; f1=fopen(“record1.dat”,”w”);
printf(“Enter a string:”);
FILE *f1; while(1)
f1=fopen("f:\\inventory.dat","w"); {

for(i=0;i<3;++i)
{
fscanf(f1,"%s%d%d",str[i],qty[i],rate[i]);
total[i]=qty[i]*rate[i];
fprintf(f1,"%s%d%d%f",str[i],qty[i],
rate[i],total[i]);
}
fclose(f1);
//Data output

f1=fopen("f:\\inventory.dat","r");
printf("Particulars\t\tQty\t\tRate
\t\tTotal\n");
for(i=0;i<3;++i)
{
fscanf(f1,"%s%d%d%f",str[i],qty[i],rate[i]
,total[i]);
printf("%s\t\t%d\t\t%d\t\t%.2f\n",str[i]
,qty[i],rate[i],total[i]);
}
fclose(f1);
getch();
}

Result:
DVD 20 100 2000.000000
DDR2 180 1800 324000.000000
Woofer 67 1500 100500.000000

10. Write a program that reads characters from keyboard and writes to a
data file. The program should display the numbers of words entered
and terminate when the user enters a dot. [T.U.2059]
Ans: #include<stdio.h>
#include<conio.h>
void main()
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
scanf(“%d”,&a.roll);
370 … A Complete Refresh Manual of C Programming fflush(stdin);
ch=getche(); printf("\nEnter name:");
if(ch==’.’) gets(a.name);
break; fflush(stdin);
else printf("\nEnter address:");
{ gets(a.add);
fputc(ch,f1); printf("Enter telephone number:");
if(ch==’ ‘) scanf("%ld",&a.tel);
++c;
}
}
printf(“Total number of words in the entered string
is %d”,c);
getch();
}

Result:

11. Write a program to open a new file.Read roll number, name,


address and telephone number of students until the user says “no”
after reading the data, write it to the file then display the content of
file.
[T.U. 2061 Poush, 2063 Baisakh]
Ans: #include<stdio.h>
#include<conio.h>
#include<string.h>
struct student
{
char name[30],add[20];
int roll;
long int tel;
}a;
void main()
{
char ch[10];

FILE *fp;
fp=fopen("record2.dat","wb");
do
{
printf(“\nEnter roll number:”)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …371 372 … A Complete Refresh Manual of C Programming


fwrite(&a,sizeof(a),1,fp); {
printf("Do you want to add another int n,i;
record?");
scanf("%s",ch); FILE *fp;
}while(strcmp("no",ch)); fp=fopen("record2.dat","wb");
fclose(fp); if(fp==NULL)
{
fp=fopen("record2.dat","rb"); printf(“\n File can not opened”);
printf("Roll No.\tName\tAddress getch();
\tTelephone Number\n"); exit(0);
while(fread(&a,sizeof(a),1,fp)==1) }
{ printf(“Enter number of students:”);
printf("%d\t%s\t%s\t%ld\n",a.roll,a.name, scanf(“%d”,&n);
a.add,a.tel);
} for(i=0;i<n;++i)
fclose(fp); {
getch(); fflush(stdin);
} printf("\nEnter name:");
gets(a.name);
Result: fflush(stdin);
Enter roll number:2 printf("\nEnter address:");
Enter name:Raman gets(a.add);
Enter address:Patan printf("Enter telephone number:");
Enter telephone number:54343 scanf("%ld",&a.tel);
Do you want to add another record?y fwrite(&a,sizeof(a),1,fp);
}
Enter roll number:20 fclose(fp);
Enter name:Raju
Enter address:Naxal fp=fopen("record2.dat","rb");
Enter telephone number:44343 if(fp==NULL)
Do you want to add another record?no {
printf(“\n File can not opened”);
Roll No. Name Address Telephonenumber getch();
2 Raman Patan 54343 exit(0);
20 Raju Naxal 44343 }

Ans: #include<stdio.h>
12. Write a program to open a binary file. Define a structure variable #include<conio.h>
struct student
that hold the name,address and telephone number of a student. Ask {
the user for the number of each student records that has to be filed. char name[30],add[20];
Read in a structure for each student and write the structure to the long int tel;
file. After having read all records, read in the content of the file and
display them. [T.U. 2064 Baisakh]
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
printf("Name\tAddress\tTel. Number\n"); }
while(fread(&a,sizeof(a),1,fp)==1)
{ 13. Write a program to open anew file. Read
printf("%s\t%s\t%ld\n",a.name, produc_code,product_name and price for 10 items and write them to
a.add,a.tel); the file. [T.U. 2060 Shrawan]
}
fclose(fp);
Ans: #include<stdio.h>
getch();
}a;
void main() #include<conio.h>
void main ( )
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
Enter name : C++ programming
C Programming Language …373 Enter price:350
{
char product_name[10][30]; Product Code Product Name Price
101 C programming
int product_code[10]; 300
………………..float price[10];
……………………….. ……………

int i;

FILE *fp;
fp = fopen("STUD.DAT", "wb");
for(i = 0;i<10; i++)
{
printf("\nEnter product code:");
scanf("%d",&product_code[i]);
printf ("\nEnter name : ");
scanf ("%s",&product_name[i]);
printf(“\nEnter price:”);
scanf ("%f",&price [i]);
fprintf(fp,"%d%s%f",product_code[i],
product_name[i],price[i]);
}
rewind(fp);
// Reading from file
printf("\nProduct Code\tProduct Name\t
Price\n");
for (i = 0; i<10; i++)
{
fscanf(fp,"%d%s%f",&product_code[i],
product_name[i],&price[i]);
printf("%d\t%s\t%f\n",product_code[i],
product_name[i],price[i]);
}
fclose (fp);
getch ( );
}
Result:
Enter product code:101
Enter name : C programming
Enter price:300
………………………………………….
……………………………………………..
…………………………………………..
Enter product code:121
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
exit(1);
374 … A Complete Refresh Manual of C Programming }
14. Write a program to open anew file, read name, roll for(i=0;i<50;++i)
number, and total score of 50 students from user and {
write to the file. After writing, display the contents of file.
do
[T.U. 2062 Poush] {
Ans: printf("\nEnter roll number:");
#include<stdio.h> scanf("%d",&a.roll);
#include<conio.h> fflush(stdin);
struct student printf("\nEnter name:");
{ gets(a.name);
char name[30]; for(i=0;i<5;++i)
int roll; {
float marks; printf("Enter marks:");
}a[50]; scanf("%d",&a.marks[i]);
void main ( ) }
{ fwrite(&a,sizeof(a),1,fp);
int
i;
15. Write a program that first appends the customer records in a binary
FILE file and display the number of customer records as well as the
*fp; contents from the file. The file name should be given by user and
display message if it does not exit. [T.U. 2065 Shrawan]
fp=fopen("score.dat","wb"); Ans: #include<stdio.h>
if(==NULL) #include<conio.h>
{ struct customer
printf(“File can not be opened:”): {
getch();
Char name[30];
121 C++ programming 350 void main ( )
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
printf("%d\n",a.marks[i]);
C Programming Language …375 }
16. Write a program to read name,rollno, and marks obtained by }
students in five subjects and store the result in a file until user is not fclose(fp);
satisfied. The program should have another portion to read all the getch();
}
stored information. Your program should ask the user to read from
or write to the file and call the specific functions.
[T.U. 2062 Baisakh]
Ans: #include<stdio.h>
#include<conio.h>
struct student
{
char name[30];
int roll;
int marks[5];
}a;
void main ( )
{
char ch[10];
int i; FILE *fp;
fp=fopen("record4.dat","wb");
do
{
printf("\nEnter roll number:");
scanf("%d",&a.roll);
fflush(stdin);
printf("\nEnter name:");
gets(a.name);
for(i=0;i<5;++i)
{
printf("Enter marks:");
scanf("%d",&a.marks[i]);
}
fwrite(&a,sizeof(a),1,fp);
printf("Do you want to add another record?");
scanf("%s",&ch);
}while(ch=='y'); fclose(fp);
fp=fopen("record4.dat","rb");
printf("Roll No.\tName\tAddress\tTelephone
Number\n");
while(fread(&a,sizeof(a),1,fp)==1)
{
printf("%d\t%s\t",a.roll,a.name);
for(i=0;i<5;++i)
{
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
{
376 … A Complete Refresh Manual of C Programming if(list[i].rank>list[j].rank)
Result: {
rtemp=list[i].rank;
strcpy(ntemp,list[i].name);
strcpy(ctemp,list[i].country);
list[i].rank=list[j].rank;
strcpy(list[i].name,list[j].name);
17. Write a program that reads name, rank and country of N different
players for a data file and prints all the information in descending
order on the basis of rank.
Ans: #include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 500
struct player
{
int rank;
char name[15],country[15];
}list[MAX];
void main()
{
FILE *fp;
int i,j,rtemp;
char ntemp[15],ctemp[15];
int n;
printf(“How many records?”);
scanf(“%d”,&n);

printf("ADD RECORDS\n\n");
fp=fopen("data.txt","w");
for(i=0;i<n;i++)
{
printf("enter the record of player[%d]\n",i+1);
fflush(stdin);
printf("Enter the Name:");
gets(list[i].name);
printf("Enter the rank:");
scanf("%d",&list[i].rank);
fflush(stdin);
printf("Enter the country:");
gets(list[i].country);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …377 file. After taking the information it closes the file and displays the
information about the student whose student_id has been entered by
strcpy(list[i].country, the user.
list[j].country);
Ans: #include<stdio.h>
list[j].rank=rtemp; #include<conio.h>
#include<process.h>
strcpy(list[j].name,ntemp);
struct student
strcpy(list[j].country,ctemp);
}
}
}
fwrite(&list,sizeof(list),1,fp);
fclose(fp);

clrscr(); fp=fopen("data.txt","r");
printf("Rank\tName\tcountryress\n ");
while(fread(&list,sizeof(list),1,fp)==1)
{
for(i=0;i<n;i++)
printf("%d\t%s\t%s\n",list[i].rank,list[i].name,l
ist[i].country);
}
fclose(fp);
getch();
}
Result:
How many records?3
ADD RECORDS
enter the record of player[1]
Enter the Name:Ena
Enter the rank:3
Enter the country:Nepal
enter the record of player[2]
Enter the Name:Fagu
Enter the rank:30
Enter the country:India
enter the record of player[3]
Enter the Name:Snjiv
Enter the rank:13
Enter the country:Bhutan
Rank Name Countryees
3 Ena Nepal
13 Sanjiv Bhutan
30 Fagu India
18. Write a program that reads the following information from the
keyboard – student_id, student name and total marks and writer to a
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
{
378 … A Complete Refresh Manual of C Programming int ctr=0;
{ char ch = 'y';
int stu_id; fp=fopen("student.c","w");
char stu_name[30]; while(ch=='y')
int marks; {
}s[100],b; void ctr++;
menu(); void clrscr();
create(); void
display(); void
search(); void
heading(); void
disp();
int i=0;
FILE *fp,*ft;

void main()
{
int first_ch;
clrscr();
heading();
printf("\n\n\n\t\t\t\t MENU");
printf("\n\n\n\t\t1.Create a new database.");
printf("\n\n\t\t2.Continue with the existing
database.");
printf("\n\n\t\t3. Exit.");
printf("\n\n\n\t\tEnter your choice( 1 - 3): ");
scanf("%d",&first_ch);
switch(first_ch)
{
case 1:
create();
break;
case 2:
menu();
break;
case 3:
exit(0);
break;
default:
printf("\n\n\n\t\tYou have entered wrong
choice...!!!..The program will exit now.");
}
getch();
}
void create()
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …379 380 … A Complete Refresh Manual of C Programming


heading(); int ctr=0;
printf("\n\n\n\n\tEnter the Employee default:
Records :\n "); printf("\n\n\tYou have entered a WRONG CHOICE..!!..
printf("\n\n\t\t Student id : "); Please Re-enter your choice");
fflush(stdin); menu();
scanf("%d",&s[i].stu_id); }
printf("\n\n\t\t Name : "); }
fflush(stdin); void display()
scanf("%s",&s[i].stu_name); {
printf("\n\n\t\t Total Marks : ");
fflush(stdin);
scanf("%d",&s[i].marks);
fwrite(&s,sizeof(s[i]),1,fp);
printf("\n\n\n\t\tDo you wish to
enter more records (y/n) ?");
ch=getche();
}
printf("\n\n\n\t%d Records have been written in the
file.",ctr);
fclose(fp);
menu();
}
void menu()
{
char ch;
clrscr();
heading();
printf("\n\n\n\t\t\t MENU :-");
printf("\n\n\t\t1.ToDISPLAY all the records");
printf("\n\n\t\t2.To SEARCH a record");
printf("\n\n\t\t3.EXIT");
printf("\n\n\n\t\tEnter your choice(1- 3):");
scanf("%d",&ch);
switch(ch)
{
case 1:
display();
break;
case 2:
search();
break;
case 3:
exit(0);
break;
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
fp=fopen("student.c","r"); display();
rewind(fp); }
while(fread(&s,sizeof(s[i]),1,fp)==1) }
{ fcloseall();
ctr++; if(flag==0)
clrscr();
heading();
printf("\n\n\n\tFollowing are the details :-");
printf("\n\n\tRecord #%d",ctr);
printf("\n\n\t\tStudentid
:%d",s[i].stu_id);
printf("\n\n\t\t Name :%s",
s[i].stu_name);
printf("\n\n\t\tTotal Marks:%d",
s[i].marks);
printf("\n\n\n\n\t\tPlease Press
Enter...");
getch();
}
menu();
}
void search()
{
int flag; char
ch='y';
while(ch=='y')
{
clrscr();
flag=0;
heading();

printf("\n\n\n\tEnter the Student id to be


searched : ");
fflush(stdin);
scanf("%d",&b.stu_id);
fp=fopen("student.c","r");
rewind(fp);
while(fread(&s,sizeof(s[i]),1,fp)==1)
{
if(s[i].stu_id == b.stu_id)
{
clrscr();
flag=1;
heading();
printf("\n\n\n\tThe details of the record
having Student id %d are :-",b.stu_id);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …381 382 … A Complete Refresh Manual of C Programming


printf("\n\n\n\t\tNo Match found !!"); gets(list[i].country);
printf("\n\n\n\tDo u wish to search for more records }
(y/n) ? ");
ch=getche();
for(i=0;i<n;i++)
}
menu(); {
} for(j=i+1;j<n;j++)
void heading() {
{ if(list[i].rank>list[j].rank)
printf("\n\n\t\t\tSTUDENT DATABASE MANAGEMENT"); {
printf("\n\n\t\t\t----------------------------"); rtemp=list[i].rank;
}
strcpy(ntemp,list[i].name);
strcpy(ctemp,list[i].country);
19. Write a program that reads name, rank and country of N different
list[i].rank=list[j].rank;
players for a data file and prints all the information in descending
strcpy(list[i].name,list[j].name);
order on the basis of rank.
strcpy(list[i].country,
Ans: #include<stdio.h>
list[j].country);
#include<conio.h>
list[j].rank=rtemp;
#include<string.h>
strcpy(list[j].name,ntemp);
#define MAX 500
strcpy(list[j].country,ctemp);
struct player
}
{
}
int rank;
}
char name[15],country[15];
fwrite(&list,sizeof(list),1,fp);
}list[MAX];
fclose(fp);
void main()
{
fflush(stdin);
FILE *fp;
printf("Enter the Name:");
int i,j,rtemp;
gets(list[i].name);
char ntemp[15],ctemp[15];
printf("Enter the rank:");
int n;
scanf("%d",&list[i].rank);
printf(“How many records?”);
scanf(“%d”,&n); fflush(stdin);
printf("Enter the country:");
printf("ADD RECORDS\n\n");
fp=fopen("data.txt","w");
for(i=0;i<n;i++)
{
printf("enter the record of
player[%d]\n",i+1);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
clrscr();
fp=fopen("data.txt","r");
printf("Rank\tName\tcountryres
s\n ");
while(fread(&list,sizeof(list)
,1,fp)==1)
{
for(i=0;i<n;i++)
printf("%d\t%s\t%s\n",list[i].rank,lis
t[i].name
,list[i].country);
}

f
c
l
o
s
e
(
f
p
)
;
g
e
t
c
h
(
)
;
}
Result:
How many records?3
ADD RECORDS

enter the record of


player[1] Enter the
Name:Ena
Enter the rank:3
Enter the country:Nepal

enter the record of player[2]


F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …383 384 … A Complete Refresh Manual of C Programming


Enter the Name:Fagu if(==NULL)
Enter the rank:30 {
Enter the country:India printf(“File can not be opened:”):
getch();
enter the record of player[3] exit(1);
Enter the Name:Snjiv }
Enter the rank:13 printf ("Name \t Phone \n");
Enter the country:Bhutan printf(" ......................\n");
while (fread (&rec, sizeof (rec), 1,
Rank Name Countryees fp) = =1)
3 Ena Nepal printf ("%s \t %s \n", list[i].name,
13 Sanjiv Bhutan listi].phone);
30 Fagu India fclose (fp);
getch ( );
}
gets (list[i].name);
20. Write a program to read name and phone number of N number of printf ("Enter phone: \n");
people. Write them on file and close it. Reopen the file and display gets(list[i].phone);
the data on it. [T.U. 2066 Jestha] fwrite (&rec, size of (rec), 1, fp);
Ans: #include<stdio.h> }
#include<conio.h> fclose(fp);
#include<string.h> // Displaying records
#define MAX 500 fp=fopen("data.txt","rb");
struct record
{
char name[25],phone[15];
}list[MAX];
void main()
{
FILE *fp;
int i,n;
printf(“How many records?”);
scanf(“%d”,&n);
fp=fopen("data.txt","wb");
if(==NULL)
{
printf(“File can not be opened:”):
getch();
exit(1);
}
for (i = 0; i < N; i++)
{
fflush(stdin);
printf ("Enter name : \n");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

21. Write a program that ask the user to input Name, Age of N different
film actors for a file and prints them in appropriate format. [Use
fwrite( ) and fread( ) functions]
Ans: #include <stdio.h.>
#include <conio.h>
struct actor
{
int age;
char name [25];
}rec;
void main ( )
{
FILE *fp;
int i, N;
fp = fopen ("dec.dat", "w+");
printf ("Enter how many nos:");
scanf ("% d", &N);
// Entering data
for (i = 0; i < N; i++)
{
fflush(stdin);
printf ("Enter name : \n");
gets (rec.name);
printf ("Enter age : \n");
scanf ("%d", &rec.age);
fwrite (&rec, size of (rec), 1, fp);
}
rewind (fp);

// Displaying records
printf ("Name \t Age \n");
printf(" ......................\n");
while (fread (&rec, sizeof (rec), 1,
fp) = =1)
printf ("%s \t %d \n", rec.name,
rec.age);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …385 386 … A Complete Refresh Manual of C Programming


fclose (fp); while (i!=0 && j!=0)
getch ( ); {
} i=fgets(ch1,80,fp1);l1++;
Result: j=fgets(ch2,80,fp2);l2++;
Enter how many :2 if (strcmp(ch1,ch2)!=0)
Enter name :Haris {
Enter age :34 printf ("\nContents of both Files are
not Equal");
Enter name :Sila printf ("\nLineNumber\tContents\t
Enter age :24 File name\n");
printf ("%d\t\t%s\t\tFrom %s",l1 ,ch1,argv[1]);
Name Age printf ("%d\t\t%s\t\tFrom
............ %s",l2,ch2,argv[2]);
Haris 34 exit();
Sila 24 }
}
22. Write a program which accepts two file names from the command if (i==0 && j==0)
printf ("\nBoth Files are equal");
line and prints whether the contents of the two files are same or not. else
If not, then print the first line number and then the contents of the {
lines from which they differ. Assume that the lines in both the files printf("\nunable to open the file
have at most 80 characters. %s",argv[2]);
Ans: #include<stdio.h> getch();
main(int argc, char *argv[]) exit();
{
FILE *fp1, *fp2;
char ch1[80],ch2[80];
int i=1,j=1,l1=0,l2=0;
if (argc!=3)
{
printf ("\nWrong number of arguments.");
getch();
exit();
}
fp1=fopen(argv[1],"r");
if (fp1==NULL)
{
printf ("\nunable to open the file
%s",argv[1]);
getch();
exit();
}
fp2=fopen(argv[2],"r");
if (fp2==NULL)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
printf("\nBoth files are not equal"); putc(h,fp);
getch(); switch(h)
} {
23. Write a program to create a data file and count total number of case 'a':
vowel. case 'e':
Ans: #include<stdio.h> case 'i':
#include<Conio.h> case 'o':
void main() case 'u':
{ v++;
FILE *fp; }
char h; int v=0; clrscr(); }
fp=fopen("text.dat","w"); printf("\nTotal vowels are %d",v);
printf("\nInput text to write into file \n"); fclose(fp);
while((h=getc(stdin))!=EOF) getch();
{ }
}
l1=0; Result:
l2=0; Input text to write into file
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
{
C Programming Language …387 printf ("\nEnter Employee
We are studying computer engineering.^Z Code:-> ");
flushall();
Total vowels are 13 scanf ("%d",&emp.code);
printf ("\nEnter
Employee Name:-> ");
24. Write a complete C program for reading an employees file flushall();
containing {emp_number, name, salary, address}. Create an output gets(emp.name);
file containing the names of those employees along with their salary
and address whose salary is > 20,000.
Ans: #include<stdio.h>
#include<conio.h>
#include<process.h>
struct employee
{
int code;
char name[30];
char address[50];
char phone[10];
float sal;
}emp,tmp;
FILE *fp1,*fp2;
void main()
{
char ch='y';
int i=1;

//Assuming that the file already exists


fp1=fopen("employee.txt","r");
if (fp1==NULL)
{
fp1=fopen("employee.txt","w");
if (fp1==NULL)
{
printf ("\nUnable to create
Employee.txt file");
getch();
exit(0);
}
printf ("\nNo Data found in
Employee.txt. Add new
records");
while (1)
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
fclose (fp2);
388 … A Complete Refresh Manual of C Programming fp2=fopen("output.txt","r");
printf ("\nEnter Employee i=1;
Address:-> "); while (1)
flushall(); {
gets(emp.address); i=fread(&emp,sizeof(emp),1,fp2);
printf ("\nEnter Employee if(i==0)break;
Phone Number:-> ");
flushall();
gets(emp.phone);
printf ("\nEnter Employee
Salary:-> ");
flushall();
scanf("%f",&emp.sal);

/*Writing records to
Employee.txt file*/
fwrite(&emp,sizeof(emp),1,fp1);
printf ("\nDo u want to add more records (y/n):->”);
flushall();
scanf("%c",&ch);
if (ch=='n' || ch=='N')break;
}
fclose(fp1);
fp1=fopen("employee.txt","r");
}
printf ("\nList of Employees having Salary
greater than 20000\n");
printf ("\nCode\tName\t\tAddress\tPhone
No.\tSalary\n"); i=1;
fp2=fopen("Output.txt","w");
getch();
if (fp2==NULL)
{
printf ("\nUnable to create Output
file\n");
getch();
exit(0);
}
while (1)
{
i=fread(&emp,sizeof(emp),1,fp1);
if(i==0)break;
if (emp.sal>20000)
fwrite(&emp,sizeof(emp),1,fp2);
}
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
{
C Programming Language …389 FILE *fp,*fpt;
printf("\n%d\t%s\t\t%s\t%s\t%f" struct employee list,temp;
,emp.code,emp.name,emp.address,emp.ph int ch,emco;
one,emp.sal); while(1)
} {
getch(); printf("\tMAIN MENU\n");
} printf("1.Add record\n");

Result:
Add new records
Enter Employee code:-> 1
Enter Employee Name:-> Rabin
Enter Employee Address:-> Baneshwor
Enter Employee Phone Number:-> 44354
Enter Employee Salary:-> 21000
Do u want to add more records (y/n):->n

List of Employees having Salary greater than


20000
Code Name Address Phone Salary
1 Rabin Baneshwor 443544 21000.00

25. Develop a menu driven program to create a sequential data file


called employee.dat with following fields: Emp_code, Emp_name,
Post and Salary. The program should work on option as given
below:
1. Add Record
2. Display Record
3. Search Record
4. Delete Record
5. Update Record
6. Exit
Ans: #include<stdio.h>
#include<conio.h>
#include<process.h>
#include<string.h>
struct employee
{
char name[20],post[15];
int ecode;
float salary;
};
void main()
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
post,list.salary);
390 … A Complete Refresh Manual of C Programming }
printf("2.Display record\n"); if(emco==0)
printf("3.Search record\n"); printf("File not found");
printf("4.Delete record\n"); fclose(fp);
printf("5.Update record\n"); }
printf("6.Exit\n");
printf("\n\n");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
fp=fopen("employee.dat","a");
printf("Enter ecode:\n");
scanf("%d",&list.ecode);
fflush(stdin);
printf("Enter Name:\n");
scanf("%s",&list.name);
printf("Enter post:\n");
scanf("%s",&list.post);
printf("Enter salary:\n");
scanf("%f",&list.salary);
fwrite(&list,sizeof(list),1,fp);
fclose(fp);
}
break;
case 2:
{
fp=fopen("employee.dat","r");
printf(“Ecode\tName\Post\Salary\n”);
printf(“…………………………………………\n”);
while(fread(&list,sizeof(list),1,fp)==1)
printf("%d\t%s\t%s\t%f\n",list.ecode,list.name,list.
post,list.salary);
fclose(fp);
}
break;
case 3:
{ fp=fopen("employee.dat","r");
printf("Enter employee code:");
scanf("%d",&emco);
while(fread(&list,sizeof(list),1,fp)==1)
{ if(emco==list.ecode)
printf("%d\t%s\t%s\t%f\n",list.ecode,list.name,list.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …391 392 … A Complete Refresh Manual of C Programming


break; list.ecode=emco;
case 4: list.salary=temp.salary;
{ fwrite(&temp,sizeof(temp),1,fpt);
int j=0; printf("The record is modified.\n");
fp=fopen("employee.dat","r"); }
fpt=fopen("temp.dat","w"); fclose(fp);
fflush(stdin); fclose(fpt);
printf("Enter employee code to delete:"); remove("employee.dat");
scanf("%d",&emco); rename("temp.dat","employee.dat");
while(fread(&list,sizeof(list),1,fpt)==1) }
{ }
if(emco==list.ecode) break;
j++; case 6:
else exit(0);
fwrite(&list,sizeof(list),1,fpt); default:
fflush(stdin); printf("Invalid Option");
} exit(0);
if(j==0) }
printf("Record not found"); getch();
fclose(fp); }
fclose(fpt); }
remove("employee.dat"); Result:
rename("temp.dat","employee.dat"); MAIN MENU
printf("Such record has deleted\n");
1. Add record
}
break; 2. Display record
case 5: 3. Search record
{ 4. Delete record
fp=fopen("employee.dat","r"); printf("Enter new
fpt=fopen("temp.dat","w"); name:");
fflush(stdin); gets(temp.name);
printf("Enter employee code to update"); printf("Enter new
scanf("%d",&emco); post:");
while(fread(&list,sizeof(list),1,fp)==1) gets(temp.post);
{ printf("enter
if(emco==list.ecode) salary:");
{ scanf("%f",&temp.salar
fwrite(&list,sizeof(list),1,fpt); y);
fflush(stdin); strcpy(list.name,temp.name);
printf("Such record is not available\n"); strcpy(list.post,temp.post);
}
else
{
fflush(stdin);
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
5. Update record
6. Exit
Enter your choice:1
Enter ecode:101
Enter name:Gauri
Enter post:Peon Enter
salary:4500
MAIN MENU
1. Add record
2. Display record
3. Search record
4. Delete record
5. Update record
6. Exit
Enter your choice:2
Ecode Name Post Salary
101 Gauri Peon 4500
MAIN MENU
1. Add record
2. Display record
3. Search record
4. Delete record
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …393 394 … A Complete Refresh Manual of C Programming


5. Update record 2.18 Graphics
6. Exit
Enter your choice:6
We will restrict our discussion on Graphics in C Language to
16 bit C programming andMS DOS environment. In a C Program first
of all you need to initialize the graphicsdrivers on the computer. This
is done using the initgraph method provided in graphics.hlibrary. In
the next few pages we will discuss graphics.h library in details.
Importantfunctions in graphic.h library will be discuees in details and
samples programmes will beprovided to show the power of C
programming language
Turbo C has a good collection of graphics libraries. If you
know the basics of C, you can easily learn graphics programming. To
start programming, let us write a small program that displays a circle
on the screen.
#include<graphics.h>
#include<conio.h>
void main()
{
int gd=DETECT, gm;
initgraph(&gd, &gm, "c:\\turboc3\\bgi " );
circle(200,100,150);
getch();
closegraph();
}
To run this program, you need graphics.h header file,
graphics.lib library file and Graphics driver (BGI file) in the program
folder. These files are part of Turbo C package. In all our programs we
used 640x480 VGA monitor. So all the programs are according to that
specification. You need to make necessary changes to your programs
according to your screen resolution. For VGA monitor, graphics driver
used is EGAVGA.BGI.
Here, initgraph() function initializes the graphics mode and
clears the screen. We will study the difference between text mode and
graphics mode in detail latter.
Init Graph: Initializes the graphics system.
Declaration:
void far initgraph(int far *graphdriver, int far *graphmode, char far
*pathtodriver); Remarks: To start the graphics system, you must first
call initgraph. initgraph initializes the graphics system by loading a
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
graphics driver from disk (or validating a registered driver) then
putting the system into graphics mode. initgraph also resets all
graphics settings (color, palette, current position, viewport, etc.) to
heir defaults, then resets graphresult to 0. Arguments:
*graphdriver: Integer that specifies the graphics driver to be used.
You can give graphdriver a value using a constant of the graphics
drivers enumeration type.
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
ellipse(500, 100,0,360, 100,50);
C Programming Language …395 outtextxy(480, 170, "Ellipse");
*graphmode : Integer that specifies the initial graphics mode (unless line(100,250,540,250);
*graphdriver = DETECT). If *graphdriver = DETECT, initgraph sets outtextxy(300,260,"Line");
*graphmode to the highest resolution available for the detected driver.
sector(150, 400, 30, 300, 100,50);
You can give *graphmode a value using a constant of the outtextxy(120, 460, "Sector");
graphics_modes enumeration type.
pathtodriver : Specifies the directory path where initgraph looks for
graphics drivers (*.BGI) first. If they're not there, initgraph looks in
the current directory. If pathtodriver is null, the driver files must be in
the current directory. This is also the path settextstyle searches for the
stroked character font files (*.CHR).
closegraph() function switches back the screen from graphcs mode to
text mode. It clears the screen also. A graphics program should have a
closegraph function at the end of graphics. Otherwise DOS screen will
not go to text mode after running the program. Here, closegraph() is
called after getch() since screen should not clear until user hits a key.
If you have the BGI file in the same folder of your program, you can
just leave it as "" only. you need not mention *graphmode if you give
*graphdriver as DETECT.
In graphics mode, all the screen co-ordinates are mentioned in terms of
pixels. Number of pixels in the screen decides resolution of the screen.
In the example 1.0, circle is drawn with x-coordinate of the center
200, y-coordinate 100 and radius 150 pixels. All the coordinates are
mentioned with respect to top-left corner of the screen.
Basic Shapes and Colors:
Now let us write a program to draw some basic
shapes.
#include<graphics.h>
#include<conio.h>
void main()
{
int gd=DETECT, gm;
int poly[12]=
{350,450,350,410,430,400,350,350,300,
430,350,450};
initgraph(&gd, &gm, "");

circle(100,100,50);
outtextxy(75,170, "Circle");
rectangle(200,50,350,150);
outtextxy(240, 170, "Rectangle");
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

396 … A Complete Refresh Manual of C place where last drawing is ended. These functions are declared as
Programming follows:
void far outtextxy(int x, int y, char *text);
drawpoly(6, poly); void far outtext(char *text);
outtextxy(340, 460, "Polygon");
Circle, arc, pieslice are declared as follows:
getch(); Declaration:
closegraph(); • void far arc(int x, int y, int stangle, int endangle, int radius);
} • void far circle(int x, int y, int radius);
Here is the screenshot of output: • void far pieslice(int x, int y, int stangle, int endangle, int radius);
Remarks:
• arc draws a circular arc in the current drawing color.

Here, circle() function takes x, y coordinates of the


circle with respect to left top of the screen and radius of the
circle in terms of pixels as arguments. Not that, in graphics,
almost all the screen parameters are measured in terms of
pixels.
Function outtextxy() displays a string in graphical mode.
You can use different fonts, text sizes, alignments, colors and
directions of the text that we will study later. Parameters passed
are x and y coordinates of the position on the screen where text
is to be displayed. There is another function outtext() that
displayes a text in the current position. Current position is the
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …397 setfillstyle, if we use functions like floodfill, fillpoly, bar etc, shpes will
be filled with fill color and pattern set using setfillstyle
• circle draws a circle in the current drawing color. These function declarations are as follows.
• pieslice draws a pie slice in the current drawing color, then fills it Declaration:
usingthe current fill pattern and fill color. • void far setfillstyle(int pattern, int color);
Arguments: • void far setcolor(int color);
• (x,y): Center point of arc, circlew, or pie slice • void far setbkcolor(int color);
• stangle: Start angle in degrees
• endangle: End angle in degrees r radius: Radius of arc, circle, and
pieslice adius: Radius ofarc, circle, and pieslice
Here, stangle and endangle are in degrees starting from the +ve
x-axis in the polar coordinate system in the anti-clockwise direction. if
stangle is 0, endangle is 360, it will draw a full circle. Refer this figure
for clear idea: For the details of current color, fill color and fill
patterns, refer the sections Lines and Colors.
Here is some idea about colors.
There are 16 colors declared in graphics has listed bellow:
BLACK: 0
BLUE: 1
GREEN: 2
CYAN: 3
RED: 4
MAGENTA: 5
BROWN: 6
LIGHTGRAY: 7
DARKGRAY: 8
LIGHTBLUE: 9
LIGHTGREEN: 10
LIGHTCYAN: 11
LIGHTRED: 12
LIGHTMAGENTA: 13
YELLOW: 14
WHITE: 15
To use these colors, use functions setcolor(), setbkcolor() and
setfillstyle(). setcolor() function sets the current drawing color. If we
use setcolor(RED); and draw any shape, line or text after that, the
drawing will be in red color. You can either use color as defined
above or number like setcolor(4);. setbkcolor() sets background color
for drawing. Setfillstyle sets fill pattern and fill colors. After calling
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a
{
398 … A Complete Refresh Manual of C Programming int gd,gm;
Remarks: gd=DETECT;
• setfillstyle sets the current fill pattern and fill color. initgraph(&gd, &gm, "");
• setcolor sets the current drawing color to color, which setcolor(3);
can range from 0 to getmaxcolor. setfillstyle(SOLID_FILL,RED);
• setbkcolor sets the background to the color specified bar(50, 50, 590, 430);
by color. The parameter pattern in setfillstyle is as follows:
setfillstyle(1, 14);
Names Value Means Fill bar(100, 100, 540, 380);
With... EMPTY_FILL 0 while(!kbhit())
Background color SOLID_FILL {
1 Solid fill LINE_FILL 2
--- LTSLASH_FILL 3 ///
SLASH_FILL 4 ///,
thick lines BKSLASH_FILL
5 \\\, thick lines LTBKSLASH_FILL
6 \\\ HATCH_FILL 7
Light hatch
XHATCH_FILL 8 Heavy
crosshatch INTERLEAVE_FILL 9
Interleaving lines WIDE_DOT_FILL 10
Widely spaced dots CLOSE_DOT_FILL
11 Closely spaced dots USER_FILL
12 User-defined fill pattern
Here is an example program with colors, pixels,
bar, cleardevice etc. stdlib.h is used for random number
generation. We have a function random(no), it returns a random
number between 0 an no. The effect is by drawing random
radius, random color circles with same center and random
pixels. kbhit() function(defined in conio.h) returns a nonzero
value when a key is pressed in the keyboard. So, the loop will
continue until a key is pressed.
#include "graphics.h"
#include "conio.h"
#include
"stdlib.h"
void main()
F -X C h a n ge F -X C h a n ge
PD PD

!
W

W
O

O
N

N
y

y
bu

bu
to

to
ww

ww
om

om
k

k
lic

lic
C

C
.c

.c
w

w
tr re tr re
.

.
ac ac
k e r- s o ft w a k e r- s o ft w a

C Programming Language …399

putpixel(random(439)+101,random(279)+101,random(16))
setcolor(random(16));
circle(320,240,random(100));
} getch();
closegraph();
}
Here is a sample program to illustrate how to use BARS which are
used for visual statistics
#include<graphics.h>
#include<conio.h>
main()
{
int gd=DETECT,gm,maxx,maxy,x,y,button;
initgraph(&gd,&gm,"");

line(80,150,200,150);
line(80,150,80,50);

settextstyle(1,HORIZ_DIR,1);
outtextxy(100,153,"<-X axis");
settextstyle(1,VERT_DIR,1);
outtextxy(60,50,"<-Y axis");
bar(100,100,120,150);
bar(130,120,150,150);
getch();
closegraph();
}

Good Luck

You might also like