You are on page 1of 153

S.

No Document Name Page No


Procedural Manual For Conducting
Experiments In Programming Lab 1-6
I B.TechExercise
PROGRAMMING
1 LAB MANUAL
a) Identifying the discrete components of a
computer and networking components
b) Demonstration of assembling a computer 7-40
c) Demonstrating installation of OS and
applications

a) Creating a document using MS Word


Exercise 2 b) Creating a document using LaTeX 41-44

Exercise 3 a) Familiarizing with the usage and applications


of MS Excel Using Excel 45-51
b) Creating a presentation using MS Powerpoint

Exercise 4 Familiarizing with the Integrated Development


Environment (IDE) for developing C programs 52-53

Exercise 5
Write a C program for the following:
a) Calculate the area of triangle using the
formula area = (s (s-a) (s-b)(s-c))1/2
where 54-60
s= (a+b+c)/2
b) Find the largest of three numbers using
ternary operator.
c) Find the roots of a quadratic equation.

Exercise 6 Develop a C program for the following:


a) Read two integer operands and one
operator form the user, perform the
operation and then print the result.
(Consider the operators +,-,*, /, % and
use Switch Statement)
b) Check whether given number is Prime
(or) not
c) Display first N natural numbers. 61-73
d) Calculate electricity bill for the
consumed units – assume suitable
constraints.
e) Find the sum of individual digits of a
positive integer and find the reverse of
the given number.

Exercise 7
Design a C program for the following: 74-99
a) Find the largest and smallest numbers in
the array.
b) Search whether the given element is in
the array.
c) Perform Addition, subtraction and
multiplication of Matrices
d) Delete n Characters from a given
Page |1 position in a given string.
Department of Computer Science & Engineering GEC
e) Illustrate at least five string handling
functions.

Exercise 8 Implement a C program for the following:


I B.Tech PROGRAMMING LAB MANUAL

EQUIPMENT REQUIRED FOR CONDUCTING THE


LAB EXPERIMENTS
HARDWARE AND SOFTWARE REQUIRED:
1. A working computer system with either Windows XP or Windows 2003.
2. Every student should be provided with a separate Cabinet for assembling and
dessembling the components of a Cabinet.
3. Windows XP Installation Software.
4. Pentium IV Processor and MotherBoard will all its components,
5. 256 MB RAM
6. 40 GB Hard Disk
7. CD ROM,CD Writer and Floppy Disk Drives
8. Keyboard & Mouse
9. Microsoft Office Suite 2007 (Incuding Powerpoint, Word, Excell)
10.LaTex Software

PROGRAMMING LAB OBJECTIVE:


 Familiarize with the discrete components of computers and networking components
 Familiarize with usage of MS Office Tools
 Provide the practice of solving problem on computer using C

Page |2 Department of Computer Science & Engineering GEC


I B.Tech PROGRAMMING LAB MANUAL

UPON COMPLETION, STUDENTS WILL BE ABLE TO:


Students will be able to
 indentify discrete components of computers and networking components
 describe the functions of discrete components of computers and networking
components
 employ MS Office Tools for creating documents and presentations and making
computations
 use computer for solving problems

REFERENCES

1. Introduction to Information Technology, ITL Education Solutions limited, Pearson


Education.
2. LaTeX Companion – Leslie Lamport, PHI/Pearson.
3. Introduction to Computers, Peter Norton, 6/e Mc Graw Hill
4. Comdex Information Technology course tool kit Vikas Gupta, WILEY Dreamtech
5. IT Essentials PC Hardware and Software Companion Guide Third Edition by David
Anfinson and KenQuamme. – CISCO Press, Pearson Education.
6. PC Hardware and A+Handbook – Kate J. Chase PHI (Microsoft)

Page |3 Department of Computer Science & Engineering GEC


I B.Tech PROGRAMMING LAB MANUAL

7. C Programming, E Balaguruswamy, 3rd edition, TMH.


8. C Programming, A Problem Solving Approach, Forouzan, Gilberg, Prasad, CENGAGE.
9. Programming in C, Second Edition Pradip Dey and Manas Ghosh, OXFORD Higher
Education

GUIDELINES TO STUDENTS
 Equipment in the lab for the use of student community. Students need to maintain a
proper decorum in the computer lab.

 Students must use the equipment including PCs, Keyboard and Mouse with care. Any
damage is caused is punishable.

 Students are required to carry their observation and record books with completed
exercises while entering the lab.

 Students are supposed to occupy the machines allotted to them and are not
supposed to talk or make noise in the lab..

 Lab can be used in free time / lunch hours by the students. Students who need to
use the systems should take prior permission from the lab in-charge.

 Lab records need to be submitted on or before date of submission.

 Students are not supposed to use floppy disks/CDs/Pen drives etc during the Lab
session.

 Use of computer network is not encouraged.

Page |4 Department of Computer Science & Engineering GEC


I B.Tech PROGRAMMING LAB MANUAL

PART - A

EXERCISE 1(A): IDENTIFYING THE DISCRETE COMPONENTS OF A


COMPUTER AND NETWORKING COMPONENTS

A Computer is a programmable electronic machine that can store, retrieve and process
data.
It was designed to automatically carry out a sequence of arithmetic or logical operations.

THE FOLLOWING ARE THE


VARIOUS COMPONENTS OF A
COMPUTER:
 Motherboard
 Central Processing Unit (CPU)
 Switching Mode Power
Supply (SMPS)
 Cabinet
 CPU Heat Sink & Fan
 Random Access Memory (RAM)
 Hard Disc Drive (HDD)
 Floppy Disc Drive (FDD)
 CD ROM Drive
 CD Writer

Page |5 Department of Computer Science & Engineering GEC


I B.Tech PROGRAMMING LAB MANUAL

 Different Screws used


 Accelerated Graphics Port (AGP) Card
 LAN/ETHERNET Card
 Cables

1. MOTHERBOARD:
 The Motherboard is the main circuit board in a computer. It interconnects all the
parts of a computer together.
 It provides a way for hardware in a computer to communicate with each other.
 The CPU, Memorym hard Drives, optical drives, Video card, Sound card and all other
ports and expansion cards all connect to the motherboard directly or via cables.
It can be thought of as the “backbone” of the computer and is also called as Main board,
system board or logic board.

Different components of a MotherBoard:


 SOCKET 478  PCI Slot
 North Bridge  CNR Slot
 South Bridge  BIOS
 CMOS Battery  ATX Power Connector
 Primary & Secondary IDE  Floppy Drive Connector
 Ports  CD In jacks
 RAM Slots (SD RAM & DDR RAM)  CMOS Jumper
 AGP Slot  System fan connector

Page |6 Department of Computer Science & Engineering GEC


 SOCKET 478/CPU Socket:
 A Socket is an electrical component that is attached to a Motherboard and is designed to house a CPU.
It provides many functions, including:
o A Physical structure to support the CPU
o Support for a Heat Sink
o Forming an electrical interface both with the CPU and the Motherboard.
 It provides mechinal and electrical connections between a CPU and the Motherboard. Here 478
indicates that this socket can hold a CPU with 478 pins.

 CPU Heat Sink & Fan Retention Module:


The main function of this module is to see that the Heat sink and fan assembly does not loose
contact with the CPU such that, there is no possibility of the CPU getting burnt because of missed contact with
the heat sink. The locking lever locks the CPU into the socket.

 NorthBridge:
It is the focal point of the motherboard. It connects CPU/Socket, RAM slots and AGP slots. It handles
communication among the CPU, RAM, Agp and the Southbridge.

7
 SouthBridge:
It is not directly connected to the CPU. NorthBridge ties the Southbridge to the CPU. It handles all of a
computer Input/Output functions such as USB, audio etc. It consists of Real time clock and controller to I/O
port.

 CMOS (Complementary Metal Oxide Semiconductor) Battery:


CMOS memory is a small memory on PC Motherboards that is used to store BIOS settings so that, each time
the computer restarts or powers on, the computer applies those settings.
CMOS battery powers the CMOS memory so that BIOS data is not lost even when the computer is off and
even when it is unplugged and removed. It also powers Southbridge. It keeps the system clock running even
when the computer is turnned off.

 Primary and Secondary IDE Channels:


IDE  Integrated Drive Electronics
These are 40 pin IDE interfaces that are used to connect IDE devices like Hard Disc, CD Drive, DVD Drive etc
to the Motherboard.

 Ports:

8
Ports are an Interface between the computer and the external world. The various ports of the
motherboard are:
PS/2 Mouse port - used to connect Mouse
or
PS2 ports Keyboard port - used to connect Keyboard
Parallel port - used to connect devices like printer
Serial port - used to connect devices like mouse ans external modem
VGA Port - Video Graphics Array
used to hold on board VGA card. Generally monitor is connected to this
port.
Ethernet/RJ 45 port - used with LAN card. It is an outerview of RJ 45 Jack associated with LAN
cards.
USB port - Universal Serial Bus. It is a high speed serial interface that is used with all
devices like pendrives etc.
Gaming port - used to connect gaming devices like Joysticks.
Sound ports - Line in, Line out and Micro phone

 RAM Slots:
There are 2 types of RAM slots
1) SDRAM (Synchronous Dynamic Random Access Memory) slots
2) DDR RAM (Double Data Rate Random Access Memory) slots
These RAM slots holds the corresponding RAM modules
SDRAM slots hold SD RAM
DDR RAM slots hold DDR RAM
These two slots differ in the number of Notches (gaps). SDRAM slot has 3 Notches while DDR RAM has only
one Notch.

9
 AGP Slot: AGP stands for Accelerated Graphics Port
It holds AGP card. It is a high speed point-to-point channel for attaching a graphics card to a computer
motherboard. It is faster than PCI slot..
 PCI Slots: PCI stands for peripheral Component Interconnect.
It is used as an expansion slot. It holds external cards which are used to increase the capabilities of the
system. There are more than one PCI slot.
 CNR Slot: CNR Stands for Communications and Networking Raiser
It is a dedicated connector for cards apecific to the motherboard design to offer communications and
networking options.

 BIOS: BIOS stands for Basic Input Output System


It provides a small library of basic I/O functions used to operate and control the peripherals such as
keyboard,display on the monitor etc.
BIOS setting can be used to:
o Configure hardware
o Set the system clock
o Enable/disable system components etc

 ATX Power Connector: ATX stands for Advanced Technology eXtended

10
This is the point from which the motherboard derives the power to work. It has 20 pins.
 Floppy Drive Connector: Used to power floppy drive.

 CD in Jacks:
This is the point from which the cable from the CD Drive is to be connected in order to listen to audio
while playing an audio CD.

 CMOS Jumper: Consists of 3 pins


When connected to the pins 1 and 2 it holds the user programmed data in the BIOS. When connected to
the pins 2 and 3 it clears the BIOS and hence restores the default data in the BIOS.

2. CPU: CPU stands for Central Processing Unit.


It is considered as the heart of the computer. It is the portion of a computer that carries out the
instructions of a computer program, to perform the basic arithmetic, logical and input/output operations of
the system.

11
The missing pins on the CPU indicate Pin1 indication which must coincide with thw pin1 indication of the
Socket while installing the CPU.

3. SMPS: SMPS stands for Switching Mode Power Supply


It is the device which supplies power to each and every component inside the computer to work. It consists
of
1. A fan to expell the heat generated inside
2. 230v AC input jack which recieves I/P
3. 230v AC output jack generally connected to the monitor.

4. CABINET:
It holds all the components of a computer.
Power switch: Starts the computer
Reset switch: Restarts the computer
Power LED: Glows when computer is working
HDD LED: glows when ever hard disk is accessed

12
Front view Back view Inner view of the Cabinet

5. CPU HEAT SINK & FAN:


It consists of locking levers which are used to secure this assembly to the CPU heat sink and fan retention
module around the socket. It consists of Fan which is used to expel heat from the heat sink to the atmosphere.

6. RAM: RAM stands for Random Access Memory


There are 2 types of RAM’s
1. SD RAM – 2 Notches, speed 133MHz

13
2. DDR RAM – 1 Notch, speed 266 MHz

7. HARD DISK DRIVE (HDD):


Jumper pins—used to change settings of Hard Disk
Power Connector – used to power the Hard Disk

8. FLOPPY DISK DRIVE (FDD):

Access LED -- glows when the floppy is accessed


Eject button -- used ti eject the floppy out of the drive
Power connector -- this is the point from which the FDD derives the power to work
Data cable connector -- comes from the Motherboard

9. CD ROM DRIVE: CD ROM stands for Compact Disk Read Only Memory
It can read data from a CD but cannot write data onto it.

14
Head phones jack: used to listen to audio when the CD Drive is playing an audio CD
Volume control: used to control the volume level coming out of the head phones jack
Access LED: glows whenever the CD inside the CD drive is accessed
Pin hole: used to unlock the drive to remove the CD in the drive in case of a power failure.
Open/Close button: used to open/close the drive

CD Audio Connectors: A cable from this is to be connected to the sound card in order to listen sound while
playing an audio CD
Jumper pins: used to change the settings of the drive
IDE Connector: An IDE connector from motherboard is connected to this inorder to
exchange signals
Power Connector: This is the point from which the CD ROM Drive derives the power to work

10. CD WRITER DRIVE:


It can read as well as write data onto a CD

15
52X  speed at which the drive can write data onto a CD
24X  speed at which the drive can rewrite data onto a rewritable CD
52X  speed at which the drive can read data from a CD

11. DIFFERENT SCREWS USED:


The follwing are the different screws used to connect different components of a computer.

Outer screw – used to connect the Cabinet case, SMPS etc


Inner screw – used to connect the devices inside the computer like CD Drive, HD Drive etc
Motherboard screw – used exclusively to screw the motherboard inside the cabinet/chasis

12. AGP CARD:


AGP Stands for Accelerated Graphics Port.
It is responsible for displaying information on the monitor

16
13. LAN CARD/ETHERNET CARD/NETWORK INTERFACE CARD:
LAN stands for Local Area Network
This card is used to connect two or more devices hence making communication between them possible.

LINK LED – Glows when there is any active connection to the card
ACT LED – Glows when ever the card sends/receives data

17
ACT stands for Acknowledgement

14. CABLES:
Floppy Drive Cable – Always has a Twist
IDE Cables – Used to connect IDE devices such as the Hard disk, CD Drive etc
IDE cables are available in 2 versions
1. 40 conductor cable – low speed
2. 80 conductor cable – high speed

18
EXERCISE 1(B): DEMONSTRATION OF ASSEMBLING A COMPUTER

ASSEMBLING A PENTIUM – IV PC WITH THE FOLLOWING COMPONENTS:


 Motherboard
 P-IV 1.6 GHz 478 pin CPU
 SMPS
 256 MB SD RAM
 Hard Disk Drive (HDD)
 Floppy Disk Drive (FDD)
 CD ROM Drive
 CD Writer Drive
 Ethernet/LAN Card

THE FOLLOWING ARE THE STEPS TO BE FOLLOWED:


1. Preparing the Chasis/Cabinet
 Open the cabinet side doors
 Install the I/O shield

19
2. Installing the Motherboard
 Always hold the motherboard on the RAM slots/PCI slots or CNR slots
 Place the Motherboard in such a way that the ports of the motherboard correctly fit into the I/O
shield
 Fix the screws to the motherboard
 Don’t touch the motherboard with the sharp edge of the screw driver as it may damage some of the
components of the motherboard.

20
3. Installing the CPU
 Unlock the lever of the socket 478 and move it up until it is perpendicular to the motherboard
 Place the CPU in the socket 478 and make sure that the pin1 indication of the CPU must coincide with
the pin1 of the socket 478. Never press CPU into the socket.
 Now, lock the socket 478 by restoring the locking lever to its original position.

21
4. Installing the CPU heat sink and fan assembly
 Put the CPU heat sink and fan assembly into the COU heat sink and fan retention module and secure
(lock) it to the CPU heat sink and fan retention module
 Power the CPU heat sink and fan by plugging 9in the power connector into the CPU fan connector on
the Motherboard.

5. Installing the RAM


 Catch the RAM at the edges and put into the corresponding Ram slot in such a way that the Notches
on the RAM must go into the Notches on the slot.
 Press the RAM into the slot until the White levers got locked.

22
6. Installing the SMPS
 Place the SMPS in the SMPS case and secure (lock) it to the chasis with the help of 4 outer screws

7. Installing the ATX power connector


 Put the ATX power connector into the corresponding connector on the motherboard and
 Press it until it gets locked.

8. Installing the HDD


 Put the Hard disk into the corresponding Hard disk cabin and secure it using the Inner screws
 Connect the IDE data cable to the IDE channel on the Motherboard in such a way that the Notch on
the cable goes into the notch provided on the motherboard
 Connect the other end of the data cable to the HDD in such a way that when we install the power
connector, the red wire on the power connector and red wire on the IDE data cable come adjacent to
each other.

23
9. Installing the FDD
 Remove the cover on the front side of the cabinet pertaining to the Floppy disk drive
 Push the FDD into the case from front
 Secure the FDD to the chasis with Inner screws
 Connect one end of the FDD cable to the Motherboard and the other end to the FDD
 Connect the cable to the FDD in such a way that when we install the power connector, the red wire of
the power connector and the red wire on the FDD data cable come adjacent to each other.

10. Powering the HDD & FDD


 Connect the peripheral power connector from the SMPS to the HDD
 Connect the Floppy power connector from the SMPS to the FDD
 Connect them in such a way that the red wire of the power connector and the red wire of the HDD &
FDD data cables come adjacent to each other.

24
11. Installing the CD ROM drive/ CD Writer drive
 Remove the cover on the front side of the cabinet pertaining to the CD Rom drive
 Push the CD ROM drive into the case from front
 Secure the CD ROM drive into the chasis with Inner screws
 Connect one end of the CD ROM drive data cable to the IDE channel on the Motherboard and the
other end to the CD ROM Drive.
 Connect the cable to the CD ROM drive in such a way that, when we install the power connector, the
red wire of the power connector and the red wire on the data cable come adjacent to each other.
 Connect the power connector from the SMPS to the CD ROM Drive
 Follow the similar steps for Installing the CD Writer Drive

25
12. Installing the LAN card
 Put the LAN card into the desired PCI slot and press it until the pins on the LAN card go into the slot
up to 3/4th of the height
 Fix the LAN card to the chasis with an Inner screw

26
 Connect the front panel connectors to the Motherboard as specified in the Motherboard specifications
manual.
 Fix the peripheral devices such as the keyboard, mouse, monitor etc to the ports
 This completes the assembling of the P-IV computer

27

EXERCISE 1(C): DEMONSTRATING INSTALLATION OF OS AND APPLICATIONS

BASIC FILE SYSTEMS:


FAT: File Allocation Table.
NTFS: New Technology File System.
FAT : Possible to access from a DOS-boot floppy, but limited to max. 4 GByte with very
inefficient file-storage (cluster-size of 64 KByte), no Security features
NTFS : Not accessible from a DOS-boot floppy, but NOT limited in size and using an efficient file-storage with a
small cluster-size, able to use File-System Security features.
INSTALLATION OF MICROSOFT WINDOWS:
1. Keep on press the delete button and go to advanced BIOS feature.
[ BIOS- Basic Input Output System ]
2. And go to boot sequence. Select first boot drivers. CD ROM and press F10 to save the bios feature. Yes and
then enter. Press any key to boot from CD. Press enter to setup windows XP.
3. Insert the Windows XP CD-ROM into your CD-ROM drive.

28
4. Press F8 to accept the Licence Aggrement

5. The screen will now list all existing partitions and un-partitioned space for each hard disk. Use the
cursor/arrow keys to choose where to create the new partition.
6. Press D to delete an existing partition or
7. Press C to create a new partition in un-partitioned space.
8. If you press D to delete an existing partition, you must then press L to confirm that you want to
delete that partition.

29
9. Repeat this process for each of the existing partitions that you want to move (or remove) in order to
create your new partition.
10. When all necessary partitions are deleted, you can then select the remaining un-partitioned space and
then press C to create new partitions.
 Type the size in megabytes (MB) that you want the new partition to be. Then press ENTER.
Alternatively, you can just press ENTER to create the partition using all the available space (i.e. create
the biggest possible partition).
11. If you want to install Windows XP, use the arrow keys to select the partition where you want to install
Windows XP and then press ENTER.
12. To format the partition, use the arrow keys to select the partition where you want to install Windows
XP.
13. Select the NTFS formatting option and press ENTER

30
14. Setup will start formatting the disk and will then start copying files from the CD-ROM to the disk

31
15. The system will then need to reboot

32
16. After the restart, Windows XP starts the first time with the Graphical User Interface

17. Setup will continue to copy files and to install devices

33
18. Personalize your system by setting regional and language settings, entering your name and organization ,
Type your product key, define name and password for the administrator account, set up date and time

34
35
36
19. Setup continues with "Finalizing installation "

20. The system will reboot again :

37
This completes installing Windows XP

EXERCISE 2(A): CREATING A DOCUMENT USING MS WORD

Aim: Write a leave letter to the Principal by using different alignments, correct formats in MS-Word.
Description:
Microsoft word is a powerful text editor which supports different font types, styles, image operations
etc. It is widely used for detailed documentation in various sectors like educational institutes, business
documentation, academic projects etc.
Procedure:
Step 1: Open MS-Word by click on START button; go to All Programs, then select Microsoft Office Word
2007.
Step 2: To open a new document, Click on Office Button then select New - > Blank Document then click
on create option.
Step 3: Then select TEXT AREA, and then write Leave Letter as a heading, Select the text, click on bold

button to make it bold as “LEAVE LETTER”, and change the font size to 16.
Step 4: Then write date and place in a format as follows
DATE: 15/09/2014,
Guntur.

Then Select the text and make it right by clicking on right alignment button
Step 5: Then write To address as follows and select this text and make it left by clicking on left alignment

38
button
To
The Principal,
College of Engineering,
Guntur.
Step 6: Then write Subject according to your letter. And select this text and press tab button for two times. Step
7: Then write the body of the letter according to your letter. And select this text and make it justification

by clicking on justify alignment button


Step 8: Then write “Thanking you Sir,” select this text and make it to center by clicking on center alignment

button
Step 9: Now write the “From address” as
follows Yours Faithfully, xxxxx.

Then make it right by clicking on Right alignment button


Step 10: This is the final step in writing leave letter. In this step, we have to save the letter as “leave
letter.doc” by selecting “Save” option from Office button. Then a prompt window will ask you to write a file
name. Now you have to give the file name and press the save button.

39
OUTPUT:
LEAVE LETTER
D:15/9/2014,
Guntur.
To
The Principal,
College of Engineering,
Guntur.

Sub:Requesting for 5 days leave-Reg

Respected Sir,

I, XXXXX studying B.Tech I year in CSE department in your


college. As I am going to my home on the occasion of devali festival and also to
celebrate my birthday on the next day.So I kindly request you to grant me leave for
5 days i.e.,16/9/2014-20/9/2014.

Thanking You Sir,

Yours Faithfully,
XXXXX,
B.Tech I year,
CSE Branch.

Viva Questions:

1. What is the importance of MS Word?


2. How do you insert the Header and Footer in a word document?
3. How do you set the Font?
4. What is the difference between MS Word and LaTex word document?

40
EXERCISE 2(B): CREATING A DOCUMENT USING LATEX

Description:
It is a“typesetting program” written by Leslie Lamport of MIT. It usesTeX
engine written by Donald E. Knuth. It is designed for producing beautiful books, thesis’s,
papers, articles etc. and the De facto standard for writing academic papers.

What is LaTeX

 A typesetting program written by Leslie Lamport of MIT.


 Pronounced as “Lah- tek or, or Lay tek
 Uses TeX engine written by Donald E. Knuth
 Designed for producing beautiful books, thesises papers, articles...
 De facto standard for writing academic papers
 Current version LaTeX2

Why LaTeX, not MS Word?


 FAST professional output - highest quality
 Platform, version independent (Unix, Win)
 Device independent output (.dvi)
 Pre set standard formats for all types of documents
 Freely available
 Secure- never lose your files, both old and new!
 Concentrate on content , leave the style to LaTeX.
 Source code for large docs comparatively small.

Disadvantages

 Need other software for extensibility.


 Need to access CTAN for modules.
 Complex tables are not easy
 Not WYSIWYG but WYSIWYM !
 Rather steep learning curve need to remember commands
 Encourages structured writing counter intuitive for lay users!
 Not integrated with other MS Office products.

Where to get LaTeX?


Linux: Almost all distributions bundle LaTeX.
Windows packages and frontends.
MikTeX
WinShell/TeXnicCenter/LEd/Texmaker
LyX (for win and Lin as well)

41
LaTeX Skeleton
% my first LaTeX file
\documentclass[options]{class}
\begin{document}

Hello, world!
\end{document}

How To Run LaTeX


Compose/Edit  TeXnicCenter myfile. tex
Compile  LaTeX.tex
View  xdvi myfile. dvi (UNIX)
yap myfile.dvi (Windows)
Dvi  PostScript dvips myfile
View PostScript gv myfile (UNIX)
Use gsview (Windows)

Syntax

Viva Questions:

1. What is the importance of MS Word?


2. How do you insert the Header and Footer in a word document?
3. How do you set the Font?

EXERCISE 3(A): FAMILIARIZING WITH THE USAGE AND APPLICATIONS OF


MS EXCEL USING EXCEL

Description: Microsoft Excel is a spreadsheet program. It features an intuitive interface,


calculation and graphing tools. These tools could be used for business financial analysis
and other administrative tasks.
Open MS-Excel by any of the following ways

Method1: Method2:
1. Click on start button 1. Click on Start button
42
2. Click on programs 2. click run
3. Click on Ms-office 3. type the Excel
4. Click on Excel 4. After click ok button

Work Book: Collection of sheets is nothing but work book.


Work sheet: Collection of cells [1048576 x (XFD)16384 ]
Cells: Combination of rows & columns
Row: Horizontal line [1, 2,3,……]
Column: Vertical line [A, B, C, ……………..]
Cell address: Column name followed by Row name
Ex :( A1, B10, H2, C3…)

New Work Book: (ctrl+N)


1. Click on file menu
2. click on new [It will appears
dialog box]
3. Click on blank work book
4. Default file
name(bok1,book2,
….)
5. Extension Excel file .XLS

Close the Work book: (ctrl+w)


1. Click on the file menu
2. click on close

Save the work Book(Ctrl+s):


1. Click on file menu
2. Click on Save
3. Type the file name
4. Click on save button(Ctrl+l)

43
Default setting Insert the
Rename the
1. Sheets -- 3 work Sheet:
work sheet:
2. Font - Arial
3. Font size - 10 1. Click on the
1. Click on
4. Row Hight- 12.75 insert menu
format menu
5. Column Width- 8.43 2. Click in work
2. Click on the
6. Font Style regular sheet
sheet
7. Font Color- Black Delete the
3. Click on the
8. Text alignment- Left work Sheet:
rename
9. Numbering alignment =- Right alignment 1. Click on the
4. type the sheet
edit menu
name
2. Click on delete
Navigation in spread Sheet
To move the cell pointer to the left row Side -- (left arrow)
To move the cell pointer to the up row Side - (up arrow)
To move the cell pointer to the down t row Side -- (down arrow)
To move the cell pointer to the right row Side (right arrow)
To move the cell pointer to the first column in same row (“HOME”)
To move the cell pointer to the last column in last row (“CTRl+RIGHT ARROW”)) To
move the cell pointer to the first column in same row CTRl+LEFT ARROW”)) To move
the cell pointer to the same row column same row (CTRl+LEFT ARROW”)

Functions:
1. Text functions
2. Date and Time Functions
3. Math functions
4. Logical functions

Mathematical Function:
NAMES SYNTAX SYNATX
SUM =A1+B1+C1 =SUM(A1:E1)
AVERAGE = (A1+B1+C1)/3 =AVERAGE(A1:C1)
MAX =MAX(A1+B1+C10 =MAX(A1:C1)
FACT =FACT(A1) =FACT(B1)
MUTLIFLICATION =A1*B1 =MMULT(A1,B1)

44
Aim: Create a marks sheet for 10 students using EXCEL.
Steps:

1 Open MS-EXCEL by clicking on START Button, go to Programs then click on


Microsoft Office then select Microsoft Office Excel 2007.
2 Write the title name is College of Engineering at (A1 address)
3 Write the sub title name is I.B.Tech CSE MARKS SHEET at (A2 address).
4 Now write the requirements fields for calculation of marks, like
S.No,H.T.No,subjects,Grand Total & Percentage from A3 to O3 cells as follows
E E CP PHY/CHE PC
S.No H.T.No ENG PHY CHE M-1 MM PSUC ED LAB LAB LAB ITWS G.TOT %

5 Write S.no’s from 1-10 in A4 - A13 cell addresses and H.T.No’s from B4- B13.
6 Now enter the marks in C4 – M13 cell addresses.
7 Now in the G.Total cell,select N4 cell and apply the formula for adding the marks
contained in C4 – M4 cell addresses in the formula bar as
fx= C4+D4+E4+F4+G4+H4+I4+J4+K4+L4+M4 then press ENTER key.
8 Select the N4 cell and drag towards down for further students calculations.
9 Now calculate the Percentage.For that select O4 cell and type % calculation formula in
Formula bar as
fx=N4/1000*100
10 Select the O4 cell and drag towards down for further students results.
11 Now the % appears in decimal values,now in order to appear the values as rounded
values,select the O4 cell then right click the mouse button , select Format cells then
Numbers and now make decimal places to 0(zero) then click OK.Now again drag for
other cell values to be rounded.
12 Now for keeping the borders,select cells from A1 – O13 and select All Borders on the
home Menu.
13 Now for saving click on OFFICE button and click on Save and type file name as
“Marks Sheet”,then click OK.

45
OUTPUT:

Viva Questions:

1. What is the importance of MS Excel?


2. How do you insert Formulae in an Excel sheet?
3. How do you filter different text? What are the custom options available in filtering
technique?

EXERCISE 3B): CREATING A PRESENTATION USING MS POWERPOINT

46
Description: Microsoft PowerPoint is a presentation program. It features an intuitive
interface with a wide variety of presentation themes, styles and types. These tool could be used
for paper presentations, conference papers, business seminars etc.

Open Microsoft PowerPoint 2007:


Click on Start button, goto All programs, click on Microsoft Office,select
Microsoft Office Power Point2007.
Creating a New Presentation:
After opening MS PowerPoint 2007, select “Blank Presentation”and click on Create.

Saving your Presentation:


To save your document, simply click on the MS 2007 logo in the top left-hand corner
and the menu bar that you see on your right here will drop down giving you various options,
including saving.
When you save a workbook in MS Excel 2007, it automatically saves with “.pptx”as its
extension.
However, you can also save your presentation so that it’s readable by earlier versions of MS
PowerPoint (97 – 2003) by simply selecting “PowerPoint 97-2003 Presentation”when choosing
what file type to save as (please see the screenshot below).

Inserting a Slide:
To insert a new slide…
–From the Hometab, select “New Slide”
‐As well, you can right‐click between any 2 slides in the preview frame located on the left‐
hand side of the Normal view and select “New Slide”
Deleting a Slide:
To delete a slide…
–Select the slide you’d like to delete (eg. by highlighting it) and selecting “Delete “from
the Hometab –As well, you can right-click on any slide in the preview frame located on the
left-hand side of the Normal view and select “Delete Slide”
Inserting Pictures:
To insert pictures…
–From the Inserttab you can insert pictures from your computer, clip art, shapes, etc…
–Also, when you have a blank slide (or parts of a blank slide), you can also click on
options within these blank compartments to insert pictures.

47
Inserting Charts:
To insert charts…
–From the Inserttab you can insert pictures from your computer, clip art, shapes, etc…
–Also, when you have a blank slide (or parts of a blank slide), you can also click on options
within these blank compartments to insert charts
•Once you’ve selected to insert a chart, it will ask you choose what kind of chart you’d like to
insert.
•After you’ve picked a type, the screen will split in half with the chart on one side and an excel
spreadsheet on the other
–To modify the chart, make changes in the data presented in the spreadsheet
– Charts from Excel can also be copied and pasted into PowerPoint
Inserting Tables:
To insert a table…
–From the Insert tab, select “Table “and a box will drop down giving you more options for
inserting a table. –Also, when you have a blank slide (or parts of a blank slide), you can also
click on options w/n these blank compartments to insert tables

•Normal viewis the default view


•Slide Sorter displays all the slides in consecutive order as thumbnails.
•Notes Page is similar to the normal view except the slides are reduced in size and
located in the upper portion of the screen with the lower portion of the screen
being allocated for adding notes to the slide.
•Slide show is the presentation where the slides are enlarged to fit the entire screen.
Animations
•All sorts Animation Effects can be added to your slides and the best way to find out
what works best for your presentation is to play around and experiment with all the
different options.
•But first, a cautionary note. Many bad presentations will overly rely on animations (and other
stylistic effects) to keep the audience interested (probably because the presentation itself was
less than riveting). The best presentations are the ones that effectively use animations as an aid
in presenting information, rather than distracting from it. In short, a good rule of thumb to
remember would be “Less is more.”
•Animating objects on a slide…
1. Go to the Animations tab.
2. Select/Highlight an object on the slide (this could be the title, the main body of text, a
textbox, a picture, a shape, a chart, a table, a bullet point, etc…
3. Click on “Custom Animation”

48
OUTPUT

Viva Questions:

1. What is the importance of MS Powerpoint?


2. How do you insert figures in a powerpoint slide?
3. What is the difference between MS Word and Powerpoint in presentation?

EXERCISE 4: FAMILIARIZING WITH THE INTEGRATED DEVELOPMENT


ENVIRONMENT (IDE) FOR DEVELOPING C PROGRAMS
Description:

49
An integrated development environment (IDE) is a programming environment that has
been packaged as an application program, typically consisting of a code editor, a compiler, a
debugger and a graphical user interface (GUI) builder. The IDE may be a stand-alone
application or may be included as part of one or more existing and compatible applications
Turbo C Integrated Development Environment
IDE is nothing but Integrated Development Environment in which one can develop, run, test
and debug the application. The Turbo C IDE appears as shown in figure.

The C Developing Environment is a screen display with windows and pull-down menus. The
program listing, error messages and other information are displayed in separate windows. The
menus may be used to invoke all the operations necessary to develop the program, including
editing, compiling, linking, and debugging and program execution. If the menu bar is inactive,
it may be invoked by pressing the [F10] function key. To select different menu, move the
highlight left or right with cursor (arrow) keys. You can also revoke the selection by pressing
the key combination for the specific menu.
Invoking the Turbo C IDE
The default directory of Turbo C compiler is c:\tc\bin. So to invoke the IDE from the windows
you need to double click the TC icon in the directory c:\tc\bin.
The alternate approach is that we can make a shortcut of tc.exe on the desktop.
Opening New Window in Turbo C
To type a program, you need to open an Edit Window. For this, open file menu and click
“new”. A window will appear on the screen where the program may be typed.
Writing a Program in Turbo C
When the Edit window is active, the program may be typed. Use the certain key combinations
to
perform specific edit functions.
Saving a Program in Turbo C
To save the program, select save command from the file menu. This function can also be
performed by pressing the [F2] button. A dialog box will appear asking for the path and name
of the file.
Provide an appropriate and unique file name. You can save the program after compiling too but
saving it before compilation is more appropriate.
Making an Executable File in Turbo C
The source file is required to be turned into an executable file. This is called “Making” of the
.exe file.

50
The steps required to create an executable file are:
1. Create a source file, with a .c extension.
2. Compile the source code into a file with the .obj extension.
3. Link your .obj file with any needed libraries to produce an executable program
All the above steps can be done by using Run option from the menu bar or using key
combination
Ctrl+F9 (By this linking & compiling is done in one step).
Compiling and linking in the Turbo C IDE
In the Turbo C IDE, compiling and linking can be performed together in one step. There
are two ways to do this: you can select Make EXE from the compile menu, or you can press the
[F9] key
Correcting Errors in Turbo C
If the compiler recognizes some error, it will let you know through the Compiler window.
You’ll see that the number of errors is not listed as 0, and the word “Error” appears instead of
the word“Success” at the bottom of the window. The errors are to be removed by returning to
the edit window.
Usually these errors are a result of a typing mistake. The compiler will not only tell you what
you did wrong, they’ll point you to the exact place in your code where you made the mistake.
Executing a Programs in Turbo C
If the program is compiled and linked without errors, the program is executed by selecting Run
from the Run Menu or by pressing the [Ctrl+F9] key combination.
Exiting Turbo C IDE
An Edit window may be closed in a number of different ways. You can click on the
small square in the upper left corner, you can select close from the window menu, or you can
press the Alt+F3 combination. To exit from the IDE, select Exit from the File Menu or press
Alt+X Combination

Viva Questions:

1. How a linker does help in compilation of C programs?


2. How does a debugger help in improving the quality of the software?

PART- B

5 a) Write a C program to calculate the area of triangle using the formula area
A= (s (s-a) (s-b)(s-c))1/2 where s= (a+b+c)/2

Description: The area of a triangle depends on the size of all the three sides of the triangle. We
use the mathematical function “sqrt” for performing the square root operation using the
mathematical header file <math.h>

51
Algorithm
1. Start.
2. Read three sides of a triangle a,b,c.
3. Calculate s= (a+b+c)/2.
4. Display Area=sqrt(s*(s-a)*(s-b)*(s-c)).
5. Display area of triangle.
6. Stop.
Flowchart

start

Read three sides


of a triangle a,b,c

calculate s= (a+b+c)/2

Display Area=sqrt(s*(s-a)*(s-b)*(s-c))

Display area of
triangle Area

Stop

Program

#include<stdio.h>
#include<math.h>
int main()
{
float a,b,c;

52
float s,area;
clrscr();
printf("Enter size of each sides of triangle");
scanf("%f%f%f",&a,&b,&c);
s = (a+b+c)/2;
area = sqrt(s*(s-a)*(s-b)*(s-c));
printf("Area of triangle is: %.3f",area);
return 0;
}

Output
1. Enter size of each sides of triangle 4.5 2.5 5
Area of triangle is: 5.612
2. Enter size of each sides of triangle 5 6 3
Area of triangle is: 7.483

Viva questions:

1) Name any four mathematical operations supported by <math.h> file?


2) How do you calculate the perimeter of a triangle?
3) What is the difference between the output format %f and %.3f?
4) What is a pre-processor directive?

5 b) Find the largest of three numbers using ternary operator.

Description: A ternary operator is a special operator that can check for two conditions in a
single statement. If the condition is true, a sequence of instructions is executed. Else, another
sequence is executed.

Algorithm
1. Start.
2. Read three numbers a,b,c .
3. If a>b goto step 3.1 otherwise goto step 4
3.1. If a>c goto step 3.2 otherwise goto step 3.3
3.2. Display a is largest of three numbers ,goto step 5
53
3.3. Display c is largest of three numbers ,goto step 5
4. If b>c goto step 4.1 otherwise goto bstep 4.2
4.1. Display b is largest of three numbers goto step 5
4.2. Display c is largest of three numbers
5. Stop.

Flowchart
start

Read three numbers a,b,c .

T F
a>b
?

T T F
a>c b>c
F
? ?

Display a is Display c is Display b is Display c is


largest of largest of largest of largest of
three three three three
numbers. numbers. numbers. numbers.

Stop

Program
#include<stdio.h>
int main()
{
int a,b,c,big;
clrscr();
printf("\nEnter 3 numbers:");
scanf("%d %d %d",&a,&b,&c);
big=a>b?a>c?a:c:b>c?b:c;
54
printf("\nThe biggest number is: %d",big);
return 0;
}
Output
1. Enter 3 numbers:345 29 2
The biggest number is: 345
2. Enter 3 numbers: 8 10 9
The biggest number is: 10

Viva questions:

1) <conio.h> file is used to support which operations?


2) How the ternary operator is different from others?
3) What are relational operators?
4) If possible, specify the same program logic without using ternary operator?

5 c) Find the roots of a quadratic equation.

Description:

Nature of roots of quadratic equation can be known from the determinant d = b2-4ac
if b2-4ac >0 then roots are real and unequal
if b2-4ac =0 then roots are real and equal
if b2-4ac <0 then roots are imaginary

Algorithm:

Step 1: start
Step 2: read the a,b,c value
Step 3: assign pow((b*b-4*a*c),0.5) value to d
Step 4: if d==0 compute r1=-b/(2*a) , r2=-b/(2*a) go to step 7 otherwise go to step5
Step 5: if d<0 print roots are imaginary and compute real and imaginary parts for r1 and r2
goto step 8 otherwise go to step 6
55
Step 6: compute r1 = ((-b+d) / (2*a)) r2 = ((-b-d) / (2*a)) go to step 7
Step 7: print r1, r2
Step 8: stop

Flowchart:

Start

Read a,b,c

d = pow((b*b-4*a*c),0.5)

F T
d= = 0 d< 0

T F
r1 = ((-b+d) / (2*a)) Display
r1=r2= r2 = ((-b-d) / (2*a)) roots are
-b / (2 * a ) imaginary
r2= -b / (2 *
a)

Display
r1, r2

Stop

56
Program:

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,b,c;
double r1,r2,d;
clrscr();
printf("Enter the values of a,b,c:");
scanf("%d%d%d",&a,&b,&c);
d=((b*b)-(4*a*c));
if(d==0)
{
r1=r2=(-b/(2*a));
printf("Roots are Equal:%lf,%lf",r1,r2);
}
else if(d<0)
printf("Roots are Imaginary");
else
{
r1=(-b+sqrt(d))/(2*a);
r2=(-b-sqrt(d))/(2*a);
printf("Roots are:%lf,%lf",r1,r2);
}
getch();
}

Output:

Enter the values of a,b,c:1 6 9


Roots are Equal:-3.000000,-3.000000

Enter the values of a,b,c:2 7 6


Roots are:-6.750000,-7.250000

Enter the values of a,b,c:1 2 3


Roots are Imaginary

Viva Questions:
1) What are various types of loop statements?
2) What is the difference between while and do-while statements?
3) List out the C features?

57
Exercise 6 :

6 a) Write a c program to read two integer operands and one operator from the user,
perform the operation and then print the result. (Consider the operators +,-,*, /, % and
use Switch Statement)

Description:
Take two integer operands and one operator from user and perform some arithmetic operations
by using the following operators like +,-,*, /, %
Ex: 2+3=5

Algorithm:

Step 1: Start

Step 2: Read the values of op1,op2 and operator op

Step 3: if the operator is ‘+’ then


Print op1+op2 go to step 4
if the operator is ‘-‘ then
Print op1-op2 go to step 4
if the operator is ‘*‘ then
Print op1*op2 go to step 4
if the operator is ‘/‘ then
Print op1/op2 go to step 4
if the operator is ‘%‘ then
Print op1%op2 go to step 4
if operator is not in the above list
print “Invalid arithmetic operator”
Step 4: stop

Flowchart:
58
start

Read op1,op2 and


opeartor

op?
‘-’
‘+’ ‘*‘ ‘/’ ‘%’
displa display a- display display display a display
y a+b b value a*b value a/b value %b value “Invalid
value operator”

start

Program:

#include<stdio.h>
#include<conio.h>
void main()
{
int op1,op2;
char op;
clrscr();
printf("\nOperations Performed are: + - * / %");
printf("\nEnter 2 Integers & an Operator:");
scanf("%d %d %c",&op1,&op2,&op);
switch(op)
{
case '+': printf("ADDITION -- Sum is %d",op1+op2);
break;
case '-': printf("SUBTRACTION -- Difference is %d",op1-op2);
break;
case '*': printf("MULTIPLICATION -- Product is %d",op1*op2);
break;
case '/': printf("DIVISION -- Quotient is %d",op1/op2);
break;
case '%': printf("MODULUS -- Remainder is %d",op1%op2);
break;
default: printf("Invalid operation");
break;
}
getch();
}

59
Output:

Operations Performed are: + - * / %


Enter 2 Integers & an Operator:2
4
*
MULTIPLICATION -- Product is 8

Operations Performed are: + - * / %


Enter 2 Integers & an Operator:2
4
+
ADDITION -- Sum is 6

Operations Performed are: + - * / %


Enter 2 Integers & an Operator:2 4 -
SUBTRACTION -- Difference is -2

Operations Performed are: + - * / %


Enter 2 Integers & an Operator:2
4
/
DIVISION -- Quotient is 0

Operations Performed are: + - * / %


Enter 2 Integers & an Operator:2
4
%
MODULUS -- Remainder is 2

VIVA QUESTIONS:

1) What are the various types of arithmetic operators?


2) What are the types of relational operators?
3) What are the types of logical operators?
4) How do you implement a switch statement?

6 b) Write a C program to check whether given number is Prime (or) not

Description:

60
A prime number is the one which has only the factors 1 and itself. We check for the
total number of factors for the given number. If the given number has only two factors, it’s a
prime number. Else, it’s not a prime number.

Algorithm:
Step 1: Start
Step 2: initialize c=0
Step 3: Read input ‘n’ from user
Step 4: initialize i=1
Step 5: check whether n%i==0 if true increment c
Step 6: increment i
Step 7: repeat steps 4 and 5 until n>i
Step 8:check c=2 if true print number is prime
Step 9: else print number not prime
Step 10: stop

Flowchart:
START
61 c=
i<=n
=2
READ INPUT ? Number is prime
Number is not prime ? ‘n’
Increment
FROM USERcount
Increment STOP
Initialize i=1i
c
F

F If(n
%i=0
)

Program

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

62
int c=0,n,i;
printf("enter a number");
scanf("%d",&n);
i=1;
do
{
if(n%i==0)
c++;
}while(i<=n);
if(c==2)
printf("given number %d is prime",n);
else
printf("given number %d is not prime",n);
getch();
}

Output
1. enter a number21
given number 21 is not prime

2. enter a number251
given number 251 is prime

Viva Questions:
1) What is a composite number?
2) How does a for loop work?
3) State the skeleton for simple if-else statement?
4) What is meant by access specifier?

63
6 c) Write a C program to display first N natural numbers.
Description:
A natural number is a number that occurs commonly and obviously in nature. As such,
it is a whole, non-negative number. The set of natural numbers, denoted N, can be defined in
either of two ways: N = {0, 1, 2, 3,}

Algorithm

1. Start.
2. Read the value of n.
3. Initialize the variable i=1.
4. Repeat.
4.1. Display i value.
4.2. i is incremented by 1 in each case
Until the condition is failed i.e. i<=n.
5. stop.

Flowchart

start

Read range value (n)

i=1

F
i<=
n
T

Display i value

i+=1

Stop

64
Program
#include<stdio.h>
int main()
{
int i,n;
clrscr();
printf("\n Enter range of natural numbers ");
scanf("%d",&n);
i=1;
while(i<=n)
{
printf("%d\t", i);
i++;
}
return 0;
}
Output
1. Enter range of natural numbers 10
1 2 3 4 5 6 7 8 9 10
2. Enter range of natural numbers 5
1 2 3 4 5

Viva Questions:
1) What is a natural number?
2) Any program execution in C language starts from which function?
3) How does the printf and scanf functions work?

65
6 d) Write a C program to calculate electricity bill for the consumed units – assume
suitable constraints.

Description: The current bill is generated on the amount of units consumed in a


monthly basis. For this purpose, we are implementing a nested else-if ladder.

Calculating electricity bill based on the following unit price


1 to 200 Units 0.50 Rs
200 to 400 Units 0.60 Rs
400 to 600 Units 0.80Rs
Greater than 600 Units 1.0 Rs

Algorithm
Step 1: Start
Step 2: Read the no. of units(U)
Step 3: if the units(U) are less than or equal to 200 then
calculate bill =U*0.50 and goto step 7
Step 4: Otherwise check the units(U) are less than or equal to 400 then
Calculate bill =100+(U-200)*0.60 and goto step 7
Step 5: Otherwise check the units(U) are less than or equal to 600 then
Calculate bill =220+(U-400)*0.80 and goto step 7
Step 6: Otherwise
Calculate bill =380+(U-600)*1.00 and goto step 7
Step 7: Display bill
Step 8: Stop

Flowchart:
start

Read no of units

66
Units< F
T =200

T Units
bill =U*0.50 <=400

bill =100+(U-200)*0.60 T F
Units
<=600

bill =220+(U-400)*0.80 bill =380+(U-600)*1.00

Display bill

stop

Program:

main()
{
float u,amt;
printf("Enter no of units\n");
scanf("%f",&u);
if(u<=200)
amt=u*0.5;
else if(u<=400)
amt=100+(u-200)*.6;
else if(u<=600)
amt=220+(u-400)*.8;
else
amt=380+(u-600)*1.00;
printf("Amount for %.0f units is %.2f",u,amt);
getch();
}
Output:

1) Enter no of units 250


Amount for 250 units is 130.00

2) Enter no of units 1000


Amount for 1000 units is 780.00

67
Viva questions:

1) What is the difference between simple-if and nested-if ladder?


2) What are the differences between floating point and integer data types?
3) Define a control statement

6 e) Write a c program to find the sum of individual digits of a positive integer and find
reverse of the given number.

Description: Sum of the individual digits means adding all the digits of a number
Ex: 123, the sum of digits is 1+2+3=6

Algorithm:
Step 1: start
Step 2: initialize the sum=0
Step 3: read number n
Step 4: if n!=0 go to Step 6 else go to step 7
Step 5: store n%10 value in rem
Add rem value to sum
Calculate rev=rev*10+rem
Assign n/10 value to n
Go to Step 4
Step 6: print sum
Step 7: print rev
Step 8: stop

Flowchart:
start

sum=0

read number n
68
F
n!=0
T

rem=n%10

Sum=sum+rem

rev=rev*10+rem

n=n/10;

Print sum

Print rev

stop

Program:

main()
{
int n,rem,rev=0,sum=0;
printf("\n Enter number");
scanf("%d",&n);
while(n!=0)

69
{
rem=n%10;
sum=sum+rem;
rev=rev*10+rem;
n=n/10;
}
printf("\n Sum=%d",sum);
printf("\n Rev=%d",rev);
}
Output:
1)
Enter number1234

Sum=10
Rev=4321

2)
Enter number567
Sum=18
Rev=765

VIVA QUESTIONS:

1) What is the mean of sum of the individual digits?


2) What is positive integer?
3) Define preprocessor?

7 a) Write a C program to find both the largest and smallest number in a list of integers

Description:

This program contains n number of elements, in these elements we can find and diplay
the largest and smallest numbers.

Algorithm:
Step 1: start
Step 2: read n
Step 3: initialize i=0

70
Step 4: if i<n do as follows. If not goto step 5
Read a[i]
Increment i
Goto step 4
Step 5: min=a[0], max=a[0]
Step 6: initialize i=0
Step 7: if i<n do as follows. If not goto step 8
If a[i]<min
Assign min=a[i]
Increment i goto Step 7
Step 8: print min,max
Step 9: stop

71
Flowchart:
Start

Read n

i= 0
false i<n i++

true

Read a[i]

min = a[0]
max = a[0]

i=0 i++
false
i< n
true
false true
if a[i]<
min

min=a[i]
a[i]>max
true

max=a[i]

Print min,
max

stop

72
Program:

main()
{
int a[20],i,n,max,min;
clrscr();
printf("Enter size\n");
scanf("%d",&n);
printf("\n Enter %d elements",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
max=min=a[0];
for(i=1;i<n;i++)
{
if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
printf("\n Max=%d",max);
printf("\n Min=%d",min);
}

Output:

1) Enter size 5
Enter 5 elements5
23
12
7
1
Max=23
Min=1

2) Enter size 9
Enter 9 elements12
356
145
897
210
23
54
65
89

Max=897
Min=12

VIVA QUESTIONS:

73
1) What is an array?
2) How many types of arrays are there?
3) What is the use of getch() function?
4) What are the advantages of implementing an array?

74
7 b) Write a c program to Search whether the given element is in the array(Linear search)

Description: We declare a one-dimensional array of some elements. In order to search


whether the given element is present in an array or not, we begin from the zero th position of
that array. We traverse throughout the array until the entire list is searched or the
corresponding element is found.

Algorithm

1. Start.
2. Read number of elements in an array (n)
3. Read n array elements
4. Read search key
5. Initialize i=0
6. If i<n do as follows if not goto step 7
6.1. check if array element equal to key then goto step 6.2 otherwise goto 6.3
6.2. Display search key is available in the array ,goto step 8
6.3. Increment i
7. if i=n display key is not found
8. Stop

Flowchart

75
start

Read number of
elements in an array (n)

Initialize i=0

i<n
?
?
T F
Read array elements
a[i]

i++

Read search key


k

i<n
i=0
i+
+
F T F

a[i]=
=k
T
key is available

F i==
n?
? T
key is not found

Stop

Program:

main()
76
{
int a[20],i,n,key;
clrscr();
printf("Enter no of elements\n");
scanf("%d",&n);
printf("Enter %d elements",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter key");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(a[i]==key)
{
printf("element is found at %d th location",i);
break;
}
}
if(i==n)
printf("key not found");

Output:

1) Enter no of elements 5
Enter 5 elements5
4
3
2
1
Enter key2
element is found at 3 th location

2) Enter no of elements 8
Enter 8 elements14 2 54 896 47 25 14 7
Enter key100
key not found

Viva Questions:
1) How an array is efficient in storing and organizing of data?
2) If the total elements of an array are n, then the maximum possible value of index is?
Why?
3) How the search operation does takes place in an array?
7 c i) Write a c program to perform the addition of two matrices

Description:A matrix is a collection of numbers arranged into a fixed


number of rows and columns. Usually the numbers are real numbers. In

77
general, matrices can contain complex numbers but we won't see those
here. Here is an example of a matrix with three rows and three columns:

The format is : rows X columns. We perform addition operations on a


matrix by checking for compatibility conditions

Algorithm:

Step 1: start
Step 2: read the size of matrices A,B – m,n
Step 3: read the elements of matrix A
Step 4: read the elements of matrix B
Step 5: perform the addition operation place the result in C matrix
Step 6: print the elements of matrix C
Step 7: Stop

78
Flowchart:
start

Read number of rows r1


and number of columns c1
of matrix 1

Read number of rows r2


and number of columns c2
of matrix 2

If r1!=r2 T
and c1!
=c2
F
Display invalid
Read matrices A and B order of
matrices

F i=0 i++
i<r1

j=0 j<c1 F
j++

c[i][j]=a[i][j]+b[i][j];

Print result matrix

stop

79
Program:

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10];
int r1,c1,r2,c2,i,j,k;
clrscr();
printf("Enter Number of rows & columns for Matrix1:");
scanf("%d %d",&r1,&c1);
printf("Enter Number of rows & columns for Matrix2:");
scanf("%d %d",&r2,&c2);
if(r1==r2 && c1==c2)
{
printf("Enter elements for Mat1:");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);
}
printf("Enter elements for Mat2:");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
scanf("%d",&b[i][j]);
}
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c1;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("%d\t",c[i][j]);
}
}
}
else
printf("Matrix addition is not possible");
getch();

Output:

80
1)
Enter Number of rows & columns for Matrix1:2
2
Enter Number of rows & columns for Matrix2:2
2
Enter elements for Mat1:2
2
2
2
Enter elements for Mat2:2
2
2
2

4 4
4 4

2)
Enter Number of rows & columns for Matrix1:2
3
Enter Number of rows & columns for Matrix2:3
2
Matrix addition is not possible

7 c ii) Write a c program to perform the subtraction of two matrices

81
Description:A matrix is a collection of numbers arranged into a fixed
number of rows and columns. Usually the numbers are real numbers. In
general, matrices can contain complex numbers but we won't see those
here. Here is an example of a matrix with three rows and three columns:

The format is : rows X columns. We perform subtraction operations on a


matrix by checking for compatibility conditions

Algorithm:

Step 1: start
Step 2: read the size of matrices A,B – m,n
Step 3: read the elements of matrix A
Step 4: read the elements of matrix B
Step 5: perform the subtraction operation place the result in C matrix
Step 6: print the elements of matrix C
Step 7: Stop

82
Flowchart:
start

Read number of rows r1


and number of columns c1
of matrix 1

Read number of rows r2


and number of columns c2
of matrix 2

If r1!=r2 T
and c1!
=c2
F
Display invalid
Read matrices A and B order of
matrices

F i=0 i++
i<r1

j=0 j<c1 F
j++

c[i][j]=a[i][j]-b[i][j];

Print result matrix

stop

83
Program:

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10];
int r1,c1,r2,c2,i,j,k;
clrscr();
printf("Enter Number of rows & columns for Matrix1:");
scanf("%d %d",&r1,&c1);
printf("Enter Number of rows & columns for Matrix2:");
scanf("%d %d",&r2,&c2);
if(r1==r2 && c1==c2)
{
printf("Enter elements for Mat1:");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);
}
printf("Enter elements for Mat2:");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
scanf("%d",&b[i][j]);
}
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c1;j++)
{
c[i][j]=a[i][j]-b[i][j];
printf("%d\t",c[i][j]);
}
}
}
else
printf("Matrix subtraction is not possible");
getch();

84
Output:
1)
Enter Number of rows & columns for Matrix1:2
2
Enter Number of rows & columns for Matrix2:2
2
Enter elements for Mat1:2
2
2
2
Enter elements for Mat2:2
2
2
2

0 0
0 0

2)
Enter Number of rows & columns for Matrix1:2
3
Enter Number of rows & columns for Matrix2:3
2
Matrix subtraction is not possible

7 c iii) Write a c program to perform the multiplication of two matrices

85
Description:A matrix is a collection of numbers arranged into a fixed
number of rows and columns. Usually the numbers are real numbers. In
general, matrices can contain complex numbers but we won't see those
here. Here is an example of a matrix with three rows and three columns:

The format is : rows X columns. We perform multiplication operations on


a matrix by checking for compatibility conditions

Algorithm:
Step 1: start
Step 2: read the size of matrices A,B
Step 3: check compatibility of matrices for multiplication i.e, number of columns
in the first matrix should be equal to number of rows in the second matrix.
Step 4: read the elements of matrix A
Step 5: read the elements of matrix B
Step 6: perform the multiplication operation by storing the resulting values into
matrix C.
Step 7: print the resultant matrix C.
Step 8: Stop

86
Flowchart :
start

Read number of rows r1


and number of columns c1
of matrix A

Read number of rows r2


and number of columns c2
of matrix B

If c1! T
=r2 F
Read matrices A and B

Display invalid
i=0 i++ order of
i<r1 matrices
F

j=0 j<c2
j++

c[i][j]=0
F
k=0 k<c1
k++

T
c[i][j]=c[i][j]+(a[i][k]*b[k]
[j])

Print result matrix

stop

87

T F
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10];
int r1,c1,r2,c2,i,j,k;
clrscr();
printf("Enter Number of rows & columns for Matrix1:");
scanf("%d %d",&r1,&c1);
printf("Enter Number of rows & columns for Matrix2:");
scanf("%d %d",&r2,&c2);
if(c1==r2)
{
printf("Enter elements for Mat1:");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);
}
printf("Enter elements for Mat2:");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
scanf("%d",&b[i][j]);
}
printf("result");
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c2;j++)
{
c[i][j]=0;
for(k=0;k<c1;k++)
c[i][j]+=a[i][k]*b[k][j];
printf("%d\t",c[i][j]);
}
}
}
else
printf("\n Matrix multiplication is not possible");
getch();

Output:

88
1)
Enter Number of rows & columns for Matrix1:2
3
Enter Number of rows & columns for Matrix2:3
2
Enter elements for Mat1:2
2
2
2
2
2
Enter elements for Mat2:2
2
2
2
2
22
result
12 12
12 12

2)
Enter Number of rows & columns for Matrix1:2
3
Enter Number of rows & columns for Matrix2:2
2

Matrix multiplication is not possible

VIVA QUESTIONS:
1) What is a matrix? How are they useful in representing data?
2) What is condition for performing matrix addition?

3) We have two matrices A of order 3*3, B of order 2*2. Can we perform multiplication
operation? Justify.

7 d) Write a c program to delete n Characters from a given position in a given string.

Description:
89
A string is a sequence of zero or more characters followed by a NULL '\0' character
(end of the string).All the string handling functions are prototyped in: string.h or stdio.h
standard header file. String constants have double quote marks around them.We use the
functions strlen, strcpy for obtaining the length of the string and copying string values
respectively.

Algorithm:
Step 1: start
Step 2: read string
Step 3: read the number of characters to be deleted and from which position we
have to delete
Step 4: copy string from position +number of characters to end
Step 5:
stop
Flow chart: Start

Read string(a)

Read position, no of
characters

delchar( a, n, pos)

Stop

delchar( char a[],int


n,int pos)

i=pos,j=pos+n i++,j++
if ((a+b-1)<=
strlen(x))
a[j]!=’\0’

a[i]=a[j];

a[i]=’\0’

Return to main
main program

90
Program:
#include <stdio.h>
#include <conio.h>
#include <string.h>
void delchar(char x[],int a,int b);
void main()
{
char string[10];
int n,pos,p;
clrscr();
puts("Enter the string");
gets(string);
printf("Enter the position from where to delete");
scanf("%d",&pos);
printf("Enter the number of characters to be deleted");
scanf("%d",&n);
delchar(string,n,pos);
getch();
}
void delchar(char x[],int n,int pos)
{
int i,j;
for(i=pos,j=pos+n;x[j]!='\0';i++,j++)
x[i]=x[j];
x[i]='\0';
printf("\n the string is deleted,now the string is:");
puts(x);
}
Output:

1) Enter the string gudlavalleru


Enter the position from where to delete2
Enter the number of characters to be deleted3
the string is deleted,now the string is:guvalleru

2)Enter the string geccse


Enter the position from where to delete1
Enter the number of characters to be deleted1
the string is deleted,now the string is:gccse

VIVA QUESTIONS:
1) What is meant by apalindrome ?
2) What is the use of gets() function ?
3) What is the use of puts() function ?
4) What is the syntax for performing String Copy operation?
5) What will happen if the amount of memory is not sufficient while implementing
strcpy() function?
6) Can we use strrev() function for Palindrome verification? Justify.

91
7)

7e) Write a c program to illustrate at least five string handling functions.

Description:

Apply some of the predefined functions on given strings. These are included in string.h header
file.

Algorithm

Step 1 : start
Step 2: read s1,s2,s3
Step 3: compute l1= strlen(s1)
Step 4 : print l1
Step 5 : compute s=strcpy(s3,s1)
Step 6 : print s
Step7: compute e= strcmp(s1,s2)
Step 7 : if e==0 go to step 8 otherwise go to step 9
Step 8 : display “strings are equal”
Step 9 : display “Strings are not equal “
Step 10 : display “reverse of 1st string is “, strrev(s1)
Step 11 : display “after concatenation of two strings s1 and s2 is “ strcat(s1,s2)
Step 12 : stop

92
Flowchart:
start

Read strings
s1,s2,s3

l1=strlen(s1)

Display l1

s=strcpy(s3,s1)

Display s

e=strcmp(s1,s2)

r=strrev(s1) c=strcat(s1,s2)
false
If
e==0

true

Display s1,s2 are Display s1,s2 are


equal not equal Display r Display c

stop

93
Program

#include<string.h>
#include<stdlib.h>
void main()
{
char s1[25],s2[25],s3[25];
int l1,l2,e;
clrscr();
printf("\n Enter three strings ");
gets(s1);
gets(s2);
gets(s3);
l1 = strlen(s1);
printf("\n length of s1 is %d ",l1);
printf("\n After copying 1st string into 3rd string is %s",strcpy(s3,s1));
e=strcmp(s1,s2);
if(e==0)
printf("\n The two strings s1 and s2 are equal ");
else
printf("\n The two Strings s1 and s2 are not equal ");
printf("\n Reverse of first string is %s ",strrev(s1));
printf("\n After adding first two strings %s",strcat(s1,s2));
getch();
}
Output:
1)
Enter three strings sagf
gec
gudlavalleru

length of s1 is 4
After copying 1st string into 3rd string is sagf
The two Strings s1 and s2 are not equal
Reverse of first string is fgas
After adding first two strings fgasgec
2)
Enter three strings gec
gec
gudlavalleru
length of s1 is 3
After copying 1st string into 3rd string is gec
The two strings s1 and s2 are equal
Reverse of first string is ceg
After adding first two strings ceggec

94
VIVA QUESATIONS:

1) What is a string?
2) Which command is used to combine two strings?
3) Which command is used to copy the strings?
4) Which header file/s is used to implement string functions?
5) What is the difference between a character and a string?
6) What is a sub-string?
7) What do the functions gets(),puts() do?

8 a) Write a C program to calculate mean, standard deviation and variance for a given set
95
of values using functions
Description:

This C Program calculates the mean, variance & standard deviation. The formula which is used
in this program are
mean = average of the numbers.
variance = (summation ( ( Xi – average of numbers) * ( Xi – average of numbers)) ) Where i =
1 to N here N is the total no of elements.
Standard deviation = Square root of the variance.

Algorithm

1. Start.
2. Read number of elements in an array (n)
3. Read n elements in the array
4. Call the sub program mean(a,n)
5. Stop

Sub program mean(int a[],int n)

1. Start
2. Initialize sum=0,t=0
3. if i<n then goto step 3.1 otherwise goto step 4
3.1 compute sum=sum+a[i]
4. compute m=sum/n and display m value
5. Call the sub program var(a,n,m)
6. End of subprogram

Sub program var(int a[],int n,int m)

1. Start
2. if i<n then goto step 2.1 otherwise goto step 3

2.1 compute t=t+pow((a[i]-m),2)


3. display v
4. Call the sub program sd(v)
5. End of subprogram
Sub program sd(int v)

1. Start
2. compute s=sqrt(v)
3. display s value
4. end of sub program.

96
Flowchart
start

Read number of
elements in an array (n)

Read array elements


a[i]

mean(a,n)

stop

sub program mean


void mean(int a[],int n)

Sum=0,t=0

F
i=0 i<n

i+
+
T

sum=sum+a[i]

m=sum/n

Display m value

var(a, n, m)

97
sub program var

void var(int a[],int n,int m)

F
i=0
i<n
i++

v=v+pow((a[i]-m),2)

Display v value

sd( v)

Sub program sd

void sd(int v)

Sd=sqrt(v)

Display s value

Program:

#include<math.h>
void mean(int a[],int);
void sd(int);

98
void var(int a[],int,int);
main()
{
int a[20],i,n,max,min;
printf("Enter size\n");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mean(a,n);
}
void mean(int a[],int n)
{
int i,sum=0,mean;
for(i=0;i<n;i++)
sum+=a[i];
mean=sum/n;
printf("mean result is %d",mean);
var(a,n,mean);
}
void var(int a[],int n,int m)
{
int i,varres=0;
for(i=0;i<n;i++)
varres+=pow((a[i]-m),2);
printf("var resulkt is %d",varres);
sd(varres);

}
void sd(int v)
{
float sdres;
sdres=sqrt(v);
printf("sd=%f",sdres);
}

Output:

1)
Enter size
5

Enter 5 elements10
20
30
40
50
mean result is 30
var resulkt is 1000
sd=31.622776

2)

99
Enter size
7

Enter 7 elements1 3 5 2 7 6 8
mean result is 4
var resulkt is 44
sd=6.633250

VIVA QUESTIONS:

1) What is a Mean?
2) What is a Standard deviation?
3) What is a Variance?

8 b) Write a C program to arrange the given numbers in the ascending order

Description:

This programs sorts the given set of integers in ascending order. It takes the help of a
temporary variable for storing intermediate values.
Algorithm:

100
Step1: Start
Step2: Read n
Step3: initialize i=0
Step4: if i<n go to step5, otherwise go to step6
Step5: Read a[i], go to step4
Step6: initialize i=0
Step7: if i<n go to step8, otherwise go to step13
Step8: initialize j=0
Step9: if j<n go to step10, otherwise go to step12
Step10: if a[j]>a[j+1], otherwise go to step 11
i) temp=a[j];
ii) a[j]=a[j+1];
iii) a[j+1]=temp; go to step11
Step11: increment j, go to step9
Step12: increment i, go to step7
Step13: initialize i=0
Step14: if i<n go to step15, otherwise go to step16
Step15: Print a[i], go to step14
Step16: Stop

101
Flowchart:

Start

Read n

i=0 i++
false
i<n
true

Read a[i]

i=1 i++
i<n
false i<n
true
false
j=0 j<n-i
j++
j++

true
If false
a[i]>a[j
]+1]
true
temp=a[i]
a[i]=a[j]
a[j]=temp

i=0 i++
false i<n
true
Print a[i]

Stop

102
Program:

#include<stdio.h>
#include<conio.h>

void bubble_sort(int[], int);

void main() {
int arr[30], num, i;

printf("\nEnter no of elements :");


scanf("%d", &num);

printf("\nEnter array elements :");


for (i = 0; i < num; i++)
scanf("%d", &arr[i]);

bubble_sort(arr, num);
getch();
}

void bubble_sort(int iarr[], int num) {


int i, j, k, temp;

printf("\nUnsorted Data:");
for (k = 0; k < num; k++) {
printf("%5d", iarr[k]);
}

for (i = 1; i < num; i++) {


for (j = 0; j < num - 1; j++) {
if (iarr[j] > iarr[j + 1]) {
temp = iarr[j];
iarr[j] = iarr[j + 1];
iarr[j + 1] = temp;
}
}

printf("\nAfter pass %d : ", i);


for (k = 0; k < num; k++) {
printf("%5d", iarr[k]);
}
}
}

Output:

103
1)

Enter no of elements :5

Enter array elements :10


18

9
4
7

Unsorted Data: 10 18 9 4 7
After pass 1 : 10 9 4 7 18
After pass 2 : 9 4 7 10 18
After pass 3 : 4 7 9 10 18
After pass 4 : 4 7 9 10 18

2)

Enter no of elements :8

Enter array elements :120 45 23 1 7 8 44 22


Unsorted Data: 120 45 23 1 7 8 44 22
After pass 1 : 45 23 1 7 8 44 22 120
After pass 2 : 23 1 7 8 44 22 45 120
After pass 3 : 1 7 8 23 22 44 45 120
After pass 4 : 1 7 8 22 23 44 45 120
After pass 5 : 1 7 8 22 23 44 45 120
After pass 6 : 1 7 8 22 23 44 45 120
After pass 7 : 1 7 8 22 23 44 45 120

Viva Questions:

1) What is importance of arranging the data?


2) What are the different parameter passing modes?
3) What are the functions supported by “conio.h” header file?

8 c i a) Write a c Program that use recursive function to find the factorial of a given
integer.

104
Description:

Factorial of a number is nothing but the multiplication of numbers from a given number
to 1

Algorithm:

main program

Step 1: start
Step 2: read n
Step 3: call sub program
Step4: f=fact(n)
Step 5: print f value
Step 6: stop

Sub program:

Step 1: initialize the f


Step 2: if n= = 0 return 1 to main program if not goto step 3
Step 3: return n*fact(n-1) go to main program

Flowchart:

105
Start

Read n

Call subprogram

f = fact(n)

print f

Stop

Sub program

fact(int n)

false
n==0

true
Return 1 Return
n*fact(n-1)

Return to main
program

Program:

#include<stdio.h>
106
#include<conio.h>
int fact(int n)
{
int f;
if((n==0)||(n==1))
return 1;
else
f=n*fact(n-1);
return(f);
}
void main()
{
int n;
clrscr();
printf("enter the number :");
scanf("%d",&n);
printf("factorial of number %d is %d",n,fact(n));
getch();
}

Output:

1)
enter the number :5
factorial of number 5 is 120

2)
enter the number :9
factorial of number 9 is 362880

8 c i b) Write a c Program that use non recursive function to find the factorial of a given
integer.

Description:

107
Factorial of a number is nothing but the multiplication of numbers from a given number
to 1

Ex: 5! =5*4*3*2*1= 120

Algorithm: main program

Step 1: start
Step 2: read n
Step 3: call the sub program fact(n)
Step 4: print the f value
Step 5: stop

Sub program:

Step 1: initialize the f=1


Step 2: if n==0 or n=1 return 1 to main program. If not goto step 3
Step 3: perform the looping operation as follows
For i=1 i<=n; i++
Step 4: f=f*i
Step 5: return f value to the main program

Flowchart:

108
start

Read n

Call subprogram
Fact(n)

Print F value

Stop

Subprogram Flowchart

Fact (int n)

Initialize F = 1

i= 1 i++
i<=n

false true

F=F*i

Return to main
program Return F

Program:

#include<stdio.h>
109
#include<conio.h>
long int f=1;
long int fact(int n)
{
int i;
if((n==0)||(n==1))
return 1;
else
{
for(i=n;i>=1;i--)
f*=i;
}
return(f);
}
void main()
{
int n;
clrscr();
printf("enter the number :");
scanf("%d",&n);
printf("factorial of number %d is %ld",n,fact(n));
getch();
}

Output:
1)
enter the number :11
factorial of number 11 is 39916800

2)
enter the number :7
factorial of number 7 is 5040

VIVA QUESTIONS:

1) What is the factorial of a number?


2) What is recursion? How is it useful in functions?
3) Define library function?
4) Define formal parameters?

8 c ii a) Write a c Program that use recursive function to find the GCD of two given
integers by using the recursive function

Description:

110
GCD means Greatest Common Divisor. i.e., the highest number which divides the
given number
Ex: GCD(12,24) is 12.Formulafor GCD is given by
GCD= product of numbers/ LCM of numbers

Algorithm:

1) For recursion:

Main program

Step 1: start
Step 2: read a,b
Step 3: call the sub program gcdrecursive(a,b) for print the value
Step 4: stop

Sub program:

Step 1: if n>m return GCD(n,m)


Step 2: if n==0 return m else goto step 3
Step 3: return gcdrecursive(n,m%n)
Step 4: return to main program

Flowchart(for recursion):

111
Start

Read a,b

Call sub program


G=gcdrecursive(a,b)

Print GCD value

Stop

gcdrecursive( )

false true
If
n>m
true
F Return
gcdrecursive(n,m)
If
n==0

Return m Call the same function


Return gcdrecursive(n,m%n)

Return to main
program

Program:

#include<stdio.h>
112
int main()
{
int n1,n2,gcd,lcm;
clrscr();
printf("\nEnter two numbers: ");
scanf("%d %d",&n1,&n2);
gcd=findgcd(n1,n2);
printf("\nGCD of %d and %d is: %d",n1,n2,gcd);
return 0;
}

int findgcd(int m,int n)


{
if(n==0)
return m;
else
return findgcd(n,m%n);

Output:
1. Enter two numbers: 250 150

GCD of 250 and 150 is: 50

2. Enter two numbers: 12 36

GCD of 12 and 36 is: 12

VIVA QUESTIONS:

1) What is a function?
2) What is the GCD of 0, 10?Why?
3) What is the storage class used in this program?

113
8 c ii b) Write a c Program that use non recursive function to find the GCD of two given
integers by using the recursive function

Description:

GCD means Greatest Common Divisor. i.e the highest number which divides the given
number
Ex: GCD(12,24) is 12
Formula: GCD= product of numbers/ LCM of numbers

Algorithm:

Main program
Step 1: start
Step 2: read a,b
Step 3: call sub program g=GCD(a,b)
Step 4: print the g value
Step 5: stop

Sub program:

Step 1: remainder r=m%n


Step 2: repeat the steps 3.1 to 3.3 until remainder!=0 else goto step 4
Step 2.1: m=n
Step 2.2:n=r
Step 2.3:r=m%n
Step 4: return n to main program

114
Flowchart:

start

Read a, b

Call subprogram
gcdnonrec(a,b)

Output g

stop

Subprogram Flowchart

gcdnonrec(m,n)

r=m%n

true false
r!=0

m=n, Return n
n=r,
r=m%n

Return to main program

Program:

115
#include<stdio.h>
int main(){
int n1,n2,gcd,lcm;
printf("\nEnter two numbers: ");
scanf("%d %d",&n1,&n2);
gcd=findgcd(n1,n2);
printf("\nGCD of %d and %d is: %d",n1,n2,gcd);
lcm=n1*n2/gcd;
printf("\nLCM of %d and %d is: %d",n1,n2,lcm);
return 0;
}

int findgcd(int m,int n)


{
int r;
r=m%n;
while(r!=0)
{
m=n;
n=r;
r=m%n;
}

return n;

Output:

1. Enter two numbers: 250 150

GCD of 250 and 150 is: 50

2. Enter two numbers: 12 36

GCD of 12 and 36 is: 12

VIVA QUESTIONS:

1) What is known as nesting of functions?


2) What is meant by a function call?
3) Distinguish between recursive and non-recursive mechanisms?

116
8 c iii a) Write a c Program that use recursive function to generate fibonacci series.

Description

A fibonacci series is defined as follows


The first term in the sequence is 0
The second term in the sequence is 1
The sub sequent terms 1 found by adding the preceding two terms in the sequence
Formula: let t1,t2,…………tn be terms in fibonacci sequence
t1=0, t2=1
tn=tn-2+tn-1……where n>2

Algorithm:

main program

Step 1: start
Step 2: read range (n)
Step 3: : Initialize i=0
Step 4: repeat step 4.1, 4.2 until i<=n is true else goto step 5
Step 4.1: call the sub program fib(n) and then print the value
Step 4.2: i++
Step 5: stop

Sub program:

Step 1: if n==1 return 0 else if n==2 return 1 else goto step 2


Step 2: return fib (n-1)+fib(n-2)
Step 3: return to main program

117
Flowchart:

Start

Read n

I=1 i<=n i++

Print Call subprogram fib(n)

Stop

Sub program

fib(int
n)

false
n==1? n==2 ?

true
return 0 return 1 return fib(n-1)+fib(n-2)

Return to main
program

Program:
118
#include<stdio.h>
int Fibonacci(int);
main()
{
int n, i, c;
clrscr();
printf("Enter no of terms in fibonacci series");
scanf("%d",&n);

printf("Fibonacci series\n");

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


{
printf("%d\t", Fibonacci(i));

return 0;
}

int Fibonacci(int n)
{
if ( n == 0 || n == 1 )
return n;
else
return Fibonacci(n-1) + Fibonacci(n-2);
}

Output:
1)Enter no of terms in fibonacci series10
Fibonacci series
0 1 1 2 3 5 8 13 21 34
2)
Enter no of terms in fibonacci series20
Fibonacci series
0 1 1 2 3 5 8 13 21 34
55 89 144 233 377 610 987 1597 2584 4181

VIVA QUESTIONS:

1) What is Fibonacci series?


2) What are the various types of unconditional statements?
3) What are the various types of conditional statements?

8 c iii b) Write a c Program that use non recursive function to generate Fibonacci series.

Description

119
A Fibonacci series is defined as follows

The first term in the sequence is 0

The second term in the sequence is 1

The current term is calculated by adding the preceding two terms in the sequence

Algorithm: main program

Step 1: start
Step 2: read range (n)
Step 3: : Initialize i=0
Step 4: repeat step 4.1, 4.2 until i<=n is true else goto step 5
Step 4.1: call the sub program fib(n) and then print the value
Step 4.2: i++
Step 5: stop
Algorithm subprogram :

Step 1: start
Step 2: initialize the a=0, b=1
Step 3: read n
Step 4: if n== 1 print a go to step 7. else goto step 5
Step 5: if n== 2 print a, b go to step 7 else print a,b
Step 6: initialize i=3
i) if i<= n do as follows. If not goto step 7
c=a+b
a=b
b=c
increment i value
goto step 6(i)
Step 7: return c
Step 8:stop

120
Flowchart:

Start

Read n

I=1 i<=n i++

Print Call subprogram fib(n)

Stop

Sub program

fib(int
n)

false
n==1 n==2 ?
? Initialize a=0,b=1
true
return 0 return 1 I=0 i<n i++

c=a+b;
a=b;
b=c;
return to main
program
return c
121
Program:

#include<stdio.h>
int Fibonacci(int);
main()
{
int n, i,c;

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

printf("Fibonacci series\n");

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


{
printf("%d\t", Fibonacci(i));

return 0;
}

int Fibonacci(int n)
{
int i,a=0,b=1,c;
if ( n == 0 || n==1)
return n;
else
{
for(i=2;i<=n;i++)
{
c=a+b;
a=b;
b=c;
}
}
return c;
}

Output:
1)

Enter no of terms in fibonacci series10

Fibonacci series

122
0 1 1 2 3 5 8 13 21 34

2)

Enter no of terms in fibonacci series20

Fibonacci series

0 1 1 2 3 5 8 13 21 34

55 89 144 233 377 610 987 1597 2584 4181

VIVA QUESTIONS:

1) Whether the number 88 comes under Fibonacci series? Justify


2) What is the purpose of return statement?
3) Define function definition and function declaration?

123
9 a) Write a c program to implement a structure to read and display the Name, date of Birth
and salary of ten employees.

Description:

Structure is a user defined data type available in C programming, which allows you to
combine data items of different kinds. Structures help to organize complex data in a
meaningful way.

Algorithm

1. Start.
2. Declare structure members with tag name emp
3. Read number of employees n
4. Read n employees information.(employee name ,date of birth, salary)
5. Display n employees information.( employee name ,date of birth, salary)
6. Stop

124
Flowchart
start

Read number of
employees (n)

Read n employees name,date


of birth , salary

i=0 i<n

i+
+
F T
Display n employees name,
date of birth , salary of
emp[i]

Stop

125
Program:
struct emp
{
char name[10];
int sal;
struct
{
int date,year;
char month[10];

}dob;
};

void main()
{
int i;
struct emp e[10];
for(i=0;i<10;i++)
{
printf("enter name sal,date,month,year of emp[%d]",i+1);
scanf("%s%d%d%s%d",e[i].name,&e[i].sal,&e[i].dob.date,e[i].dob.month,&e[i].dob.year);
}
for(i=0;i<10;i++)
{
printf("employee %d details\n",i+1);
printf("name:%s\nsal:%d\ndob:%d %s
%d\n",e[i].name,e[i].sal,e[i].dob.date,e[i].dob.month,e[i].dob.year);
}
getch();
}

Output:

enter name sal,date,month,year of emp[1]hari


20000
12
12
2014
enter name sal,date,month,year of emp[2]gopi
21000
12
4
2012
enter name sal,date,month,year of emp[3]lalitha
22000
15
4
2011
enter name sal,date,month,year of emp[4]murari

126
23000
23
4
2010
enter name sal,date,month,year of emp[5]bhaskar
22000
12
3
1990
enter name sal,date,month,year of emp[6]satish
23000
23
4
1999
enter name sal,date,month,year of emp[7]gopi
20000
12
4
2000
enter name sal,date,month,year of emp[8]vinni
30000
12
4
2000
enter name sal,date,month,year of emp[9]mani
28000
23
5 2000
enter name sal,date,month,year of emp[10]harsha
30000
12
3
1998
Employee1 details
name: hari
sal: 20000
dob: 12 12 2014
employee 2 details
name: gopi
sal: 21000
dob: 12 4 2012

employee 3 details
name:
sal:
dob:
employee 4 details
name:
sal:
dob:
employee 5 details

127
name:bhaskar
sal:22000
dob:12 3 1990
employee 6 details
name:satish
sal:23000
dob:23 4 1999
employee 7 details
name:gopi
sal:20000
dob:12 4 2000
employee 8 details
name:vinni
sal:30000
dob:12 4 2000
employee 9 details
name:mani
sal:28000
dob:23 5 2000
employee 10 details
name:harsha
sal:30000
dob:12 3 1998

VIVA QUESTIONS:

1) What is a Structure?
2) Difference between Structure and Union?
3) How do you access Structure Members?

128
9 b) Write a c program to display the Name, Marks in five subjects and total marks of
given number of students. (Using array of structures).

Description:An array of structures uses each element of an array to represent a structure


variable. We declare an array which displays the sum of the marks obtained by the students
along with their individual subject total marks.

Algorithm
1. Start.
2. Declare structure members with tag name
3. Read number of students n
4. Read n students information.(student name, marks in 5 subjects)
5. Display n students information.(student name, marks in 5 subjects)
6. Calculate total marks for each student
7. Display total marks for each student
8. Stop

129
Flowchart
start

Read number of
students (n)

Read n students name,marks


in 5 subjects

i=0 i<n

i+
+
F T F
Display student name

j=0
j<n
j+
+

T
Display student marks in
5 subjects

Calculate total marks of each student using


s[i].tot+=s[i].marks[j]

Display total marks of each


student

Stop

Program

130
struct stu
{
char name[10];
int m1[5];
int tot;
}s[20];

main()
{
int n,i,j;
clrscr();
printf("Enter no of students");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter student %d name and five subjects marks details",i+1);
scanf("%s",s[i].name);
for(j=0;j<5;j++)
scanf("%d",&s[i].m1[j]);
}
for(i=0;i<n;i++)
{
printf("\nStudent Name%s\n",s[i].name);
printf("\n Marks in 5 subjects");
for(j=0;j<5;j++)
{
printf("%d\t",s[i].m1[j]);
s[i].tot+=s[i].m1[j];
}
printf("\nTotal=%d\n",s[i].tot);
}

getch();
}

Output

Enter student 1 name and five subjects marks details hari


45 67 89 34 67

Enter student 2 name and five subjects marks details gopi


56 89 67 98 45

Enter student 3 name and five subjects marks details lavanya


45 67 89 67 97

Student Name hari

Marks in 5 subjects 45 67 89 34 67
Total=302

131
Student Name gopi

Marks in 5 subjects 56 89 67 98 45
Total=355

Student Name lavanya

Marks in 5 subjects 45 67 89 67 97
Total=365

Enter no of students 1

Enter student 1 name and three subjects marks details sai


89 67 78 67 90

Student Name sai

Marks in 5 subjects 89 67 78 67 90
Total=391

Viva Questions:

1) What is the difference between arrays of structures and arrays within structures?
2) Explain about the “dot operator”?
3) Is nesting of structures possible? Justify.

9c) Write a C program to perform the following operations using Structure and
functions:
i) Reading a complex number
ii) Writing a complex number
iii) Addition of two complex numbers

132
iv) Multiplication of two complex numbers

Description:
In this program the complex number means it contains the two parts . first one is real part and
second one is imaginary part(2+3i).by taking these two complex numbers we can perform the
addition and multiplication operation.

Algorithm for main function


Step 1: Start
Step 2: Define structure compl with members r and c
Step 3: Read 2 complex numbers c1,c2
Step 4: Display first complex number is
Step 5: Call subprogram write(c1)
Step 6: Display first complex number is
Step 7: Call subprogram write(c2)
Step 8: Display addition result is
Step 9: Call subprogram add(c1,c2)
Step 10: Display multiplication result is
Step 11: Call subprogram mul(c1,c2)
Step 12: Stop
Algorithm for write function

Step 1: Display complex number c

Step 2: Return to calling function

Algorithm for add function

Step 1 : calculate c3.r = c1.r+c2.r;

Step 2 : calculate c3.i=c1.i+c2.i ;

Step 3 : return to main function

Algorithm for mul function

Step 1: calculate c4.r=c1.r*c2.r-c1.i*c2.i

Step 2 : calculate c4.i=c1.r*c2.i+c1.i*c2.r

Step 3: return to main function

133
Flow chart:
Start

subprogram write(struct compl c)


Define structure
compl with
members r and c
Display complex number c
c1c
Read 2 complex
numbers c1,c2 Return to calling function

Display first complex


number is
subprogram add(struct compl c1,
struct compl c2)

Call subprogram
write(c1) c3.r=c1.r+c2.r;
c3.i=c1.i+c2.i ;
Display second complex number is
Call subprogram
write(c3)
Call subprogram write(c2)
return to main

Display addition result is


subprogram mul(struct compl c1,
struct compl c2)

Call subprogram add(c1,c2)


c4.r=c1.r*c2.r-c1.i*c2.i
c4.i=c1.r*c2.i+c1.i*c2.r

Display multiplication result is


Call subprogram

write(c4)
Call subprogram mul(c1,c2)
return to main

Stop

Program:

134
struct comp
{
int r,i;
};
void write(struct comp);
void add(struct comp,struct comp);
void mul(struct comp,struct comp);
main()
{
struct comp c1,c2,c3;
clrscr();
printf("Enter first complex number");
scanf("%d %d",&c1.r,&c1.i);
printf("Enter second complex number");
scanf("%d %d",&c2.r,&c2.i);
printf("\nFirst complex number is");
write(c1);
printf("\n Second complex number is");
write(c2);
add(c1,c2);
mul(c1,c2);
getch();
}
void write(struct comp c1)
{
printf("\n%d+%di",c1.r,c1.i);
}
void add(struct comp c1,struct comp c2)
{
struct comp c3;
c3.r=c1.r+c2.r;
c3.i=c1.i+c2.i;
printf("\nAddition result is");
write(c3);
}
void mul(struct comp c1,struct comp c2)
{
struct comp c3;
c3.r=c1.r*c2.r-c1.i*c2.i;
c3.i=c1.r*c2.i+c1.i*c2.r;
printf("\nMultiplication result is");
write(c3);
}

Output:

1)

135
Enter first complex number2
3
Enter second complex number3
4
First complex number is
2+3i
Second complex number is
3+4i
Addition result is
5+7i
Multiplication result is
-6+17i

2)
Enter first complex number2
-2
Enter second complex number-8
-9
First complex number is
2+-2i
Second complex number is
-8+-9i
Addition result is
-6+-11i
Multiplication result is
-34+-2i

VIVA QUESTIONS:

1) Define structure?
2) What is use of <math.h> header file?
3) What is a matrix?

136
10 a) Write a C program to exchange (Swap) values of two integers using call by
reference.

Description
This program interchanges values of two variables using functions and sending addresses.

Algorithm:

Step 1 : Start
Step 2 : Read num1,num2.
Step 3 : Display before swapping num1,num2.
Step 4 : Calling swap function.
Step 5 : Display after swapping.
Step 6 : Stop

Algorithm for swap:


Step 1 : start
Step 2 : assign t = *a;
Step 3 : assign *a =*b
Step 4 : assign *b = t
Step 5 : stop

start

Read num1, num2

Before Swapping Print


num1,num2

Swap(&num1,&
num2)

Flowchart:
After Swaping Print
num1,num2137

Stop
Subprogram:

void swap(int *a,int


*b)

temp=*a
*a=*b,
*b=temp

main()

Program
#include<stdio.h >
#include<conio.h>
void swap(int *a,int *b)
138
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int num1,num2;
clrscr();
printf("Enter 2 Numbers to Swap:");
scanf("%d%d",&num1,&num2);
printf("\nBefore Swapping: Two Numbers are:Num1=%d\tNum2=%d",num1,num2);
swap(&num1,&num2);
printf("\nAfter Swapping:\nTwo Numbers are:Num1=%d\tNum2=%d",num1,num2);
getch();
}

Output:
Enter 2 Numbers to Swap:10 20
Before Swapping:
Two Numbers are:Num1=10 Num2=20
After Swapping:
Two Numbers are:Num1=20 Num2=10
Enter 2 Numbers to Swap:55 66
Before Swapping:
Two Numbers are:Num1=55 Num2=66
After Swapping:
Two Numbers are:Num1=66 Num2=55

Viva Questions:

1) What is the difference between call by value and call by reference?


2) What is a pointer?
3) Explain about chaining of pointers?

139
10 b i) Write a C program to illustrate the usage of dynamic memory management
function.(malloc)

Description:

Dynamic memory allocation allows a program to obtain more memory space, while
running or to release space when no space is required. C language supports allocation of
memory dynamically by using four library functions under "stdlib.h" for dynamic memory
allocation.

Function Use of Function


malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
Allocates space for an array elements, initializes to zero and then returns a pointer to
calloc()
memory
free() deallocate the previously allocated space
realloc() Change the size of previously allocated space

Algorithm

Step 1 : start
Step 2 : read n
Step 3 : allocate memory for n values of given type using malloc
Step 4 : assign 0 to i ,sum to 0
Step 5 : if(i<n) go to step 6 else go to step 8
Step 6 : read p+i value
Step 7 : compute i = i+1 goto step 5
Step 8 : assign 0 to i
Step 9: if(i<n) go to step 10 else go to step 13
Step 10 : display *(p+i), (p+i)
Step 11: compute sum=sum+*(p+i)
step 12: increment i go to step 9
Step 13: display sum
Step 14: free the memory
step 15 : Stop

140
Flowchart:

STAR
T

Read n

p=(int *) malloc(n*sizeof(int));

i=0 i++
false
i<n

true

Read (p+i)

i=0 i++
false
i<n

true
Print *(p+i), (p+i)

sum+=*(p+i)

Display sum

free(p)

Stop

141

free(a)
Stop
Program:

#include<stdio.h>
main()
{
int *p,n,i,sum=0;
printf("\n Enter size");
scanf("%d",&n);
p=((int *)calloc(n,sizeof(int)));
if(p==NULL)
{
printf(" No space");
exit(0);
}
printf("\n Enter %d elements",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("\n Element \t Address\n");
for(i=0;i<n;i++)
{
printf("\n %d\t %u",*(p+i),p+i);
sum+=*(p+i);
}
printf("%d",sum);
free(p);
}

142
Output:
1)

Enter size5
Enter 5 elements5
4
3
2
1
Element Address

5 3458
4 3460
3 3462
2 3464
1 3466

15

2)

Enter size8

Enter 8 elements12 3 5 1 7 9 23 54

Element Address

12 3458
3 3460
5 3462
1 3464
7 3466
9 3468
23 3470
54 3472

114

143
10 b ii) Write a C program to illustrate the usage of dynamic memory management
function. (realloc)

Algorithm

Step 1 : start
Step 2 : read n
Step 3 : allocate memory for n values of given type using malloc
Step 4 : assign 0 to i
Step 5 : if(i<n) go to step 6 else go to step 7
Step 6 : display p+i value goto step 5
Step 7: read new size n2
Step 8 : assign 0 to i
Step 9 : if(i<n2) go to step 10 else go to step 11
Step 10 : display p+i value
Step 11: free the memory
Step 12: Stop

Flowchart:

144
STAR
T

Read n

p=(int *) malloc(n*sizeof(int));

i=0 i++
false
i<n

true

display (p+i)

Read new size(n2)

i=0 i++
false
i<n2

true
display (p+i)

free(p)

Stop

Program

#include<stdio.h>

145

free(a)
Stop
main()
{
int *p,n,n2,i;
printf("\n Enter size");
scanf("%d",&n);
p=(int *)malloc(n*sizeof(int));
if(p==NULL)
{
printf(" No space");
exit(0);
}
printf("\n previous addresses are");
for(i=0;i<n;i++)
printf("%u\t ",p+i);
printf("\n Enter new size");
scanf("%d",&n2);
p=(int *)realloc(p,n2);
printf("\n new addresses are\n");
for(i=0;i<n2;i++)
printf("%u\t",p+i);
free(p);
}

Output:

1)
Enter size5
previous addresses are3478 3480 3482 3484 3486
Enter new size10
new addresses are
3494 3496 3498 3500 3502 3504 3506 3508 3510 3512

2)
Enter size10
previous addresses are3478 3480 3482 3484 3486 3488 3490
3492 3494 3496
Enter new size6
new addresses are
3502 3504 3506 3508 3510 3512

Viva Questions:

1) Explain about “<alloc.h>” header file


2) What are the differences between static and dynamic arrays?
3) Explain about “sizeof” operator in detail.

10c) Write a C program to copy contents of one file to another.

146
Description:

In this program we have to use the file functions to perform the copy operation from
one file to another file.

Algorithm:

Step 1: Start
Step 2: read source file fname1, destination file fname2
Step 3: open source file in read mode
Step 4: open destination file in write mode
Step 5: if NULL pointer, then print unable to open files, go to step 8 otherwise go
to step6
Step 6: read a character from source file and write to destination file until EOF
Step 7: Close source file and destination file and print copied successfully
Step 8: Stop

Flowchart:

147
Start

Read source file


fname1

Read destination
file fname2

fs=fopen(fname1,"r");
ft=fopen(fname2,"w");

if
false
fs==NULL ||
ft==NULL
false
if ch!=EOF
true
Print
Unable to open true

ch=fgetc(fs);
exit fputc(ch,ft);

fcloseall()

Print File copy operation


performed successfully

Stop

Program:
148
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fs,*ft;
char ch,fname1[20],fname2[20];
printf("\n enter sourse file name");
gets(fname1);
printf("\n enter dest file name");
gets(fname2);
fs=fopen(fname1,"r");
ft=fopen(fname2,"w");
if(fs==NULL||ft==NULL)
{
printf("unable to open");
exit(0);
}
do
{
ch=fgetc(fs);
fputc(ch,ft);
}while(ch!=EOF);
fcloseall();
printf("\nFile copy operation performed successfully");
}

OUTPUT:
enter sourse file name1.c

enter dest file name2.c

File copy operation performed successfully

VIVA QUESTIONS:

1) What is a file system?


2) What are the various operations performed on the file?
3) Explain about EOF?
4) Define File?
5) What are the Modes of Opening a File?
6) Which Header File handles all the file Operations?

149
10d) Write a C program to count the number of characters, words and lines in a file.

Description:
In this program, we have to count the number of lines, words and characters in a given program
or given text by using the string function. We check for conditions new line, empty space for
updating the above values.
Algorithm:

Step 1: Start
Step 2:initialize noc=0,now=0,nol=0.
Step 3: open file fname in read mode
Step 4: if fp is NULL, then print unable to open files, go to step 10 otherwise go
to step5
Step 5: read a character from file to c
Step 6: if c !=EOF then goto step 6.1otherwise go to step 7
6.1 increment noc by 1
6.2 if ch=’ ‘ or c=’\t’ then increment now by 1
6.3 if ch=\n the increment nol and now by 1
Step 7: increment nol and now by 1
Step 8:print the noc ,now and nol
Step 9:Close the file.
Step 10: Stop

start
Flowchart :

Initialize nol,now,noc to
0

Read file name fname1

fp=fopen(fname1,"r")

150
fp==NULL?
F

T
Unable to open the file
file

ch=fgetc(p)

ch!=EOF ?

noc++

ch ==’ ‘
|| \t’
T F
now++

F ch==’\n’ ?

T
nol++

now++

Display nol+1

Display now+1

Display noc

fclose(fp)
Program:

#include<stdio.h> stop
#include<conio.h>
void main()
{
int noc=0,now=0,nol=0;

151
FILE *fw,*fr;
char fname[20],ch;
clrscr();
printf("\n enter the source file name");
gets(fname);
fr=fopen(fname,"r");
if(fr==NULL)
{
printf("\n error \n");
exit(0);
}
do
{
ch=fgetc(fr);
noc++;
if(ch==' ')
now=1+now;
if(ch=='\n')
{
nol++;
now++;
}
}while(ch!=EOF);
fclose(fr);
printf("\n total no of character=%d",noc);
printf("\n total no of words=%d",now+1);
printf("\n total no of lines=%d",nol+1);
getch();
}

Output:
1)
enter the source file namea.c
total no of character=13
total no of words=1
total no of lines=1

2)
enter the source file namerealloc.c
total no of character=431
total no of words=50
total no of lines=25

VIVA QUESTIONS:

1) What is use of strlen() ?


2) What is the difference between getc() and getchar() functions ?
3) What are the null characters used in the above program?

152

You might also like