Vous êtes sur la page 1sur 123

GURU NANAK INSTITUTIONS

TECHNICAL CAMPUS
School of Engineering & Technology
Ibrahimpatnam, R R District 501 506 (A. P.)

COMPUTER PROGRAMMING LAB MANUAL


COMMON TO I B.Tech ALL BRANCHES
(2013-2014)

1
SNO NAME OF PROGRAM Pg no

1 Instructions for Students 1

2 Introduction to computer Concepts 2

a)Operating Systems 3

b)Computer Languages 21

c)Creating and running programs 22

d)Program Development method 23

3 a) Write a C program to find the sum of individual digits of positive integer. 25

b) Write a C program to print Fibonacci numbers 27

c) Write a C program to generate prime numbers between 1 & n 29

4 a) Write a C program to calculate the Sum=1-x2/2!+ x4/4!- x6/6!+ x8/8!- x10/10! 31

b) Write a C program to find the roots of a quadratic equation. 33

5 a) Write a C program to solve s=ut+1/2 at2 35

b) Write a C program perform arithmetic operations using switch statement 36

a) i)Write a C program to find the factorial of a given integer using non-recursive 40


6 function.

a)ii) Write a C program to find factorial of a given integer using recursive function. 42

b) i) Write C program to find GCD of two integers by using the recursive function 43

b) ii) Write C program to find GCD of two integers using non-recursive function. 45

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

b)i) Write a C program to perform addition of two matrices. 48

b)ii) Write a C program to multiplication of two matrices 51

a)Write a C program that uses functions to perform the following operations: 53


8 i)To insert a sub-string in to given main string from a given

ii) To delete n Characters from a given position in a given string. 55


2
b) Write a C program to determine if the given string is palindrome or not. 56

a) Write a C program that displays the position or index in the string S where the 58
9 string T begins, or - 1 if S doesn't contain T.

b) Write C program to count the number of lines, words & characters in a given text. 60

10 a) Write a C program to generate Pascals triangle. 62

. b) Write a C program to construct a pyramid of numbers 64

11 Write a C program to read in two numbers, x and n, and then compute the sum of this 66
geometric progression: 1+x+x2+x3+.+xn

a) 2s complement of a number is obtained by scanning it from right to left and 67


12 complementing all the bits after the first appearance of a 1. Thus 2s complement
of 11100 is 00100. Write a C program to find the 2s complement of a binary
number.

b) Write a C program to convert Roman numeral to decimal equivalent. 70

13 Write a C program that uses functions to perform the following operations: 72


i) Reading a complex number ii) Writing a complex number
iii) Addition of two complex numbers iv) Multiplication of two complex numbers

14 a) Write a C program to copy the contents of one file to another. 76

b) Write a C program to reverse the first n characters in a file. 78

15 a) Write a c program to display the contents of a file. 80

b) Write a C program to merge two files into a third file (i.e., the contents of the first 81
file followed by those of the second are put in the third).

16 a) Write a C program that uses non recursive function to search for a Key value in a 82
given list of integers using Linear search.

b) Write a C program that uses non recursive function to search for a Key value in a 85
given sorted list of integers using Binary search

17 a) Write a C program that implements the Selection sort method to sort a given array 87
of integers in ascending order.

b) Write a C program that implements the Bubble sort method to sort a given list of 90
names in ascending order.

3
18 Write a C program that uses functions to perform Various operations on singly linked 93
list.

19 Write a C program that implements stack (its operations) using a singly linked list to 100
display a given list of integers in reverse order

20 Write a C program that implements Queue (its operations) using a singly linked list 104
to display a given list of integers in the same order

21 Write a C program to implement the linear regression algorithm. 108

22 Write a C program to implement the polynomial regression algorithm. 110

23 Write C program to implement the Lagrange interpolation. 113

24 Write C program to implement the Newton- Gregory forward interpolation. 114

25 Write a C program to implement Trapezoidal method. 116

26 Write a C program to implement Simpson method. 118

4
INSTRUCTIONS FOR STUDENTS

These are the instructions for the students attending the lab :
Before entering the lab the student should carry the following things
(MANDATORY)
1. Identity card issued by the college.
2. Class notes
3. Lab observation book
4. Lab Manual
5. Lab Record
Student must sign in and sign out in the register provided when attending the lab
session without fail.
Come to the laboratory in time. Students, who are late more than 15 min., will not
be allowed to attend the lab.
Students need to maintain 100% attendance in lab if not a strict action will be
taken.
All students must follow a Dress Code while in the laboratory
Foods, drinks are NOT allowed.
All bags must be left at the indicated place.
Refer to the lab staff if you need any help in using the lab.
Respect the laboratory and its other users.
Workspace must be kept clean and tidy after experiment is completed.
Read the Manual carefully before coming to the laboratory and be sure about what
you are supposed to do.
Do the experiments as per the instructions given in the manual.
Copy all the programs to observation which are taught in class before attending
the lab session.
Students are not supposed to use floppy disks, pendrives without permission of
lab- in charge.
Lab records need to be submitted on or before the date of submission.

5
INTRODUCTION TO COMPUTERS
A Computer is an electronic device which performs operations such as accepts
data as an input, store the data, manipulate or process the data and produce the result as
an output.

Hardware: The physical components which are used to assemble computer system are
known as hardware. Any computer device which we can touch including cables and wires
is hardware.
Software
Software is a set of program or instructions given to the computer to carry out certain jobs
or tasks. It is set of programs which actually makes the computer useful
. The software can be classified into three categories
System Software
Programming Software
Application Software

System Software
System software is responsible for managing a variety of independent hardware
components, so that they can work together. Its purpose is to unburden the application
software programmer from the often complex details of the particular computer being
used, including such accessories as communications devices, printers, device readers,
displays and keyboards, and also to partition the computer's resources such as memory
and processor time in a safe and stable manner.
Device drivers
Operating systems
Servers
Utilities
Window systems

Programming Software: Programming Software usually provides tools to assist a


programmer in writing computer programs, and software using different programming
languages in a more convenient way. The tools include:
Compilers
Debuggers
Interpreters
Linkers
Text editors

Application Software: Application software is developed to aid in any task that benefits
from computation. It is a broad category, and encompasses Software of many kinds,
including the internet browser being used to display this page. This category includes:
Business software
Computer aided design
Databases
6
Decision making software
Educational software
Image editing
Industrial automation
Mathematical software
Medical software
Simulation
Spreadsheets
Telecommunications
Video games
Word processing
Operating Systems
Computer Operating System is a System Software program which acts as in
interface between a user and a Computer Machine. The basic goal of an operating system
is to provide convenient environment to the user. Several types of operating systems are
there. Some examples of operating systems are as follows
Microsoft Disk Operating System
Unix Operating System
Windows Operating System

DISK OPERATING SYSTEM


Disk Operating System in short called as DOS is a simple Computer
Operating System. It is invented by Tim Paterson who is an American Computer
Programmer in the 1980s.It is an interface between a user and machine. It receives the
commands given by the user , converts them into simple form commands and given to
core part of the Operating System called as Kernel.

Kernel receives the Simple form commands and generates the corresponding
system calls which can able to execute on the bare hardware of the machine.DOS
consists four major Components and a set of additional utilities.

The major components are as follows:

BOOT RECORD
MSDOS.SYST
IO.SYS
COMMAND.COM

BOOTING: Process that starts up a computer is called booting. It checks for proper
functioning of all the peripheral devices attached with the system. It searches for the
operating system and, when located, loads it into the main memory as shown in the figure1

Cold Booting is done by turning on the computer

Warm Booting is performed by pressing Ctrl+Alt+Del keys simultaneously


Rules for Filenames
Disk files have to be identified by Operating System so that DOS can address
7
them. These filenames have specific rules.

The basic form or syntax of a filename is: Filename.ext

The first part of the name to the left of the period is called the primary name or
root name. The root name can be from one to eight characters long and cannot be the
same as a device name. The second part to the right of the period is the secondary name
or extension. It is optional and, if used, can be one to three characters long. The period is
used between the root name and extension and must be present if there is an extension.

The following are legal and illegal characters in a filename:

Legal: A-Z 0-9 $#&@!()-{}_~

Illegal: |<>\^+=?/[];.* plus control characters and the space

Example for a file name is sample.txt


8
Examples of disk operating systems that were extensions to the os

The DOS operating system for the Apple Computer's Apple II family of
computers.. Usually it was called Apple DOS to distinguish it from MS-DOS.
Commodore DOS, which was used by 8-bit Commodore computers. Unlike
most other DOS systems, it was integrated into the disk drives, not loaded into the
computer's own memory.
Atari DOS, which was used by the Atari 8-bit family of computers. The Atari
OS only offered low-level disk-access, so an extra layer called DOS was booted off of
a floppy that offered higher level functions such as file systems.
MSX-DOS, for the MSX computer standard. Initial version, released in 1984,
was nothing but MS-DOS 1.0 ported to Z80; but in 1988 it evolved to version 2,
offering facilities such as subdirectories, memory management and environment
strings. The MSX-DOS kernel resided in ROM (built-in on the disk controller) so
basic file access capacity was available even without the command interpreter, by
using BASIC extended commands.
Disc Filing System (DFS) This was an optional component for the BBC Micro,
offered as a kit with a disk controller chip, a ROM chip, and a handful of logic chips,
to be installed inside the computer. See also Advanced Disc Filing System.

Examples of Disk Operating Systems that were the OS itself

The DOS/360 initial/simple operating system for the IBM System/360 family
of mainframe computers (it later became DOS/VSE, and was eventually just called
VSE).
The DOS operating system for DEC PDP-11 minicomputers (this OS and the
computers it ran on were nearly obsolete by the time PCs became common, with
various descendants and other replacements).
DOS for the IBM PC compatible platform
The best known family of operating systems named "DOS" is that running on IBM
PCs type hardware using the Intel CPUs or their compatible cousins from other
makers.

Default Drive
The default drive is the first disk drive on which DOS will look for a program
if no drive specification is given with the filename.
The default drive letter is part of the prompt (unless someone has changed the
prompt to eliminate it).
C:\ > indicates that drive C is the default drive. The right (or second) drive in such a
system is called drive B and the first hard disk in any system is given the letter C as its
drive designation. The drive can be changed by typing the desired default drive
followed by a colon at the prompt. To change to drive D from C drive just type D: as
9
shown here:

After changing the drive the prompt appears like as follows

DOS commands divided in to two types. They are as follows.

1. Internal commands or Memory-Resident Commands

2. External Commands or Disk-Residence Commands

Internal Commands

These are also called memory-resident commands. These commands are automatically
loaded in to the computer's memory during the booting process. They actually included

10
in the Command.com file. So these commands are executable immediately after getting
the dos prompt.

Few Internal Commands are as follows

01. VER

02. VOL

03 DATE

04. TIME

05. CLS

06. DIR

07. MD

08. CD

09. PATH

10. RD

11. COPY CON

12. TYPE

13. COPY

14. DEL

15. REN

A Command can be given in upper case or lower case letters. The Internal commands can
execute immediately but External commands require special files for execution without
which it is not possible to execute them.

1.VER- All Operating Systems have its own edition number or release or version
number. The version number indicates which edition of Operating System it is.

Syntax: VER <Enter>

Example: C:\> VER <Enter>

11
2.VOL- It is used to display volume label and serial number of the current drive

Syntax: Vol [drive:]

Example: C:\>Vol <Enter>

3.DATE: - Used to display the current system date and prompt for entering new date.

Syntax: Date <Enter>

Example: C:\> date <Enter>

12
4. TIME: - Displays the current system Time and prompt for entering new time.

Syntax: Time <Enter>

Example: C:\> Time <Enter>

5. CLS: - Clears the cluster screen.

Syntax: CLS <Enter>

Example: C:\> CLS <Enter>

13
6. DIR: - This command displays the list of directories and files with details like date of
creation whether it is directory or file etc.

Syntax: DIR <Enter>

Example: DIR <Enter>

Switches:

/p : To view one screen of files at a time.

/w : Displays only five column of filenames and directories.

/b : Display only file and directory.


14
/l : Display all the information in lower case letters.

/a :stands for attributes that are given below.

/h - Hidden ( or not hidden) files

s/-s - System ( or not systems) files

d/-d - Directory ( or not Directory) names

r/-r - Read only( or not read only) files

DIR *.txt : Display all the files with extension .txt

DIR D???.* : Display all the files starting with D and having less than or equal to
four characters in the file name and any extension.

Here "?" And "*" are called "wild card character".

"*" Stand for any number of the character

"?" Stands for nay one character.

7. MD OR MKDIR: -Used to create a new Directory or nested Directories.

Syntax: MKDIR OR MD [DRIVE:] PATH DIRECTORY NAME

Example: C:\> MD SAMS <Enter>

8. CD OR CHDIR: - This command allows you to change present directory to another


directory.

Syntax: CD [DRIVE:] PATH

Example: C:\> CD SAMS and press <Enter>

9. PATH: - This command defines a list of directories DOS Searches for external
commands.
Syntax: PATH (Displays the current search path)

PATH; : - ( Clear the search path so DOS will search for external commands only in the
current directory)

10. RD: - To delete the empty directory.

Syntax: RD [DRIVE:] PATH

15
NOTE: -The directory must be empty when we use RD.

Example: C:\> RD SAMS and press <Enter>

Switches: - 1. /s - Remove with subdirectories and files.

2. /q - Don't ask to confirm.

11. COPY CON: -We use this command to create a new file.

Syntax: COPY CON <FILENAME>

Example: C:\> Copy Con sams.txt <Enter>

Note: - Typing here and when you are done, press Ctr+Z or F6 key followed by Enter to
save the current document.

12. TYPE: - This command allows you to see the contents of an existing file on the
screen.

SYNTAX: TYPE <file name>

Example: C:\> TYPE SAMS

13. COPY: - Using this command you can make duplicate files of an exiting file from one
location to another or one directory to another with different name or exiting name.
SYNTAX: COPY < SOURCE FILE NAME> <TARGET FILENAME>

Example: C:\> COPY SAMS.TXT A:\TAJ

Example: C:\> COPY*.TXT +*.BAK TARGET FILENAME And Then Press Enter

Example: C:\> COPY SAMS.TXT C:\SAMS_1\FO\RECEPTION And Then Press Enter

You can also have the option to change the name of files as you copy it.

Example: C:\> COPYold.TXT C:\dos\new.txt And Then Press Enter

14. DEL/ERASE: This command removes one or more files from the disk or current
working directories.

SYNTAX: DEL filespec [/p] or ERASE filespec [/p]

Example: C:\> DEL C:*.BAK /P And Then Press Enter

16
Example: C:\> DEL abc And Then Press Enter

Example: C:\> DEL ????.COM And Then Press Enter

Switches: - 1. /p -confirmation 2. /q - In quit mode

15. REN: Used to change the name of the file or directory.

SYNTAX: REN <file name>

Example: REN sams sams1 <Enter>

Example: REN *.dat *.mst And Then Press Enter

16. PROMPT: This command allows you to customize the dos prompt.

SYNTAX: 1. PROMPT

SOME SPECIAL $ PARAMETERS ARE GIVEN BELOW.

CHARACTER EXAMPLE DESCRIPTION


$Q = Equal Sign
$$ $ Dollar Sign
$t 12:30:06:92 Display current time
$d tue 09-07-2007 Display current date
$v msdos version 6.2 show dos version number
$g > Greater than sign
$L < Less than sign

Most people like to set their prompt to $p$g which display the current directory followed
by > sign.

Example: PROMPT $P$G <Enter>

17. TREE: - It is used to display directory structure of a specified directory graphically.

Syntax : TREE [drive:] [path] [/f]

[/F] : displays the names of the files in each directory.

EXTERNAL COMMANDS:

These are also called Disk-Resident Commands. These commands are meant for
special purpose. These are found in separate files on Hard Disk or Floppy Disk, So that

17
they don't typically consume valuable memory space. They are loaded into memory only
when called.

Some External Command are:

1. Xcopy

2. Move

3. FC

4. Doskey

5. Mem

6. FILTER

a.. More

b.. Sort

c Find

7. Attrib

8. Deltree

9. Edit

10. Tree

1. XCOPY: This command is faster than Copy Command and allows you to copy
entire directories/disk including all the sub directories and files to destination.

Syntax: XCOPY Source [ Target][/Y][-Y] [/P][/E]

SWITCHES :

/-Y : Prompts before copying over existing files.

/y : Overwrites existing files without prompting.

/p : Ask before copying each file.

/e : Copying empty directory also.

/s : Copying subfolders.

18
EXAMPLE: XCOPY C:\SAMS D:\SAMS /S/E

2. MOVE : This command moves a file or group of files from one directory to
another and also one disk to another disk. It can also be used to rename directories.

SYNTAX: Move [Path File Name] [Destination file name path]

SWICHES:

/-Y : Prompt before it overwrites while it copies file that already exists.

/Y : Overwrites existing files without prompting.

EXAMPLE: move c:\sams\fo.txt to d:

EXAMPLE: move c:\sams\fo.txt to d:\ new_sams

3. FC: Stands for File Compare. If you wish to compare two files or two sets
of files then you may use this command. This command has the capability to
differentiate between the files and display the difference.
SYNTAX: FC <files spec 1> <files spec2> [/a][/b][/c][l][/n]
Switches

/a : This switch displays only the first and last line of each group.

/b : Compare the files in library mode ( byte-by-byte)

/c : Ignore the case of letters.

/l : Compare the files in text mode.

/n : Displays the line number for lines that are different.

EXAMPLE: FC first.txt second.txt\n and then Press <enter>

4. DOSKEY: Dos can remember only the last command you had entered. But
in order to make DOS remember all the commands you enter you will have to
load a DOSKEY utility. Also Used To Create Macros.

Syntax: DOSKEY and Press <Enter>

Display message on the screen.

DOSKEY Installed.

19
NOTE: - To display all commands from the history list one the screen.
Example: DOSKEY / History or /h < Enter>.

Now when DOSKEY is in memory, it can help store all the commands which you enter
so that any of those commands need not be typed again to be executed. And this all are
called HISTORY LIST. Now when you want the same command to be done you can use
right arrow key or 'F1' or 'F3' Issuing following command.

Second feature of DOSKEY is Doskey Macro. Using this macro you can create own
command and latter you can run it on the system prompt. For example

EXAMPLE: - DOSKEY C= CLS

Now if you type at the system prompt only C and press enter it will clear the screen.

Recalling Commands: Some key is provided to recall recent commands you have run
since installing DOSKEY.

Key Stroke Effect

Up Display the Preceding Command and further list.


Arrow Show the next command you executed after the one that's being
Down
displayed.
Arrow
Page Up Display the oldest command that is still in Doskey.
Page Show the most recent command that you executed
Down Display the entire list of command that you
F7 executed.
F9 Selects a commands
Alt+F7 Erase the command history list.
Alt+F10 Erase all macros in memory
Esc Clear the command line.
Ctrl-T Command separator

20
Computer Programming Lab Manual

5. MEM:

This command displays amount of total available memory ( low, Expanded and
Extended) and all currently programs.

Syntax: MEM [/f][/p][/m]

Switches:

/f : Using this switch MEM display all the areas of memory that are fee.

/p : Use this option to display the information one screen at a time.

/m : Display information about how a specified program is using memory.

Example: MEM/p and then press <Enter>

6. FILTER:

A Powerful feature of DOS is its use of filters to process data directly. A DOS FILTER
can process in unique way any data that passes through it and can change what we see on
the screen.

There are three FILTERS include in DOS.

A. MORE: More command used to pause vertical Scrolling on the display screen,
after each screenful, The display pauses and the message - - More - - appears. Pressing
any key display the next screen.

EXAMPLE: C:\> MORE < TYPE FILE.TXT and then press <Enter>

EXAMPLE: C:\> DIR /MORE and then press <Enter>

B. SORT: Reads, Sorts in Order and sends the data to the screen, file or to another
device. Sort to arrange data in an order.

SYNTAX: SORT [drive:][Path][filename][/r][+n]

Switches:

[drive:][Path][filename] : Specifies the name and location of the file to be


searches. It must be preceded

21
Computer Programming Lab Manual

by the redirection character (<).

[/r] : Sort lines in reverse ASCII Order ( Z-A)

[+n] : Sorts line starting with the contents in column n. The default is 1.

EXAMPLE: C:\> SORT < NAME .TXT and then press <Enter>

EXAMPLE: C:\> SORT /+20 < PHONE .TXT and then press <Enter>

EXAMPLE: C:\> DIR / SORT > PHONE .TXT and then press <Enter>

Note: Sort command doesn't distinguish between upper and lower case. It can sort file
of maximum 63 k size.

Combining Input & Output redirection :

EXAMPLE: C:\> SORT < NAME .DAT > SORTNAME.DAT and then press
<Enter>

Here the sort command is being directed to take its input from <name.dat and after
sorting, send its output to the > sortname.dat file.

C. FIND: The find Filter is used to search a file one or more designated character (called
a text string) Depending upon the form of the FIND Command. Each line having (or not
having) the text string is sent to an output devices. Such as the Screen, a file or the
printer. The text string is always typed within quotes ( "Text Sring").

SYNTAX: FIND [/v][/c][/n] "String " [d:] [path][filename]

Switches:

[/v] : Displays all the lines that do not contain string.

[/c] : Display the total number of lines found to contain the string.

[/n] : Display the line number as well as the line that contains the string.

[/i] : Ignores uppercase or lowercase during the search.

Where:

"String" : Specifies one or more alphabet or numeric character whose maximum


length should not be more than 250 characters and must be enclosed in double quotes.

[d:] [path][filename] : Specifies the name and location of the file to be searches .

22
Computer Programming Lab Manual

EXAMPLE: C:\> FIND "Rajni" my.txt per.txt and then press <Enter>

EXAMPLE: C:\> DIR/ FIND "TXT" and then press <Enter>

7. ATTRIB:

Every File on the Disk has its own description like size, space occupied, the type, the
date it was created, etc. Likewise, every file has few attributes. The attributes of a file
indicates whether it is a

i) Read-Only File: r ii) Archive File a

iii) Hidden File: h iv) System File s

With the ATTRIB command you can check the attributes of a file.

SYNTAX: ATTRIB [+r][+a][+h][/+s] [filename]

Switches:

+r, -r : +r Read-Only attribute or, -r turn of Read-Only attribute

+a,-a : +a archive attribute, or -a turn of archive attribute

+h,-h : +h hidden attribute, or -h turn of hidden attribute

+s, -s : +s system attribute and it should not be used generally.

Note:

While Creating a new file every file gets read only attribute and archive attribute by
default.

EXAMPLE: C:\> ATTRIB my.txt +R and then press <Enter>

EXAMPLE: C:\> ATTRIB my.txt +H and then press <Enter>

8. DELTREE:

This command used for deleting an entire directory whether in that directory contains
files or subdirectories and also it will delete hidden files.

23
Computer Programming Lab Manual

Syntax: DELTREE [drive:][path] directories [/y]

EXAMPLE: C:\> DELTREE my.txt and then press <Enter>

9. EDIT:

This is the DOS Editor, which you can use to edit the text file and also creating new file.

Syntax: Edit [drive:][path][filename]

EXAMPLE: C:\> EDIT c:\sams\FO.TXT and then press <Enter>

EXAMPLE: C:\> Edit NEW FILE and then press <Enter>

BATCH FILES

It is a collection of DOS commands to perform a certain task. or A batch file is nothing


but sequence of commands to perform sequence of operations step by step.

Look at the following commands you give step by step to perform an operation.

Suppose your job is

First - Check the directory

Second - Copy a file called ABC.txt to another disk

Third - Delete ABC.TXT from the present disk

Fourth - Clear the screen

If you do all this steps daily after your hour, then the commands you give would be:

i) C:\> DIR <Enter> ii) C:\> COPY C:ABC.TXT D: <Enter>

iii) C:\> DEL ABC.TXT <Enter> iv) C:\> CLS <Enter>

Instead of heating yup your head daily giving the same set of commands you can do it in
a much simpler manner. All you do is put all the commands in a batch file.

How to create a batch file:

C:\> COPY CON A.bat <Enter>

Note: Here Con means Console that is Keyboard, A the file name and .bat is extension.

GNI 24
Computer Programming Lab Manual

It is compulsory that a batch file must have extension .BAT.

You will find the cursor below 'A' now type

C:\> DIR <Enter>

C:\> COPY A.TXT D : <Enter>

C:\> DEL A.TXT <Enter>

C:\> CLS <Enter>

Now Press the F6 or Ctrl+Z key combination. You shall find ^Z symbol below CLS, Now
press Enter. You will receive the following message

1files Copied.

And you are returned to the prompt C:\>

Now to execute the Batch File simply type the name of the file.

C:\> A <Enter>

You will see all the commands in the A.Bat come right into action. So instead of typing
all those command one after another performed the same job by just typing the file name.

Computer Languages
Programming language is used to communicate user with the computer give ideas,
logics, thoughts etc. These are used to develop programs. These are classified as:
1. Low Level Languages
2. High Level Languages
3. Assembly / Symbolic Language

1.Low Level Languages:


Machine / Binary Language: It is a first generation programming language. It is
the language based on binary digits ( 0s and 1s ).
a. Advantages:
i. Computer can understand directly.
b. Disadvantages:
i. It is very difficult to remember the codes and address of memory
locations.
ii. User cant modify the program.
iii. User cant debug the program.
.iv. It is machine dependent.
.v. It is suitable for simple applications.

2.Assembly / Symbolic Language: It is a second generation programming language.


This language based on symbolic codes (mnemonic) to represent any instruction.
a. Advantages:

GNI 25
Computer Programming Lab Manual

i. User can remember the mnemonics.


ii. It is easy to understand and develop the programs.
iii. User can modify the program and debug.
iv. It is suitable for simple applications.
.b. Disadvantages:

i. It is machine dependent.
ii. It requires the translator program called Assembler.

3.High Level Language: It is a third generation programming language. It is based on


English grammatical notations and mathematical formulaes. these are classified as
general and specific purpose language.
a. Advantages:
i. Easy to follow.
ii. Easy to understand
iii. Easy to modify and debug.
iv. Suitable for complex applications.
b. Disadvantages:
i. It requires the translator program called Compiler or Interpreter.
ii. It runs programs slower with compare to low level languages

INTRODUCTION TO C LANGUAGE

C is a structured programming language developed at AT & Ts Bell Laboratories


of USA in 1972. It was designed and written by Dennis Ritchie. In the late seventies C
began to replace the more familiar languages of that time like PL/I, ALGOL, etc. C was
originally designed for and implemented on the UNIX operating system on the DEC
PDP-11, by Dennis Ritchie.
The operating system, the C compiler, and essentially all UNIX applications are
written in C. C is not tied to any particular hardware or system, however, and it is easy to
write programs that will run without change on any machine that supports C. HISTORY
OF C LANGUAGE Ken Thompson created a language which was based upon a language
known as BCPL and it was called as B. B language was created in 1970, basically for
UNIX operating system, Dennis Ritchie used ALGOL, BCPL and B as the basic
reference language from which he created C. In 1983, the American National Standards
Institute (ANSI) began the definition of a standard of a c. It was approved in December
1989. In 1990, The International standards Organization (ISO) adopted the ANSI
standard. This version of c is known as C89.New features are been added and now the
version of c is C99.

Creating and Running Programs


There are four steps in this process.
1. Writing and editing the program using Text editor (source code).
2.Compile the program using any C compiler
3.Linking the program with the required library modules(object file)
4.Executing the program. (.Exe file)

GNI 26
Computer Programming Lab Manual

Creating and Editing a C Program in a compiler:


Writing or creating and editing source program is a first step in c language. Source
code is written in c programming language according to the type of problem or
requirement, in any text editor. Saving C Program in C Programming Language: Source
code is saved on the secondary storage. Source code is saved as text file. The extension of
file must be ".c". Example the file name is "sample.c"

Compiling C program : Computer does not understand c programming language. It


understands only 0 and 1 means machine language. So c programming language code is
converted into machine language. The process of converting source code in to machine
code is called compiling. Compiler is a program that compiles source code. Compiler also
detects errors in source program. If compiling is successful source program is converted
into object program. Object program is saved on disk. The extension of file is ".obj"

Linking in C programming Language: There are many built in functions available in c


programming language. These functions are also called library functions. These functions
are stored in different header files.

Loading program: The process of transferring a program from secondary storage to


main memory for execution is called loading a program. A program called loader does
loading.

Executing program: Execution is the last step. In this step program starts execution. Its
instructions start working and output of the program display on the screen.

Program Development Method :

1. Specifying and analyzing the problem statement.


2. Designing an Algorithm
3. Coding and Implementation
4. Debugging
5. Testing and validating
6. Documentation and maintenance

Specifying and analyzing the problem statement: the problem which has to be
implemented into a program must be thoroughly understood before the program is
written. Problem must be analyzed to determine the input and output requirements of the
program. A problem statement is created with these specifications.

Designing an Algorithm: with the problem statement obtained in the previous step,
various methods available for obtaining the required solution are analyzed and the best
method is designed into algorithm.
Coding and implementation: the actual problem is written in the required programming
language with the help of information depicted in flow charts and algorithms.

Debugging: there is a possibility of occurrence of errors in programs. These errors must


be removed to ensure proper working of programs. Hence solving the program without
errors is known as debugging.
Types of errors that may occur in the program are:

GNI 27
Computer Programming Lab Manual

a) Syntactic Errors(Compilation Errors): These errors occur due to the usage of wrong
syntax for the statements.

b) Runtime Errors: These errors are determined at the execution time of the program.

c)Logical Errors: These errors occur due to incorrect usage of the instructions in the
program.

Testing and Validating: Testing and Validation is performed to check whether the
program is producing correct results or not for different values according to user
requirement.

Documentation and Maintenance: Documentation is the process of collecting,


organizing and maintaining, in written the complete information of the program for future
references. Maintenance is the process of upgrading the program according to the
changing requirements.

Algorithm / Pseudo Code


Algorithm is a method of representing the step by step logical procedure for solving a
problem. It is a tool for finding the logic of a problem.

Algorithm Properties:
1.Finiteness: an algorithm must terminate in a finite number of steps.
2.Definiteness: Each step of an algorithm must be clear and easy to understand
(unambiguous).
3.Effectiveness: Each step must be effective, in the sense that should be primitive (easily
convertible to program).
4.Generality: The algorithm must be complete in itself so that it can be used to solve all
problems of a specific type for any input data.
5.Input / Output: Each algorithm must take zero, one or more quantities as input data and
produce one or more output values.

Writing an algorithm
An algorithm can be written in English, like sentences and using mathematical formulas.
Sometimes algorithm written in English like language is Pseudo code.
Examples
Finding the average of three numbers

Step 1.Let a, b and c are three integers


Step 2.Let d is float
Step 3.Display the message Enter any three integers:
Step 4.Read three integers and stores in a,b,c
Step 5.Compute the d = (a+b+c)/3.0
Step 6.Display The avg is: , d
Step 7.End.

GNI 28
Computer Programming Lab Manual

Flow Chart
The pictorial representation of an algorithm using some shapes and symbols is known as
flow chart.

Week 1:
1. a) Write a C program to find the sum of individual digits of positive
integer.

AIM:
To find the sum of individual digits of positive integer.
Description:
Summation of digits of a number
Ex: 1234
Summation =1+2+3+4=10
ALGORITHM:
Step 1: Start
Step 2: Read n
Step 3: Initialize sum 0
Step 4: while(n!=0)
Begin
Step 5: rn%10
Step 6: sumsum+r
Step 7: nn/10
End
Step 8: Print sum
Step 9: Stop

GNI 29
Computer Programming Lab Manual

FLOWCHART: Start

Read n

Sum = 0

while False
n!=0

True
r=n%10
sum=sum+r
n=n/10

Print Sum

Stop

PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,r,sum=0;
clrscr();
printf("ENTER A POSITIVE INTEGER \n");
scanf("%d",&n);
while(n!=0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
printf("THE SUMOF INDIVIDUAL DIGITS OF A POSITIVE INTEGER IS..%d",sum);
getch();
}

GNI 30
Computer Programming Lab Manual

SAMPLE INPUT:
ENTER A POSITIVE INTEGER
5321

EXPECTED OUTPUT:
THE SUM OF INDIVIDUAL DIGITS OF A POSITIVE INTEGER IS..11

1. b) A Fibonacci Sequence is defined as follows: the first and second


terms in the sequence are 0 and 1. Subsequent terms are found by
adding the preceding two terms in the sequence. Write a C program
to generate the first n terms of the sequence.

AIM: To generate the first n terms of the Fibonacci sequence..


Description: Initial Fibonacci numbers are 0 and 1. Next number can be generated by
adding two numbers. So 0+1=1. Therefore next number can be generated by adding two
previous . so Fibonacci series is 0 1 1 2 3 5

ALGORITHM:
Step 1 : Start
Step 2 : Read n
Step 3 : Initialize f0 0, f1 1, f 0
Step 4 : i=0
Step 5 : while(i<=n) do as follows
printf("%d\t",f0);
f=f0+f1;
f0=f1;
f1=f;
i=i+1;
If not goto step 7
Step 6 : Stop

GNI 31
Computer Programming Lab Manual

FLOWCHART:
Start

f0=0, f1=1

i=0

FALSE
while
i<n

Stop TRUE Print f0


f=f0+f1;
Print f0 f0=f1;
f1=f;
i=i+1;

PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int f0,f1,f,n,i;
clrscr();
printf("ENTER THE VALUE FOR n \n");
scanf("%d",&n);
f0=0;
f1=1;
printf("FIBONACCI SEQUENCE FOR THE FIRST %d TERMS:\n",n);
i=0;
while(i<n)
{
printf("%d\t",f0);
f=f0+f1;
f0=f1;
f1=f;
i=i+1;
}
}

INPUT:
ENTER THE VALUE FOR n
GNI 32
Computer Programming Lab Manual

10
OUTPUT:
FIBONACCI SEQUENCE FOR THE FIRST 10 TERMS:
0 1 1 2 3 5 8 13 21 34

1. c) Write a C program to generate all prime numbers between


1 and n. Where n is the value supplied by the user.

Aim: To print a prime numbers up to 1 to n


Description:
Prime number is a number which is exactly divisible by one and itself only
Ex: 2, 3,5,7,;
FLOWCHART:

Start

Read n

false I=1
I<=n
I++

false J = 1 J++

J<=i
false true

If fact==2
false

If I % j == 0

Output i true

Fact ++

stop

GNI 33
Computer Programming Lab Manual

Algorithm:
Step 1: start
Step 2: read n
Step 3: initialize i=1,c=0
Step 4:if i<=n goto step 5
If not goto step 10
Step 5: initialize j=1
Step 6: if j<=i do the following. If no goto step 7
i)if i%j==0 increment c
ii) increment j
iii) goto Step 6
Step 7: if c== 2 print i
Step 8: increment i
Step 9: goto step 4
Step 10: stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,fact,j;
clrscr();
printf("enter the number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{ fact=0;
//THIS LOOP WILL CHECK A NO TO BE PRIME NO. OR NOT.
for(j=1;j<=i;j++)
{
if(i%j==0)
fact++;
}
if(fact==2)
printf("\n %d",i);
}
getch( );
}
Output:
Enter the number : 5
2 3 5

GNI 34
Computer Programming Lab Manual

Week2:
2. a) Write a C program to calculate the Sum=1-x2/2!+ x4/4!- x6/6!+
x8/8!- x10/10!

Aim: To calculate the sum.


Algorithm:
Main program:

Step 1: start
Step 2: declare x,i,n,s=0,c
Step 3: read x value
Step 4: for i=0 , n=0; i<=10; i=i+2, n++ goto step 5
Step 5: s=s+(pow(-1,n)*pow(x,i)/fact(i))
Step 6: print s value
Step 7: stop

Sub program: fact( x)

Step 1: while x!=0 goto Step 2


Step 2: y=y+x; x
Step 3: return y
Step 4: return to main program
Flowchart:
Main Program:

GNI 35
Computer Programming Lab Manual

Program:
#include<stdio.h>
#include<math.h>
long fact(int);
void main()
{
int x,i,n;
float s=0,c;
clrscr();
printf("\n enter the value of x\t");
scanf("%d",&x);
/*perform the looping operation*/
for(i=0,n=0;i<=10;i=i+2,n++)
s=s+(pow(-1,n)*pow(x,i)/fact(i));
printf("\n the result is %f",s);
getch();
}
/* calling sub program*/

long fact(int x)
{
long int y=1;
while(x!=0)
{
y=y*x;
x--;
}
return y;
}

Input:
Enter the value of x : 1
Output:
The result is 0.540302 2 Enter the value of x: 2 The result is -0.416155

GNI 36
Computer Programming Lab Manual

2. b) Write a C program to find the roots of a quadratic equation.

AIM: To find the roots of a quadratic equation.


Description: roots of quadratic equation are
ALGORITHM:
Step 1: Start
Step 2: Read a,b,c
Step 3: calculate disc = b*b-4*a*c
Step 4: if(disc>0)
Begin
Step 5: root1=(-b+sqrt(disc))/(2*a)
Step 6: root2=(-b-sqrt(disc))/(2*a)
Step 7: Print Root1 , Root2
End
Step 8: else if(disc=0)
Begin
Step 9: root1=-b/(2*a)
Step 10: root2=root1;
Step 11: Print Root1 , Root2
End
Step 12: else
Step 13: Print Roots are imaginary
Step 14: Stop

FLOW CHART

GNI 37
Computer Programming Lab Manual

PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int a,b,c;
float disc,root1,root2;
float img,real;
printf("ENTER VALUES FOR a,b,c:\n");
scanf("%d%d%d",&a,&b,&c);
disc=(float)b*b-4*a*c;
if(disc>0)
{ printf("THE ROOTS ARE REAL & UNEQUAL:\n");
root1=(-b+sqrt(disc))/(2*a);
root2=(-b-sqrt(disc))/(2*a);
printf("Root1=%f\n",root1);
printf("Root2=%f\n",root2);
}
else if(disc==0)
{
printf("THE ROOTS ARE REAL AND EQUAL:\n");
root1=-b/(2*a);
root2=root1;
printf("Root1=%f\n",root1);
printf("Root2=%f\n",root2);
}
else
{ printf("THE ROOTS ARE IMAGINARY:\n");
disc=-disc;
img=(float)disc/2*a;
real=(float)-b/2*a;
if (img>0)
{ printf("Root1=%f + i%f\n",real,img);
printf("Root2=%f - i%f\n",real,img);
}
else
{ img=-img;
printf("Root1=%f + i%f\n",real,img);
printf("Root2=%f - i%f\n",real,img);
}

}
return 0;
}
INPUT:
ENTER VALUES FOR a,b,c
1 4 4

GNI 38
Computer Programming Lab Manual

OUTPUT:
THE ROOTS ARE EQUAL AND THEY ARE.. Root1=-2 Root2=-2

Week 3:

3 a)The total distance traveled by vehicle in t seconds is given by


distance=ut+1/2at2 where u and a are the initial velocity(m/sec) and
acceleration(m/sec2). Write C program to find the distance traveled at
regular intervals of time given the values of u and a. The program
should provide the flexibility to the user to select his own time intervals
and repeat the calculations for different values of u and a.
AIM:
To calculate s=u*t+1/2*a*t2

ALGORITHM:
Step 1: Start
Step 2: read a,u, t, t1, t2
Step 3: for i is t1, i less than or equal to t2 and i=i+t
Begin
Step 4: calculate s = u*i+1/2*a*i2
Step 5: Print i,s
End
Step6: Stop

FLOWCHART:
Start

Read a,u,
t, t1, t2

i=0 i<=n
i++

S=u*i+1/2*a*i2

Print i, s

Stop
GNI 39
Computer Programming Lab Manual

PROGRAM:
#include<stdio.h>
#include<math.h>
void main()
{
int a,u,t,t1,t2,i;
float s;
clrscr();
printf("ENTER THE VALUES OF a,u,t,t1,t2:");
scanf("%d%d%d%d%d",&a,&u,&t,&t1,&t2);
for(i=t1;i<=t2;i=i+t) // performing the looping operation for time intervals
{
s=(u*i)+(0.5*a*i*i); // calculate the total distance
printf("\n\nthe distance travelled in %d seconds is %f ",i,s);
}
getch();
}

Input:
ENTER THE VALUES OF a,u,t,t1,t2:
1 2 3 1 5
Output:
the distance travelled in 1 seconds is 2.500000

3. 3 b) Write a C program which takes two integer operands and one


operator from the user, performs the operation and then prints the
result.(Consider the operators +,-,*,/,% and use Switch Statement.)

AIM:
To perform arithmetic operations using switch statement.
ALGORITHM:
Step 1: Read a,b
Step 2: Print Menu Options
Step 3: do
Begin
Step 4: Read ch
Step 5: switch(ch)

GNI 40
Computer Programming Lab Manual

Begin
Step 6: case 1:
Begin
Calculate c = a+b
Print c
break;
End
case 2:
Begin
Calculate c = a-b
Print c
break;
End
case 3:
Begin
Calculate c = a*b
Print c
break;
End
case 4:
Begin
Calculate c = a/b
Print c
break;
End
case 5:
Begin
Calculate c = a%b
Print c
break;
End

default:Print Invalid choice


End
End

GNI 41
Computer Programming Lab Manual

FLOWCHART:

Start

Read
a,b,ch

switch(ch)

c=a+b c=a-b c=a*b c=a/b c=a%b

Print c

Stop
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,ch;
clrscr();
printf("ENTER TWO VALUES FOR a & b\n");
scanf("%d %d",&a,&b);
while(1)
{
printf("MENU OPTIONS \n");
printf("************\n");
printf("1.Addition\n");
printf("2.Subtraction\n");
printf("3.Multiplication\n");
printf("4.Division\n");
printf("5.Modulus\n");
printf(6.Exit\n);
printf("\n");
printf("ENTER UR CHOICE\n");
scanf("%d",&ch);
switch(ch)
{

GNI 42
Computer Programming Lab Manual

case 1: c=a+b;
printf("The addition of %d and %d is..%d\n",a,b,c);
break;
case 2: c=a-b;
printf("The subtraction of %d and %d is..%d\n",a,b,c);
break;
case 3: c=a*b;
printf("The multiplication of %d and %d is..%d\n",a,b,c);
break;

case 4: c=a/b;
printf("The division of %d and %d is..%d\n",a,b,c);
break;
case 5: c=a%b;
printf("The modulus of %d and %d is..%d\n",a,b,c);
break;
case 6:exit(0);
default:printf("INVALID CHOICE\n");
}
}

getch();
}

INPUT:
ENTER TWO VALUES FOR a & b:
20 16

OUTPUT:
MENU OPTIONS
***************
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Modulus
6.Exit

ENTER UR CHOICE
1
The addition of 20 and 16 is..36

ENTER UR CHOICE
2
The subtraction of 20 and 16 is..4

ENTER UR CHOICE
3
GNI 43
Computer Programming Lab Manual

The multiplication of 20 and 16 is..320

ENTER UR CHOICE
4
The division of 20 and 16 is..1

ENTER UR CHOICE
5
The modulus of 20 and 16 is..4

ENTER UR CHOICE 6

Week4:

4.a) Write a C program to find the factorial of a given integer using


non-recursive function.

AIM:
To find the factorial of a given number using non-recursive function.
ALGORITHM:
Step 1: Start
Step 2: Read n
Step 3: Call fact(n) goto step 6
Step 4: Store result in f
Step 5: Print f goto step 10
Step 6: Begin //sub program
Initialize f 1
Step 7: for i is 1 to n by step 2
Step 8: Calculate f = f*i
Step 9: return f
End
Step 10: Stop

GNI 44
Computer Programming Lab Manual

Start
FLOWCHART:

Read n

f = fact(n)

f=1
Print f

For i is 1 to n by
Step 1

FALSE
Stop TRUE
PROGRAM: f = f*i
#include<stdio.h>
#include<conio.h>
int fact(int);
void main()
{
int n,i,f;
clrscr();
printf("ENTER A VALUE FOR n:\n");
scanf("%d",&n);
f=fact(n);
printf("THE FACTORIAL OF A GIVEN NO IS..%d",f);
getch();
}
int fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
f=f*i;
return(f);
}
INPUT:
ENTER A VALUE FOR n
5
OUTPUT:THE FACTORIAL OF A GIVEN NUMBER IS..120

GNI 45
Computer Programming Lab Manual

4.b) Write a C program to find the factorial of a given integer using


recursive function.

AIM:
To find the factorial of a given number using recursive function.

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

Sub program:
Step 1: initialize the f
Step 2: if n= = 0 or n == 1 return 1 to main program if not goto step 3
Step 3: return n*fact(n-1) to main program
FLOW CHART:

Main Program Sub Program

Start

Fact ()

Read n
False
If n=0 || n=1

Call subprogram
F = fact(n) True
Return
n*fact(n-1)

Print f

Return n to
main program
Stop

GNI 46
Computer Programming Lab Manual

PROGRAM:
#include<stdio.h>
#include<conio.h>
int fact(int);
void main()
{
int n,res;
clrscr();
printf("ENETR A NUMBER:\n");
scanf("%d",&n);
res=fact(n);
printf("THE FACTORIAL OF A GIVEN NUMBER IS..%d",res);
getch();
}
int fact(int n)
{
int r;
if(n==0)
return(1);
else
{
r=n*fact(n-1);
return(r);
}
}

INPUT:
ENTER A VALUE FOR n
5

OUTPUT:
THE FACTORIAL OF A GIVEN NUMBER IS..120

4.b)i) Write a C program to find the GCD of two given integers by


using the recursive function

Aim: To find the Gcd of two given integers by using the recursive function

Algorithm:

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

GNI 47
Computer Programming Lab Manual

Sub program: GCD(n,m)


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

Flow CHART:

Main Program:
Start

Read a,b

Call sub program


G=gcd(a,b)

Print gcdvalue

Stop

Program:
#include<stdio.h>
#include<conio.h>
int gcdrecursive(int m,int n)
{
if(n>m)
return gcdrecursive(n,m);
if(n==0)
return m;
else
return gcdrecursive(n,m%n); // return to the main program
}
void main()
{
int a,b,igcd;
clrscr();
printf("enter the two numbers whose gcd is to be found:");
scanf("%d%d",&a,&b);
printf("GCD of a,b is %d",gcdrecursive(a,b)); // return to the sub program
getch();
}

GNI 48
Computer Programming Lab Manual

Input:
Enter the two numbers whose gcd is to be found: 5 25

Output:
GCD of a,b is : 5

4 B ii) Write a C program to find the GCD of two given integers using
non-recursive function.

To find the GCD of two given integers by using the non 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:
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: initialize the p=1, q, remainder


Step 2: remainder=p-(p/q*q)
Step 3: remainder=0 return q else goto step 4
Step 4: GCD(q,remainder) return to main program

Flowchart:

Program:
GNI 49
Computer Programming Lab Manual

#include<stdio.h>
#include<conio.h>
#include<math.h>
int gcdnonrecursive(int m,int n)
{
int remainder;
remainder=m-(m/n*n);
if(remainder==0)
return n;
else
gcdnonrecursive(n,remainder);
}

void main()
{
int a,b,igcd;
clrscr();
printf("enter the two numbers whose gcd is to be found:");
scanf("%d%d",&a,&b);
printf("GCD of %d",gcdnonrecursive(a,b));
getch();
}

Output:
1. enter the two numbers whose gcd is to be found:5,25
GCD of a,b is : 5

WEEK 5:
5. a) Write a C program to find both the largest and smallest
number in a list of integers.

AIM:
To find the largest and smallest number in a list of integers.
ALGORITHM:

Step 1: start
Step 2: read n
Step 3: initialize i=0
Step 4: if i<n do as follows. If not goto step 5
Read a[i]
Increment i

GNI 50
Computer Programming Lab Manual

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

Program:
#include<stdio.h>
#include<conio.h>
void main()
{ int a[10],i,n,small,large;
clrscr();
printf("Enter The Array Size:");
scanf("%d",&n);
printf("ENTER ELEMENTS OF ARRAY");
for(i=0;i<n;i++) // read the elements of an array
scanf("%d",&a[i]);
small=a[0];
large=a[0];
for(i=0;i<n;i++)// read the elements of an array
{ if(a[i]<small)// check the condition for minimum value
small=a[i];
if(a[i]>large)//check the condition for maximum value
large=a[i];
}
printf("largest value is:%d\n",large);
printf("smallest value is:%d\n",small);

GNI 51
Computer Programming Lab Manual

getch();
}
INPUT:
Enter The Array Size:10
ENTER THE ELEMENTS OF ARRAY
7 10 9 8 6 5 2 3 4 1
OUTPUT:
largest value is : 10
smallest value is : 1

5. b)i) Write a C program to perform addition of two matrices.

AIM:
To perform addition of two matrices.
ALGORITHM:
Step 1: Start
Step21: for i is 0 to 2 by step 1
for j is 0 to 2 by step 1
Step 3: Read a[i][j],b[i][j]
Step 4: goto step 2
Step 5: calculate c[i][j]=a[i][j]+b[i][j]
Step 6: goto step 2
Step 7: Print c[i][j]
Step 8: Stop

GNI 52
Computer Programming Lab Manual

Flow Chart:
Start

For i=0;i<3;i++ F
For j=0;j<3;j++
T

Read a[i][j], b[i][j]

For i=0;i<3;i++
For j=0;j<3;j++
F
T
c[i][j]=a[i][j]+b[i][j]

For i=0;i<3;i++
For j=0;j<3;j++

T
Print c[i][j] Stop

PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3];
int i,j;
clrscr();
printf("ENTER A MATRIX\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
}
printf("ENTER B MATRIX\n");
GNI 53
Computer Programming Lab Manual

for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
}
printf(" After addition of two matrices :\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}

INPUT:
ENTER a MATRIX
1 2 3
4 5 6
7 8 9
ENTER b MATRIX
1 1 1
1 1 1
1 1 1

OUTPUT:
After addition of two matrices is..
2 3 4
5 6 7
8 9 10

GNI 54
Computer Programming Lab Manual

5. b)ii) Write a C program to multiplication of two matrices

AIM:
To perform multiplication of two matrices.
ALGORITHM:
Step 1: Start
Step21: for i is 0 to 2 by step 1
for j is 0 to 2 by step 1
Step 3: Read a[i][j],b[i][j]
Step 4: goto step 2
Step 5: calculate c[i][j]=a[i][j]+b[i][j]
Step 6: goto step 2
Step 7: Print c[i][j]
Step 8: Stop

GNI 55
Computer Programming Lab Manual

PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3];
int i,j;
clrscr();
printf("ENTER A MATRIX\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
}
printf("ENTER B MATRIX\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
}
printf("The addition of two matrices is..\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}

INPUT:
ENTER a MATRIX
1 2 3
4 5 6
7 8 9
ENTER b MATRIX
1 1 1
1 1 1
1 1 1

OUTPUT:

GNI 56
Computer Programming Lab Manual

The addition of two matrices is..


2 3 4
5 6 7
8 9 10

Week 6:

6. Write a C program that uses functions to perform the following


operations:
a. To insert a sub-string in to given main string from a given
position.
Aim:
To insert a string into another string from a specified position.
Flow Chart :

Algorithm:
Step 1: start

GNI 57
Computer Programming Lab Manual

Step 2: read main string and sub string


Step 3: find the length of main string(r)
Step 4: find length of sub string(n)
Step 5: copy main string into sub string
Step 6: read the position to insert the sub string( p)
Step 7: copy sub string into main string from position p-1
Step 8: copy temporary string into main string from position p+n-1
Step 9: print the strings
Step 10: stop

Program:
#include<stdio.h>
#include<string.h>
main()
{
char a[3qq0],b[30],c[30];
int pos=0,i=0,l,la,lb,lc,j;
puts("Enter a string");
gets(a);
puts("Enter sub string");
gets(b);
puts("enter position for insertion");
scanf("%d",&pos);
la=strlen(a);
lb=strlen(b);
l=pos+lb;
lc=la+lb;
for(i=0;i<pos;i++)
{
c[i]=a[i];
}
j=0;
for(i=pos;i<=l;i++)
{
c[i]=b[j];
j++;
}
j=pos;
for(i=l;i<lc;i++)
{
c[i]=a[j];
j++;
}
c[i]='\0';
puts("String after Insertion is:");
printf("%s",c);
}
Input:
Enter First String:

GNI 58
Computer Programming Lab Manual

Comer
Enter Second String:
put

Output:
Enter the position where the item has to be inserted:3

Computer

6. a)ii) To delete n Characters from a given position in a given string.

Aim: To delete n Characters from a given position in a given string.

Algorithm:
Step 1: start
Step 2: read string
Step 3: find the length of the string
Step 4: read the value of number of
characters to be deleted and positioned
Step 5: string copy part of string from
position to end, and
(position + number of characters to
end)
Step 6: stop
Flow Chart:

Program:
#include<stdio.h>
#include<string.h>

GNI 59
Computer Programming Lab Manual

main()
{
char a[30],c[30];
int pos=0,i=0,L,La,j,n;
puts("Enter a string");
gets(a);
puts("enter position for deletion");
scanf("%d",&pos);
puts("Enter number of characters to be deleted");
scanf("%d",&n);
La=strlen(a);
L=pos+n;
for(i=0;i<pos;i++)
{
c[i]=a[i];
}
j=pos;
for(i=L;i<=La;i++)
{
c[j]=a[i];
j++;
}
puts("String after Deletion is:");
printf("%s",c);
}

Input:
Enter the string
Raviraju

Enter the position from where to delete:2


Enter the number of characters to be deleted 4
Output:
Raju

6. b) Write a C program to determine if the given string is palindrome or not.

Aim: To determine if the given string is palindrome or not.


Description :
Palindrome means string on reversal should be same as original
Ex: madam on reversal is also madam
Algorithm:
Step 1: start
Step 2: read string A
Step 3: copy string A into B
Step 4: reverse string B
Step 5: compare A &B
If A equals B to got step 6

GNI 60
Computer Programming Lab Manual

Else goto step 7


Step 6:print given string A is pallindrom
Step 7:print given string is not pallindroma
Step 8: stop

Flow Chart:

PROGRAM:
#include<stdio.h>
#include<string.h>
int main()
{
char a[30],b[30];
int pos=0,i=0,l,la,j,n;
puts("Enter a string");
gets(a);
strcpy(b,a);
strrev(b);
if(strcmp(a,b)==0)
printf("Pallindrome");
else
printf("Not Pallindrome") ;
return 0;
}

GNI 61
Computer Programming Lab Manual

Week 7:

7. a) Write a C program that displays the position or index in the string S


where the string T begins, or - 1 if S doesn't contain T.

Aim: To display the position or index in the string S where the string T begins,
or - 1 if S doesn't contain T

Algorithm:
Step 1: start
Step 2: read the string and then displayed
Step 3: read the string to be searched and then displayed
Step 4: searching the string T in string S and then perform the following steps
i. found=strstr(S,T)
ii. if found print the second string is found in the first string at the
position. If not goto step 5
Step 5: print the -1
Step 6: stop

Flow Chart:
Start

initialize s[],t[], found vars

Read First String

Display string

Read string to be searched

Display the string

Found = strstr(s,t)

No if found Yes

Print -1 print the string


Found s

Stop

GNI 62
Computer Programming Lab Manual

Program:
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char s[30], t[20];
char *found;
clrscr();
/* Entering the main string */
puts("Enter the first string: ");
gets(s);
/* Entering the string whose position or index to be displayed */
puts("Enter the string to be searched: ");
gets(t);
/*Searching string t in string s */
found=strstr(s,t);
if(found)
printf("Second String is found in the First String at %d position.\n",found-s);
else
printf("-1");
getch();
}

Input:
Enter the first string:
computer
Enter the string to be seareched:
mp

Output:
Second string is found in the first string at 2 position

GNI 63
Computer Programming Lab Manual

7. b) Write a C program to count the number of lines, words and


characters in a given text.

AIM:
To count the number of lines, words and characters in a given list.
ALGORITHM:
Step 1: Start
Step 2: Read the text until an empty line
Step 3: Compare each character with newline char \n to count no of lines
Step 4: Compare each character with tab char \t\ or space char to count no
of words
Step 5: Compare first character with NULL char \0 to find the end of text
Step 6: No of characters = length of each line of text
Step 7: Print no of lines, no of words, no of chars
Step 8: Stop

Flow Chart:
Start

Initialize end=0,chars=0,words=0,lines=0

While
End==0
true
C=0

false
If (ctr=getchar())!=\n

True Line[c]=\0
Line[c++]=ctr

true If line[0]=\0

Print lines, false


Words,chars i=0 Words ++
i++ line[i]!=\0
stop T F
If line[i]== || Lines++
Line[i]==\t Chars+=strlen(line)

Words ++

GNI 64
Computer Programming Lab Manual

PROGRAM:
#include <stdio.h>
void main()
{
char line[81], ctr;
int i,c,
end = 0,
characters = 0,
words = 0,
lines = 0;
printf("TYPE ANY TEXT.\n");
printf("GIVE ONE SPACE AFTER EACH WORD.\n");
while( end == 0)
{
/* Reading a line of text */
c = 0;
while((ctr=getchar()) != '\n')
line[c++] = ctr;
line[c] = '\0';
/* counting the words in a line */
if(line[0] == '\0')
break ;
else
{
words++;
for(i=0; line[i] != '\0';i++)
if(line[i] == ' ' || line[i] == '\t')
words++;
}
/* counting lines and characters */
lines = lines +1;
characters = characters + strlen(line);
}
printf ("\n");
printf("Number of lines = %d\n", lines);
printf("Number of words = %d\n", words);
printf("Number of characters = %d\n", characters);
}

INPUT:
TYPE ANY TEXT
GIVE ONE SPACE AFTER EACH WORD.
Ramu is a good boy.

OUTPUT:
THE NUMBER OF CHARACTERS IN A GIVEN TEXT IS..18
THE NUMBER OF WORDS IN A GIVEN TEXT IS..5
THE NUMBER OF LINES IN A GIVEN TEXT IS..1

GNI 65
Computer Programming Lab Manual

Week 8:
8. a) Write a C program to generate Pascals triangle.

AIM: To generate Pascals triangle.


ALGORITHM:
Step 1: Start
Step 2: Read r
Step 3: Initialize b=1, q=0
Step 4: while q<=r
Begin
Step 5: for(p=30-3*q;p>0;p--)
Step 6: for(x=0;x<=q;x++)
Begin
Step 7: if x==0 or q==0
Step 8: Initialize b = 1
Step 9: else b=(b*(q-x+1)/x);
Step 10:Print b
End
Step 11:q=q+1
End
Step12: Stop
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int b,p,q,r,x;
clrscr();
printf("ENTER NUMBER OF ROWS\n");
scanf("%d",&r);
b=1;
q=0;
while(q<r)
{ for(p=30-3*q;p>0;p--)
printf(" ");
for(x=0;x<=q;x++)
{
if(x==0||q==0)
b=1;
else
b=(b*(q-x+1)/x);
printf(" %d",b);
}
printf("\n");
q++;
}
getch();
}

GNI 66
Computer Programming Lab Manual

INPUT:
ENTER NUMBER OF ROWS 5

OUTPUT:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

GNI 67
Computer Programming Lab Manual

8. b) Write a C program to construct a pyramid of numbers


as shown below.

AIM: To construct a pyramid of numbers

ALGORITHM:
Step 1: Start
Step 2: Read n
Step 3: i:=0
Step 4: if(i<n) goto step 5
else goto step 15
Step 5: k=n
Step 6: if(k>i) goto step 7
else goto step 10
step 7:print blank
step 8:k:=k-1
step 9:goto step 6
step 10:j=1;
step 11:if(<=i) goto step 12
else goto step 15
step12:print j
step 13:j:=j+1
step 14: goto step 11
step 15:stop

PROGRAM:

#include<stdio.h>
int main()
{
int i,n,j,k;
printf("Enter how many rows to be printed: ")
scanf(" %d",&n);
for(i=0;i<n;i++)
{
for(k=n;k>i;k--)
printf(" ");
for(j=1;j<=i;j++)
{
printf("%2d",j);
}
printf("\n");
}
return 0;
}

GNI 68
Computer Programming Lab Manual

INPUT:
ENTER NUMBER OF ROWS 5
OUTPUT:
1
12
123
1234

GNI 69
Computer Programming Lab Manual

Week 9:

9. Write a C program to read in two numbers, x and n, and then compute the
sum of this geometric progression.

AIM:
To compute the sum of geometric progression.
Description:
ALGORITHM:
Step 1: Read x,n
Step 2: Initialize sum 1
Step 3: Read x,n
Step 4: for i is 1 to n by step 1
Step 5: Calculate sum=sum+pow(x,i)
Step 6: Print sum

PROGRAM:
#include<stdio.h>
int main()
{
float x,sum;
int n,i;
printf("Enter no of terms");
scanf("%d",&n);
printf("Enter value for X");
scanf("%f",&x);
sum=1;
for(i=1;i<n;i++)
{
sum=sum+x;
x=x*x;
}
printf("Sum of the series upto %d terms is%f\n ",n,sum);
return 0;
}

Run 1
Enter no of terms5
Enter value for X1
Sum of the series upto 5 terms is 5.000000

GNI 70
Computer Programming Lab Manual

Week 10:

10. a) 2s complement of a number is obtained by scanning it from right to


left and complementing all the bits after the first appearance of a 1.
Thus 2s complement of 11100 is 00100.
Write a C program to find the 2s complement of a binary number.

Aim: To convert the given binary number to 2s complement


Description: calculation of 2s complement is as follows
Take a binary number and find its complement and add 1 to it to get 2s
complement
n=1111
1s=0000
Add 1 to 1s complement to get 2s complement
0000
+1
---------------
0001
----------------
Algorithm:
Main program
Step 1: Start
Step 2: declare the subprogram complement(char *a)
Step 3: initialize the variable i
Step 4: read the binary number
Step 5: perform the loop operation. if it is true then follows. if not goto step 7
i)for(i=0;a[i]!=\0;i++)
ii)if(a[i]!=0&&a[i]!=1) then displayed the number is not valid.
enter the correct number.
iii)Exit the loop
Step 6: call sub program complemt(a)
Step 7: stop

Sub program:

Step 1: initialize the variable I,c=0,b[160


Step 2: 1=strlen(a)
Step 3: perform the loop operation. if it is true then follows. if not goto
i)for(i=l-1;i>=0;i--)
ii)if(a[i]==0) then b[i]=1 else
iii)b[i]=0
Step 4: for(i=l-1;i>=0;i--) is true

GNI 71
Computer Programming Lab Manual

i)if(i==l-1) then
ii)if(b[i]==0) then b[i]=1 else
iii)b[i]=0,c=1 if not goto step 5
Step 5: if(c==1&&b[i]==0) is true then
i)b[i]=1, c=0 if not goto Step 6
Step 6: if(c==1&&b[i]==1) then b[i]=0,c=1
Step 7: displayed b[l]=\0
Step 8: print b and return to main program
Program:
#include <stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void complement (char *a);/*function proto typing */
int main()
{
char a[16];
int i;
printf("Enter the binary number");
gets(a);
for(i=0;a[i]!='\0'; i++)
{
if (a[i]!='0' && a[i]!='1')
{
printf("The number entered is not a binary number. Enter the correct number");
exit(0);
}
}
complement(a);
getch();
return 0;
}

void complement (char *a)


{
int L, i, c=0;
char b[16];
L=strlen(a);
for (i=L-1; i>=0; i--)
{
if (a[i]=='0')
b[i]='1';
else

GNI 72
Computer Programming Lab Manual

b[i]='0';
}
for(i=L-1; i>=0; i--)
{
if(i==L-1)
{
if (b[i]=='0')
b[i]='1';
else
{
b[i]='0';
c=1;
}
}
else
{
if(c==1 && b[i]=='0')
{
b[i]='1';
c=0;
}
else if (c==1 && b[i]=='1')
{
b[i]='0';
c=1;
}
}
}
b[L]='\0';
printf("The 2's complement is %s", b);
}

Run 1:
Enter the binary number1111
The 2's complement is 0001

GNI 73
Computer Programming Lab Manual

10. b) Write a C program to convert a Roman numeral to its decimal


equivalent.

Aim: To convert roman number to its decimal equivalent


Algorithm:
Step 1: Start
Step 2: read the roman numerical as string
Step 3: find length of roman numerical
Step 4: for each charcter in the string
i)if(char=I) then decimal=1
ii)if(char=V) then decimal=5
iii)if(char=X) then decimal=10
iv)if(char=L) then decimal=50
v)if(char=C) then decimal=100
vi)if(char=D) then decimal=500
vii)if(char=M) then decimal=1000
viii) otherwise invalid character
Step 5: repeat step 4 until the length of the string
Step 6: k=char[length-1]
Step 7: for each character of decimal string
i)if(decimal[i]>dec[i-1]) then k=k-decimal[i-1]
ii)else if(decimal[i]=decimal[i-1 or decimal[i]<decimal[i-1) then
k=k+decimall[i-1]
Step 8: repate step 7 until the length of decimal string
Step 9: print decimal value
Step 10: Stop

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int *a,len,i,j,k;
char *rom;
printf("Enter the Roman Numeral:");
scanf("%s",rom);
len=strlen(rom);
for(i=0;i<len;i++)
{
if(rom[i]=='I')
a[i]=1;
else if(rom[i]=='V')
a[i]=5;

GNI 74
Computer Programming Lab Manual

else if(rom[i]=='X')
a[i]=10;
else if(rom[i]=='L')
a[i]=50;
else if(rom[i]=='C')
a[i]=100;
else if(rom[i]=='D')
a[i]=500;
else if(rom[i]=='M')
a[i]=1000;
else
{
printf("\nInvalid Value");
exit(0);
}
}
k=a[len-1];
for(i=len-1;i>0;i--)
{
if(a[i]>a[i-1])
k=k-a[i-1];
else if(a[i]==a[i-1] || a[i]<a[i-1])
k=k+a[i-1];
}
printf("\nIts Decimal Equivalent is:");
printf("%d",k);
getch();
return 0;
}

GNI 75
Computer Programming Lab Manual

Week 11:

Write a C program that uses functions to perform the following operations:


i) Reading a complex number
ii) Writing a complex number
iii) Addition of two complex numbers
iv) Multiplication of two complex numbers

AIM: To perform arithmetic operations on complex numbers


Complex numbers of type a+ib
Addition: (a+ib)+(x+iy)=a+x+i(b+y)
Subtraction: (a+ib)-(x+iy)=a-x+i(b-y)
Multiplication: (a+ib)*(x+iy)= ax-by+i(ay+bx)
Division
(a+ib)/(x-iy) = * = = =

ALGORITHM:
Step 1:start
Step 2: Read Two complex numbers c1 ,c2
Step 3: c3=c1+c2
Step 4:print c3
Step 5: c3=c1-c2
Step 6: print c3
Step 7: c3=c1*c2
Step 8: print c3
Step 9: c3=c1/c2
Step 10: print c3
Step 11:print c
Step 12:stop

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct complex
{
float real,img;
};

/*code for reading complex number*/


struct complex read_complex()
{
struct complex c;
printf("enter real part of complex number");
GNI 76
Computer Programming Lab Manual

scanf("%f",&c.real);
printf("enter Imaginary part of complex number");
scanf("%f",&c.img);
return c;
}

/*code for adding complex numbers*/


struct complex add_complex(struct complex c1,struct complex c2)
{
struct complex c3;
c3.real=c1.real+c2.real;
c3.img=c1.img+c2.img;
return c3;
}

/*code for subtraction of complex numbers*/


struct complex sub_complex(struct complex c1,struct complex c2)
{
struct complex c3;
c3.real=c1.real-c2.real;
c3.img=c1.img-c2.img;
return c3;
}

/*code for multiplication of complex numbers*/


struct complex mul_complex(struct complex c1,struct complex c2)
{
struct complex c3;
c3.real=c1.real*c2.real-c1.img*c2.img;
c3.img= c1.img*c2.real+c2.img*c1.real;
return c3;
}

/*code for division of complex numbers*/


struct complex div_complex(struct complex c1,struct complex c2)
{
struct complex c3;
c3.real= (c1.real*c2.real+c1.img*c2.img)/(c2.real*c2.real+c2.img*c2.img);
c3.img= (c1.img*c2.real-c1.real*c2.img)/(c2.real*c2.real+c2.img*c2.img);
return c3;
}

/*code for display of complex number*/


void display_complex(struct complex c)
{
char sign;
printf("The result is:");
if(c.img<0)
{
sign='-';

GNI 77
Computer Programming Lab Manual

c.img=-c.img;
}
else
sign='+';
printf("%5f%ci%5f",c.real,sign,c.img);

int main()
{
int choice;
struct complex a,b,c;
while(1)
{
printf("\n---------------------------------\n");
printf("|Menu for operation complex numbers|\n ");
printf("----------------------------------\n");
printf("1.Addition \n ");
printf("2.Subtraction \n ");
printf("3.Multiplication \n ");
printf("4.Division \n ");
printf("5.Clear Screen \n ");
printf("6.Exit Menu \n ");
printf("Enter Your Choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("You Have Selected Addition operation on complex NUmbers\n");
printf("Enter First complex number\n");
a=read_complex();
printf("Enter Second complex Number\n");
b=read_complex();
c=add_complex(a,b);
display_complex(c);
break;
case 2:printf("You Have Selected Subtraction operation on complex NUmbers\n");
printf("Enter First complex number\n");
a=read_complex();
printf("Enter Second complex Number\n");
b=read_complex();
c=sub_complex(a,b);
display_complex(c);
break;
case 3:printf("You Have Selected Multiplication operation on complex Numbers\n");
printf("Enter First complex number\n");
a=read_complex();
printf("Enter Second complex Number\n");
b=read_complex();
c=mul_complex(a,b);
display_complex(c);

GNI 78
Computer Programming Lab Manual

break;
case 4:printf("You Have Selected Division operation on complex Numbers\n");
printf("Enter First complex number\n");
a=read_complex();
printf("Enter Second complex Number\n");
b=read_complex();
c=div_complex(a,b);
display_complex(c);
break;
case 5: clrscr();
break;
case 6: exit(0);
default:printf("Invalid choice");
}
}

GNI 79
Computer Programming Lab Manual

Week 12:

12 a) Write a C program to copy the contents of one file to another.

Aim:
Program which copies one file to another

Algorithm:
Step 1: Start
Step 2: read command line arguments
Step 3: check if no of arguments =3 or not. If not print invalid no of arguments
Step 4: open source file in read mode
Step 5: if NULL pointer, then print source file can not be open
Step 6: open destination file in write mode
Step 7: if NULL pointer, then print destination file can not be open
Step 8 : read a character from source file and write to destination file until EOF
Step 9: Close source file and destination file
Step 10: Stop

Program:

GNI 80
Computer Programming Lab Manual

#include<stdio.h>
#include<process.h>
#include<conio.h>
void main()
{
FILE *ft,*fs;
int c=0;
clrscr();
fs=fopen("a.txt","r");
ft=fopen("b.txt","w");
if(fs==NULL)
{
printf("Source file opening error\n");
exit(1);
}
else
if(ft==NULL)
{
printf("Target file opening error\n");
exit(1);
}
while(!feof(fs))
{
fputc(fgetc(fs),ft);
c++;
}
printf("%d bytes copied from 'a.txt' to 'b.txt'",c);
c=fcloseall();
printf("%d files closed",c);
}

INPUT:
a.txt
An array is a collection of elements of similar datatypes

OUTPUT:
57 bytes copied from a.txt to b.txt
2 files closed

GNI 81
Computer Programming Lab Manual

12. b) Write a C program to reverse the first n characters in a file.


(Note: The file name and n are specified on the command line.)

Aim: To reverse the first n characters in a file


Algorithm:
Step 1: Start
Step 2: read the command line arguments
Step 3: check if arguments=3 or not
If not print invalid no of arguments
Step 4: open source file in read mode
Step 5: if NULL pointer, then print file can not be open
Step 6: Store no of chars to reverse in k
K= *argv[2]-48
Step 7: read the item from file stream using fread
Step 8: Store chars from last position to initial position in another string(temp)
Step 9: print the temp string
Step 10: Stop

Program:
GNI 82
Computer Programming Lab Manual

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <process.h>
void main(int argc, char *argv[])
{
char a[15];
char s[20];
char n;
int k;
int j=0;
int i;
int len;
FILE *fp;
if(argc!=3)
{
puts("Improper number of arguments.");
exit(0);
}
fp = fopen(argv[1],"r");
if(fp == NULL)
{
puts("File cannot be opened.");
exit(0);
}
k=*argv[2]-48;
n = fread(a,1,k,fp);
a[n]='\0';
len=strlen(a);
for(i=len-1;i>=0;i--)
{
s[j]=a[i];
printf("%c",s[j]);
j=j+1;
}
s[j+1]='\0';
getch();
}
Input:
source.c
this is source
ouput.c
this is source
Output: Command line arguments
source.c ouput.c
source.c
this is source
ecruos si siht

Week 13:

GNI 83
Computer Programming Lab Manual

13. a) write a c program to display the contents of a file.

Aim: To display the contents of a file.


Algorithm:
Step 1:
Step 2:
Program:

#include <stdio.h>
#include <conio.h>
#include<string.h>
#include <process.h>
int main()
{
FILE *fs;
char ch;
char *fname;

printf("Enter the file name :");


gets(fname);
fs = fopen(fname,"r");
if(fs==NULL)
{
puts("Source file cannot be opened.");
getch();
}
else
{
while((ch=fgetc(fs))!=EOF)
{

putchar(ch);

}
}
getch();
return 0;
}

Input:
Enter the file name :sample.txt
Output:
this is my first program

GNI 84
Computer Programming Lab Manual

13. b) Write a C program to merge two files into a third file (i.e., the contents of
the first file followed by those of the second are put in the third).

#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp1,*fp2,*fp3;
char file1[20],file2[20],file3[20],ch;
puts("Program to merge two files....\n");
puts("Enter first file name:");
gets(file1);
puts("Enter Second file name:");
gets(file2);
puts("Enter Destination file name:");
gets(file3);
fp1=fopen(file1,"r");
fp2=fopen(file2,"r");
fp3=fopen(file3,"w");
if(fp1==NULL&&fp2==NULL)
printf("Error opening file1 and file2.....\n");
else
{
if(fp3==NULL)
printf("Error in creating destination file....\n");
else
{
while((ch=fgetc(fp1))!=EOF)
putc(ch,fp3);
while((ch=fgetc(fp2))!=EOF)
putc(ch,fp3);
}
printf("File Merging Sucessfull....");
fcloseall();
getch();
}
}

GNI 85
Computer Programming Lab Manual

Week 14:

14 a) Write a C program that uses non recursive function to search for


a Key value in a given list of integers using Linear search.

AIM: To uses non recursive function to search for a Key value in a given list
of integers using Linear search.
Description:
Linear search or sequential search is a process of searching elements
in a array in linear fashion. Compare key with each element in the array . if
element if found its index is returned else -1 is returned to indicate that
element is not found

ALGORITHM:
Step 1. Start
Step 2. Read the value of n
Step 3. for i=1 to n increment in steps of 1
Read the value of ith element into array
Step 4. Read the element(b) to be searched
Step 5. c<--lsearch(a,n,b)
Step 6. if c equal to 0 goto step 7 otherwise goto step 8
Step 7. print unsuccessful search
Step 8. print successful search
Step 9. stop

lsearch(k[],n,m)
step 1. start
step 2. for i=1 to n increment in steps of 1
step 3. if m equal to k[i] goto step 4 otherwise goto step 2
step 4. return i
step 5. return 0
step 6. Stop

GNI 86
Computer Programming Lab Manual

Linear search()

PROGRAM:
#include<stdio.h>
void lsearch(int list[],int n,int key);
void main()
{
int n,i,key,list[25];
clrscr();
printf("enter no of elements\n");
scanf("%d",&n);
printf("enter %d elements ",n);
for(i=0;i<n;i++)
scanf("%d",&list[i]);
printf("enter key to search");
scanf("%d",&key);
lsearch(list,n,key);
getch();
}
void lsearch(int list[],int n,int key)
{
int i,pos=-1;

GNI 87
Computer Programming Lab Manual

for(i=0;i<n;i++)
if(key==list[i])
{
pos=i;
break;
}
if(pos==-1)
printf("\nelement not found");
else
printf("\n element found at index %d",pos);
}

GNI 88
Computer Programming Lab Manual

14 b) Write a C program that uses non recursive function to search for a


Key value in a given sorted list of integers using Binary Search

Aim: To search for a key element using binary search


Description: For binary search to work, the item in the list must be in assorted order.
The approach employed in the binary search is divid and conquer. If the list to be sorted
for a specific item is not sorted, binary search fails.The given list is divided into two
halves and searched in the halves basing on key value. If key value is less than middle
element then searching is done in first half of the list else next half is searched

Algorithm:
BINARY SEARCH

step 1. Start
step 2. Read the value of n
step 3. for i=1 to n increment in steps of 1
Read the value of ith element into array
step 4. Read the element(x) to be searched
step 5. search<--binary(a,n,x)
step 6. if search equal to 0 goto step 7 otherwise goto step 8
step 7. print unsuccessful search
step 8. print successful search
step 9. stop

BINARY SEARCH FUNCTION

step 1. start
step 2. initialise low to 1 ,high to n, test to 0
step 3. if low<= high repeat through steps 4 to 9 otherwise goto step 10
step 4. assign (low+high)/2 to mid
step 5. if m<k[mid] goto step 6 otherwise goto step 7
step 6. assign mid-1 to high goto step 3
step 7. if m>k[mid] goto step 8 otherwise goto step 9
step 8. assign mid+1 to low
step 9. return mid
step 10. return 0
step 11.stop

Program:
#include<stdio.h>
void bsearch(int list[],int n,int key);
void main()
{
int n,i,key,list[25];
clrscr();
GNI 89
Computer Programming Lab Manual

printf("enter no of elements\n");
scanf("%d",&n);
printf("enter %d elements in ascending order ",n);
for(i=0;i<n;i++)
scanf("%d",&list[i]);
printf("enter key to search");
scanf("%d",&key);
bsearch(list,n,key);
getch();
}

void bsearch(int list[ ],int n,int key)


{
int mid,first=0,pos=-1,last=n-1;
while(first<=last)
{
mid=(first+last)/2;
if(key==list[mid])
{
pos=mid;
break;
}
else if(key<list[mid])
last=mid-1;
else
first=mid+1;
}
if(pos==-1)
printf("element not found");
else
printf("element found at index %d",pos);
}

GNI 90
Computer Programming Lab Manual

Week 15:

15 a) Write a C program that implements the Selection sort method to


sort a given array of integers in ascending order.

AIM: implements the Selection sort method to sort a given array of integers
Description:
This is the simplest method of sorting. In this method, to sort the data in
ascending order, the 0th element is compared with all other eements. If the 0th element is
found to be greater than the compared element then they are interchanged.

Algorithm:

step 1) Start
step 2) Initiliaze the variables I,j,temp and arr[]
step 3) Read the loop and check the condition. If the condition is true
print the array elements and increment the I value. Else goto step 4
step 4) Read the loop and check the condition. If the condition true
then goto next loop.
step 5) Read the loop and check the condition. If the condition true
then goto if condition
step 6) If the condition if(arr[i]>arr[j]) is true then do the following
steps
i) temp=arr[i]
ii) arr[i]=arr[j]
iii) arr[j]=temp
step 7) increment the j value
step 8) perform the loop operation for the displaying the sorted elements.
step 9) print the sorted elements
step 10) stop

GNI 91
Computer Programming Lab Manual

Program:
#include<stdio.h>
void selection_sort(int list[],int n);
void main()
{
int n,i,list[25];
clrscr();
printf("enter no of elements\n");
scanf("%d",&n);
printf("enter %d elements ",n);
for(i=0;i<n;i++)
scanf("%d",&list[i]);
selection_sort (list,n);
printf("elements after sorting\n");
for(i=0;i<n;i++)
printf("%3d\n",list[i]);
getch();
}

GNI 92
Computer Programming Lab Manual

void selection_sort (int list[],int n)


{
int min,temp,i,j;
for(i=0;i<n;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(list[j]<list[min])
min=j;
}
temp=list[i];
list[i]=list[min];
list[min]=temp;
}
}

GNI 93
Computer Programming Lab Manual

15 b)Write a C program that implements the Bubble sort method to


sort a given list of names in ascending order.

AIM: Bubble sort method to sort a given list of names in ascending order.

DESCRIPTION:
Bubble sort is the simplest and oldest sorting technique. This method takes two
elements at a time. It compare these two elements. If first elements is less than second
one, they are left undistrurbed. If the first element is greater then second one then they are
swapped. The procedure continues with the next two elements goes and ends
when all the elements are sorted.
But bubble sort is an inefficient algorithm. The order of
bubble sort algorithm is O(n2)

ALGORITHM:
Bubble Sort:

step 1. start
step 2. read the value of n
step 3. for i= 1 to n increment in steps of 1
Read the value of ith String into array
step 4. call function to sort (bubble_sort(a,n))
step 5. for i= 1 to n increment in steps of 1
print the value of ith String in the array
step 6. stop

BUBBLE SORT FUNCTION

step 1. start
step 2. initialise last to n
step 3. for i= 1 to n increment in steps of 1
begin
step 4. initialise ex to 0
step 5. for i= 1 to last-1 increment in steps of 1
begin
step 6. if k[i]>k[i+1] goto step 7 otherwise goto step 5
begin
step 7. assign k[i] to temp
assign k[i+1] to k[i]
assign temp to k[i+1]
increment ex by 1
end-if
end inner for loop
step 11. if ex!=0
assign last-1 to last
end for loop
step 12. stop.

GNI 94
Computer Programming Lab Manual

PROGRAM:

#include<stdio.h>
#include<string.h>
#include<conio.h>
void bubble_sort(char list[ ][30],int n);
int main()
{
int n,i;
char list[25][30];
printf("enter no of elements\n");
scanf("%d",&n);
printf("enter %d elements ",n);
for(i=0;i<n;i++)
scanf("%s",&list[i]);
bubble_sort (list,n);
printf("List of names after sorting\n");

GNI 95
Computer Programming Lab Manual

for(i=0;i<n;i++)
printf("%s\n",list[i]);
getch();
return 0;
}
void bubble_sort (char list[ ][30],int n)
{
char temp[30];
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n-1;j++)
if(strcmp(list[j],list[j+1])>0)
{
strcpy(temp,list[j]);
strcpy(list[j],list[j+1]);
strcpy(list[j+1],temp);
}
}

GNI 96
Computer Programming Lab Manual

Week 16:

16. Write a C program that uses functions to perform Various


operations on singly linked list.

AIM: To perform Various operations on singly linked list.


Description:
In this program we have to create a single linked list, insert the elements into that
list ,delete the some elements from that list and then perform the sorting operation and
traversal operation on that created linkedlist

Various operation on single linked list

Algorithm :
Step 1: Start
Step 2: Declare a structure named linked-list
Step 3: Declare the pointers next, first, fresh, ptr
Step 4: Print main menu
Step 5: Read choice
Step 6: Switch(choice)
Step 7: If(choice==1)
7.1 Assign fresh=malloc(size of (node))
7.2 Read the element fresh->data
7.3 Read the choice where to insert
7.4:Switch(choice)
7.4.1: If choice==1
7..4.2: Call the function IBegin()
7.4.3: If choice==2

GNI 97
Computer Programming Lab Manual

7.4.4: Call the function Iend()


7.4.5: If choice==3
7.4.6: Call the function Imiddle()
Step 8: If(choice==2)
8.1: Read the position to delete
8.2: Switch(choice)
8.2.1: If choice==1
8..2.2: Call the function DBegin()
8.2.3: If choice==2
8.2.4: Call the function Dend()
8.2.5: If choice==3
8.2.6: Call the function Dmiddle()
Step 9: If choice==3
9.1 Call function view
114Step 10: If choice==4
10.1 Exit()
Step 11: Start insert function
Step 12: If(first==null)
Step 13: First->data=e
Step 14: First->next=null
Step 15: Else declare new node
Step 16:fresh->data=e
Step 17: If choice=1
Step 18: frsh->next=first
Step 19: first=fresh
Step 20:if choice=2
Step 21: ptr=first
Step 22: ptr->next=fresh
Step 23: fresh->next=full
Step 24: If choice =3
Step 25: Enter the position
Step 26:at p-1 node
Step 27: fresh->next= ptr->next
Step 28: ptr->next=fresh
Step 29: for delete function
Step 30: If first!=null
Step 31: Enter the position to delete
Step 32: If choice=1
115Step 33: d=first->data
Step 34: first=first->next
Step 35: if choice=2
Step 36: ptr=first
Step 37: Traverse to last node
Step 38: d=ptr->next->data
Step 39: ptr ->next=ptr->next->next
Step 40: Print d value
Step 41: for function view
Step 42: for ptr=first and ptr!=null and ptr=ptr->next
Step 43: Print ptr->data
Step 44: End

GNI 98
Computer Programming Lab Manual

PROGOGRAM:

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct lnode
{
int data;
struct lnode *next;
};
typedef struct lnode * lptr;

/*function to create a node*/


lptr create_node()
{
lptr node;
node=(lptr)malloc(sizeof(struct lnode));
return node;
}

/*function to insert an element at end of list*/


lptr insert_end(lptr head,int x)
{
lptr p,temp;
p=create_node();
p->data=x;
p->next=NULL;
if(head==NULL)
return p;
else
{
temp=head;
while(temp->next!=NULL)
temp=temp->next;
temp->next=p;
return head;
}
}

/*function to insert an element at front of existing list*/


lptr insert_front(lptr head,int x)
{
lptr p,temp;
p=create_node();
p->data=x;
p->next=NULL;
if(head==NULL)
return p;
else

GNI 99
Computer Programming Lab Manual

{
p->next=head;
head=p;
return head;
}
}

/*function to insert element after a node*/


lptr insert_after(lptr head,int x,int pos)
{
lptr p,temp,q;
int c=1;
p=create_node();
p->data=x;
p->next=NULL;
if(head==NULL)
return p;
else
{
temp=head;
while(c<=pos)
{
q=temp;
temp=temp->next;
c++;
}
q->next=p;
p->next=temp;
return head;
}
}

/* function to insert a node before a selected node*/


lptr insert_before(lptr head,int x,int pos)
{
lptr p,temp,q;
int c=1;
p=create_node();
p->data=x;
p->next=NULL;
if(head==NULL)
return p;
else
{ temp=head;
while(c<=(pos-1))
{
q=temp;
temp=temp->next;
c++;
}

GNI 100
Computer Programming Lab Manual

if(c==1)
{
p->next=head;
head=p;
}
else
{
q->next=p;
p->next=temp;
}
return head;
}
}

/*function to insert a node at end of list*/


lptr delete_end(lptr head)
{
lptr temp,prev;
temp=head;
if(head->next==NULL)
{
free(temp);
head=NULL;
return head;
}
else
{ while(temp->next!=NULL)
{
prev=temp;
temp=temp->next;
}
prev->next=NULL;
printf("\n %d is deleted from list",temp->data);
free(temp);
return head;
}
}

/*function to delete a node from front of list*/


lptr delete_front(lptr head)
{
lptr temp;
temp=head;
head=head->next;
printf ("\n%d is deleted",temp->data);
free(temp);
return(head);
}

GNI 101
Computer Programming Lab Manual

/*function to display data present in all nodes in a linked list*/


void display(lptr head)
{
lptr temp;
temp=head;
printf("\n\n");
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->next ;
}
}

*function to print number of nodes present in a linked list*/


int node_count(lptr head)
{
lptr temp;
int ncount=0;
temp=head;
while(temp!=NULL)
{
temp=temp->next;
ncount++;
}
return ncount;
}

void main()
{
lptr head=NULL;
int choice,item,pos;
while(1)
{
printf("enter choice \n1.insert end \n2.insert front \n3.insert after\n4.insert before\n");
printf("5.del end\n6.del front\n7.dislay\n8.node count \n9.clear screen\n10.exit");
scanf("%d",&choice);
switch(choice)
{
case 1 : printf("enter value into new node");
scanf("%d",&item);
head=insert_end(head,item);
printf("\n\nelement inserted at end");
break;
case 2 : printf("\n\nenter value into new node");
scanf("%d",&item);
head=insert_front(head,item);
printf("\n\nelement inserted at end");
break;
case 3 : printf("\nenter value into new node");

GNI 102
Computer Programming Lab Manual

scanf("%d",&item);
printf("\n\nenter position from 1 to %d",node_count(head));
scanf("%d",&pos);
head=insert_after(head,item,pos);
printf("\n\nelement inserted after %d pos",pos);
break;
case 4 : printf("enter value into new node");
scanf("%d",&item);
printf("\nenter position from 1 to %d",node_count(head));
scanf("%d",&pos);
head=insert_before(head,item,pos);
printf("\nelement inserted before %d pos",pos);
break;
case 5 : if(head==NULL)
printf("empty list");
else
head=delete_end(head);
break;
case 6 : if(head==NULL)
printf("empty list");
else
head=delete_front(head);
break;
case 7 : if(head==NULL)
printf("empty list");
else
display(head);
break;
case 8 : if(head==NULL)
printf("empty list");
else
printf("\nno of nodes are %d",node_count(head));
break;
case 9 : clrscr();
break;
case 10 : exit(0);
default : printf("invalid choice enter choice again ");
break;
}
}
}

Output:

GNI 103
Computer Programming Lab Manual

Week17:

17 .Write a C program that implements stack (its operations) using a singly linked
list to display a given list of integers in reverse order. Ex. input: 10 23 4 6 output:
6 4 23 10

DESCRIPTION:
In this program we have to implement the stack operation by using the arrays.
Here they stack operation are push and pop. Push operation is used to insert the elements
into a stack and pop operation is used to remove the elements in to a stack
ALGORITHM:
ALGORITHM FOR PUSH operation

Function Push(s,top,x)
Step 1: [Check for stack overflow]
If top>=n
Then printf(stack overflow)
Return
Step 2: [Increment Top]
Top<-top+1
Step 3: [ Insert element]
S[top]<-x
Step 4:[finished]
Return

ALGORITHM FOR POP OPERATION

Function POP(s,top)
Step 1: [Check for stack underflow]
If top=0
Then printf(stack underflow)
Exit
Step 2: [Decrement Top]
Top<-top-1
Step 3: [Return former top element of stack]
Return(S[top+1])
Step 4:[finished]
Return

GNI 104
Computer Programming Lab Manual

GNI 105
Computer Programming Lab Manual

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct stack
{
int data;
struct stack *next;
};
typedef struct stack * sptr;
sptr createnode()
{
sptr node;
node=(sptr)malloc(sizeof(struct stack));
return node;
}
sptr push(sptr head,int x)
{
sptr p,temp;
p=createnode();
p->data=x;
p->next=NULL;
if(head==NULL)
return p;
else
{
p->next=head;
head=p;
return head;
}
}
sptr pop(sptr head)
{
sptr temp;
temp=head;
head=head->next;
printf("%d is deleted",temp->data);
free(temp);
return(head);
}
void display(sptr head)
{
sptr temp;
temp=head;
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
}

GNI 106
Computer Programming Lab Manual

void main()
{
sptr top=NULL;
int choice,item;
clrscr();
while(1)
{
printf("\n--------------------------------\n");
printf("| MENU FOR OPERATIONS ON STACK |");
printf("\n--------------------------------\n");
printf("1.push\n2.pop\n3.display\n4.exit");
printf("\n-------------------------------\n");
printf("Enter Your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("\n enter element to push");
scanf("%d",&item);
top=push(top,item);
printf("element %d is pushed succesfully" ,item);
break;
case 2: if(top==NULL)
printf("stack is empty");
else
top=pop(top);
break;
case 3: if(top==NULL)
printf("stack is empty");
else
display(top);
break;
case 4: exit(0);
}
}
}

Output:

GNI 107
Computer Programming Lab Manual

Week 18:

18 Write a C program that implements Queue (its operations) using a


singly linked list to display a given list of integers in the same order. Ex.
input: 10 23 4 6 output: 10 23 4 6

Description:
In this program we have to implement the Queue operation by using the arrays.
Here they Queue operation are push and pop. Insert operation is used to insert the
elements into a Queue and Delete operation is used to remove the elements in to a Queue.

ALGORITHM:

ALGORITHM FOR INSERTING AN ELEMENT IN TO A QUEUE:


Function QINSERET(Q,F,R,N,Y)
Step 1: [overflow]
If R>=N
Then printf( overflow)
Return
Step 2: [Increment rear pointer]
R<-R+1
Step 3: [ Insert element]
Q[R]<-y
Step 4: [Is front pointer properly set?]
If F=0
Then f<-1
Return

ALGORITHM FOR DELETING AN ELEMENT FROM A STACK:


Function QDELETE(Q,F,R)
Step 1: [Underflow]
If F=0
Then printf(Queue underflow)
Return(0)
Step 2: [Delete element]
y<-q[f]
Step 3: [Is Queue Empty?]
If F=R
Then F=R=0
Else
F=F+1
Step 4:[Return element]
Return(r)

GNI 108
Computer Programming Lab Manual

FLOW CHART

GNI 109
Computer Programming Lab Manual

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct queue
{
int data;
struct queue *next;
};
typedef struct queue * qptr;

qptr createnode()
{
qptr node;
node=(qptr)malloc(sizeof(struct queue));
return node;
}
qptr insert_q(qptr r,qptr *f,int x)
{
qptr p,temp;
p=createnode();
p->data=x;
p->next=NULL;
if(*f==NULL)
{ r=p;
*f=r;
}
else
{
while(r->next!=NULL)
r=r->next;
r->next=p;
}
return r;
}
void delete_q(qptr *front)
{
qptr temp;
temp=*front;
*front=(*front)->next;
printf ("\n\n%d is deleted",temp->data);
free(temp);
}

GNI 110
Computer Programming Lab Manual

void display(qptr front)


{qptr temp;
temp=front;
while(temp!=NULL)
{
printf("\t%d\n",temp->data);
temp=temp->next;
}
}
void main()
{qptr rear,front;
int choice,item;
clrscr();
front=rear=NULL;
while(1)
{
printf("\n-----------------------------\n");
printf("|MENU FOR OPERATIONS ON QUEUE|");
printf("\n-----------------------------\n");
printf("1.INSERT \n 2.DELETE\n3.DISPLAY\n4.EXIT\n Enter choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("\n enter element to insert");
scanf("%d",&item);
rear=insert_q(rear,&front,item);
printf("\n\nelement %d is inserted succesfully" ,item);
break;
case 2: if(front==NULL)
printf("\n\nqueue is empty");
else
delete_q(&front);
break;
case 3: if(front==NULL)
printf("\n\nqueue is empty");
else
display(front);
break;
case 4: exit(0);
default:printf("Invalid choice...Try Again\n");
break;
}
}
}

GNI 111
Computer Programming Lab Manual

Week 19:

Write a C program to implement the linear regression algorithm.

AIM: To implement the linear regression algorithm

ALGORITHM:

Step 1. Read n
Step 2. Sumx=0
Step 3. Sumxsq=0
Step 4. Sumy=0
Step 5. Sumxy=0
Step 6. fori=1 to n do
Step 7. Read x,y
Step 8. Sumx=sumx+x
Step 9.Sumxsq=Sumxsq+x2
Step 10.Sumy=Sumy+y
Step 11.Sumxy=sumxy+x x y end for
Step 12. denom=n x sumxsq sumx x sumx
Step 13. a0=(sumy x sumxsq sumx x sumxy) / denom
Step 14. a1=(n x sumxy-sumx x sumy)/ denonm
Step 15. Write a1,a0
Step 16. STOP

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

float mean(float *a, int n);


void deviation(float *a, float mean, int n, float *d, float *S);

void main()
{
float a[20],b[20],dx[20],dy[20];
float sy=0,sx=0,mean_x=0,mean_y=0,sum_xy=0;
float corr_coff=0,reg_coff_xy=0, reg_coff_yx=0;
char type_coff[7];
int n=0,i=0;

clrscr();
printf("Enter the value of n: ");
scanf("%d",&n);
printf("Enter the values of x and y:\n");
for(i=0;i<n;i++)
scanf("%f%f",&a[i],&b[i]);
mean_x=mean(a,n);

GNI 112
Computer Programming Lab Manual

mean_y=mean(b,n);
deviation(a,mean_x,n,dx,&sx);
deviation(b,mean_y,n,dy,&sy);

for(i=0;i<n;i++)
sum_xy=sum_xy+dx[i]*dy[i];
corr_coff=sum_xy/(n*sx*sy);
printf("Enter the type of regression coefficient as 'x on y' or 'y on x': ");
fflush(stdin);
gets(type_coff);

if(strcmp(type_coff,"x on y")==1)
{
reg_coff_xy=corr_coff*(sx/sy);
printf("\nThe value of linear regression coefficient is %f",reg_coff_xy);
}
else if(strcmp(type_coff,"y on x")==1)
{
reg_coff_yx=corr_coff*(sy/sx);
printf("\nThe value of linear regression coefficient is %f",reg_coff_yx);
}
else
printf("\nEnter the correct type of regression coefficient.");
getch();
}

float mean(float *a, int n)


{
float sum=0, i=0;
for(i=0;i<n;i++)
sum=sum+a[i];
sum=sum/n;
return (sum);
}

void deviation(float *a, float mean, int n, float *d, float *s)
{
float sum=0,t=0;
int i=0;
for(i=0;i<n;i++)
{
d[i]=a[i]-mean;
t=d[i]*d[i];
sum=sum+t;
}
sum=sum/n;
*s=sqrt(sum);
}

GNI 113
Computer Programming Lab Manual

Week 20

20. Write a C program to implement the polynomial regression algorithm.

Sep 1: Strart
Step 2: Read n
Step 3: Initialize sumx = 0, sumxsq = 0, sumy = 0, sumxy = 0, sumx
sumx4 = 0, sumxsq =0
Step 4: Intialize i=0
Step 5: Repeat steps 5 to 7 until i<n
Step 6: Read x,y
Step 7: Sumx = sumx + x
Sumxsq =sumxsq + pow(x,2)
Sumx3 = sumx3 + pow(x,3)
Sumx4 = sumx4 + pow(x,4)
Sumy = sumy + y
Sumxy = Sumxy + x*y
Sumxsqy = Sumxsqy + pow(x,2) *y
Step 8: Increment I by 1
Step 9: Assign
a[0][0] = n
a[0][1] = n
a[0][2] = n
a[0][3] = n
a[1][0] = n
a[1][1] = n
a[1][2] = n
a[1][3] = n
a[2][0] = n
a[2][1] = n
a[2][2] = n
a[2][3] = n

Step 10: Intialize i=0


Step 11: Repeat steps 11 to 15 until i<3
Step 12: Intialize j=0
Step 13: Repeat step 13 to 14 until j<=3
Step 14: Write a[i][j]
Step 15: Increment j by 1
Step 16: Increment I by 1
Step 17: Initialize k =0
Step 18: Repeat steps 18 to 27 until k<=2
Step 19: Intialize i=0
Step 20: Repeat step 20 to 26 until i<=2
Step 21: If I not equal to k
Step 22: Asign u=a[i][k]/a[k][k]
Step 23: Intialize j=k

GNI 114
Computer Programming Lab Manual

Step 24: Repeat steps 24 and 25 until j<=3


Step 25: Assign a[i][j] = a[i][j] u *a[k][j]
Step 26: Increment j by 1
Step 27: Increment i by 1
Step 28: Increment k by 1
Step 29: Initialize I =0
Step 30: Repeat steps 31 to 33 until i<3
Step 31: Assign b[i] = a[i][3]/a[i][i]
Step 32: Write I, b[i]
Step 33: Increment I by 1
Step 34: Write b[2],b[i],b[0]
Step 35: Stop

PROGRAM:
#include<stdio.h>
#include<math.h>
void main()
{
int n, I, j, k;
float sumx, sumxsq, sumy, sumxy, x, y;
float sumx3, sumx4, sumxsqy, a[20][20], u=0.0, b[20];
printf(\n Enter the n value);
scanf(%d, &n);
sumx = 0;
sumxsq = 0;
sumy = 0;
sumxy = 0;
sumx3 = 0;
sumx4 = 0;
sumxsqy = 0;
for(i=0; i<n; i++)
{
scanf(%f %f, &x, &y);
sumx +=x;
sumxsq += pow(x,2);
sumx3 += pow(x,3);
sumx4 += pow(x,4);
sumy +=y;
sumxy += x * y;
sumxsqy += pow(x,2) *y;
}
a[0][0] = n;
a [0][1] = sumx;
a [0][2] = sumxsq;
a [0][3] = sumy;
a [1][0] = sumx;
a [1][1] = sumxsq;
a [1][2] = sumx3;
a [1][3] = sumxy;

GNI 115
Computer Programming Lab Manual

a [2][0] = sumxsq;
a [2][1] = sumx3;
a [2][2] = sumx4;
a [2][3] = sumxsqy;
for(i=0; i<3; i++)
{
for(j=0; j<=3; j++)
printf(%10.2f,a[i][j]);

printf(\n);
}
for(k=0; k<=2; k++)
{
for(i=0;i<=2;i++)
{
if(i!=k)
u=a[i][k]/a[k][k];
for(j = k; j<=3; j++)
a[i][j]=a[i][j] u * a[k][j];
}
}
for(i=0;i<3;i++)
{
b[i] = a[i][3]/a[i][i];
printf(\nx[%d] = %f, I, b[i]);
}
printf(\n);
printf(y= %10.4fx +10.4 fx +%10.4f,b[2],b[i],b[0]);
}

Enter the n value 10


-4 21
-3 12
-2 4
-1 1
02
17
2 15
3 30
4 45
5 67
10.00 5.00 85.00 204.00
5.00 85.00 125.00 513.00
85.00 125.00 1333.00 3193.00
X[0] = 2.030303
X[1] = 2.996970
X[2] = 1.984848
Y= 1.9848xsq + 2.9979x + 2.0303

GNI 116
Computer Programming Lab Manual

Week 21:

21. Write C program to implement the Lagrange interpolation.

#include<stdio.h>
#include<conio.h>
#define MaxN 90

void main()
{
float arr_x[MaxN+1], arr_y[MaxN+1], numerator, denominator, x, y=0;
int i, j, n;
clrscr();
printf("Enter the value of n: \n");
scanf("%d", &n);
printf("Enter the values of x and y: \n");
for(i=0; i<=n; i++)
scanf("%f%f", &arr_x[i], &arr_y[i]);
printf("Enter the value of x at which value of y is to be calculated: ");
scanf("%f", &x);
for (i=0; i<=n; i++)
{
numerator=1;
denominator=1;
for (j=0; j<=n; j++)
if(j!=i)
{
numerator *= x-arr_x[j];
denominator *= arr_x[i]-arr_x[j];
}
y+=(numerator/denominator)*arr_y[i];
}
printf("When x=%4.1f y=%7.1f\n",x,y);
getch();
}

GNI 117
Computer Programming Lab Manual

Week 22:

22. Write C program to implement the Newton- Gregory forward interpolation.

/* Write C program to implement the Newton- Gregory forward interpolation.*/

#include<stdio.h>
#include<conio.h>
#define MaxN 100
#define Order_of_diff 4

void main ()
{
float arr_x[MaxN+1], arr_y[MaxN+1], numerator=1.0, denominator=1.0, x, y, p, h,
diff_table[MaxN+1][Order_of_diff+1];
int i,j,n,k;
clrscr();

printf("Enter the value of n \n");


scanf("%d",&n);
printf("Enter the values of x and y");

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


scanf("%f%f", &arr_x[i], &arr_y[i]);
printf("Enter the value of x at which value of y is to be calculated");
scanf("%f", &x);
h=arr_x[1]-arr_x[0];

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


diff_table[i][1]=arr_y[i+1]-arr_y[i];/*Creating the difference table and calculating first
order differences*/
for(j=2; j<=Order_of_diff; j++)/*Calculating higher order differences*/
for(i=0; i<=n-j; i++)
diff_table[i][j]=diff_table[i+1][j-1] - diff_table[i][j-1];
i=0;

while(!(arr_x[i]>x)) /* Finding x0 */
i++;
i--;
p=(x-arr_x[i])/h;
y=arr_y[i];

for (k=1; k<=Order_of_diff; k++)


{
numerator *=p-k+1;
denominator *=k;
y +=(numerator/denominator)*diff_table[i][k];
}

GNI 118
Computer Programming Lab Manual

printf("When x=%6.1f, y=%6.2f\n",x, y);


getch();
}

Input/Output:
Enter the value of n 4
Enter the value to be found 2.5
Enter the values for xis & fis
11
28
3 27
4 64
X = 2.500000
Sum = 15.625000

GNI 119
Computer Programming Lab Manual

Week 23:

23. Write a C program to implement Trapezoidal method.

Algorithm:
Step 1. Read x1, x2, e { x1 and x2 are the two end points of the
internal the allowed error in integral is e}
Step 2. h=x2-x1
Step 3. SI = (f(x1) + f(x2))/2;
Step 4. I = h-si
Step 5. i=1 Repeat
Step 6. x=x1 + h/2
Step 7. for J= 1 to I do
Step 8. SI= SI + f(x)
Step 9. x=x+h
Endfor
Step 10. i=21
Step 11. h=h/2 { Note that the internal has been halved above and
the number of points where the function has to be computed
is doubled}
Step 12.i0=i1
Step 13. i1 = h.si
Step 14. until / I1-i0 / <=c./i1/
Step 15. Write I1,h,i
Step 16. Stop

PROGRAM:
#include<stdio.h>
#include<math.h>
main()
{
float h,a,b,n,x[20],y[20],sum=0,integral;
int i;
clrscr();
printf("enter the value ofa,b,n:");
scanf("%f %f %f",&a,&b,&n);
printf("enter the values of x:");
for(i=0;i<=(n-1);i++)
{
scanf("%f",&x[i]);
}
printf("\n enter the values of y:");
for(i=0;i<=(n-1);i++)
{
scanf("%f",&y[i]);
}
h=(b-a)/n;

GNI 120
Computer Programming Lab Manual

x[0]=a;
for(i=1;i<=n-1;i++)
{
x[i]=x[i-1]+h;
sum=sum+2*y[i];
}s
um=sum+y[b];
integral=sum*(h/2);
printf("approximate integral value is: %f",integral);
getch();
}

Input/Output:
Enter the values of a,b,n
123
Enter the values of x:
123
Enter the values of y:
123
Approximate integral value is 2.166667

GNI 121
Computer Programming Lab Manual

Week 24:

24. Write a C program to implement Simpson method.

Algorithm:
Step 1. Read x1,x2,e
Step 2. h=(x2-x1)/2
Step 3. i=2
Step 4. si=f(x1) + f(x2)
Step 5. s2=0
Step 6. s4=f(x1+h)
Step 7. I0=0
Step 8. In =(s+4s4). (h/3)
Repeat
Step 9. s2=s2+s4 {s2 stores already computed functional value and s4
the value computed in the new nitration }
Step 10. s4=0
Step 11. x=x1+h/2
Step 12. for j=1 to I do
Step 13. s4=s4+f(x)
Step 14. x=x+h
Step 15. h=h/2
Step 16. i=2i
Step 17. io=in
Step 18. in= (s1+2s2+4s4) . (h/3)
Step 19. until |In-Io|e. /in
Step 20. Write In,h,i
Step 21. STOP

PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
float h,a,b,n,x[20],y[20],sum=0,itgl;
int i;
clrscr();
printf("enter the values of a,b,n");
scanf("%f%f%f",&a,&b,&n);
printf("enter the values of x");
for(i=0;i<=n;i++)
{
scanf("%f",&x[i]);
}
printf("\n enter the values of y");
for(i=0;i<=n;i++)

GNI 122
Computer Programming Lab Manual

{
scanf("%f",&y[i]);
}
h=(b-a)/n;
a=x[0];
b=x[n];
for(i=0;i<=(n-2);i++)
{
x[i]=x[i]+h;
if(i%2==0)
{
sum=sum+4*y[i];
}else
{
sum=sum+2*y[i];
}
}itgl=sum*(h/3);
printf("integral value%f",itgl);
getch();
}

Input/Output:
Enter the values of a,b,n
123
Enter the value of x
4567
Enter the values of y
8912
Integral value is 5.555556

GNI 123

Vous aimerez peut-être aussi