Computer Programing Lab Manual
Computer Programing Lab Manual
TECHNICAL CAMPUS
School of Engineering & Technology
Ibrahimpatnam, R R District 501 506 (A. P.)
1
SNO NAME OF PROGRAM Pg no
a)Operating Systems 3
b)Computer Languages 21
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
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
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
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
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
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
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.
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
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 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.
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:
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.
01. VER
02. VOL
03 DATE
04. TIME
05. CLS
06. DIR
07. MD
08. CD
09. PATH
10. RD
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.
11
2.VOL- It is used to display volume label and serial number of the current drive
3.DATE: - Used to display the current system date and prompt for entering new date.
12
4. TIME: - Displays the current system Time and prompt for entering new time.
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.
Switches:
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.
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)
15
NOTE: -The directory must be empty when we use RD.
11. COPY CON: -We use this command to create a new file.
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.
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*.TXT +*.BAK TARGET FILENAME And Then Press Enter
You can also have the option to change the name of files as you copy it.
14. DEL/ERASE: This command removes one or more files from the disk or current
working directories.
16
Example: C:\> DEL abc And Then Press Enter
16. PROMPT: This command allows you to customize the dos prompt.
SYNTAX: 1. PROMPT
Most people like to set their prompt to $p$g which display the current directory followed
by > sign.
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.
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.
SWITCHES :
/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.
SWICHES:
/-Y : Prompt before it overwrites while it copies file that already exists.
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.
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.
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
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.
20
Computer Programming Lab Manual
5. MEM:
This command displays amount of total available memory ( low, Expanded and
Extended) and all currently programs.
Switches:
/f : Using this switch MEM display all the areas of memory that are fee.
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.
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>
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.
Switches:
21
Computer Programming Lab Manual
[+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.
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").
Switches:
[/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.
Where:
[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>
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
With the ATTRIB command you can check the attributes of a file.
Switches:
Note:
While Creating a new file every file gets read only attribute and archive attribute by
default.
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
9. EDIT:
This is the DOS Editor, which you can use to edit the text file and also creating new file.
BATCH FILES
Look at the following commands you give step by step to perform an operation.
If you do all this steps daily after your hour, then the commands you give would be:
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.
Note: Here Con means Console that is Keyboard, A the file name and .bat is extension.
GNI 24
Computer Programming Lab Manual
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.
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
GNI 25
Computer Programming Lab Manual
i. It is machine dependent.
ii. It requires the translator program called Assembler.
INTRODUCTION TO C LANGUAGE
GNI 26
Computer Programming Lab Manual
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.
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.
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.
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
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
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
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
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!
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
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
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:
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
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
GNI 41
Computer Programming Lab Manual
FLOWCHART:
Start
Read
a,b,ch
switch(ch)
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
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:
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
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:
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
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
Flow CHART:
Main Program:
Start
Read 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:
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
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
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
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
Week 6:
Algorithm:
Step 1: start
GNI 57
Computer Programming Lab Manual
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
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
GNI 60
Computer Programming Lab Manual
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:
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
Display string
Found = strstr(s,t)
No if found Yes
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
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
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.
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
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:
Sub program:
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;
}
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
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:
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;
};
scanf("%f",&c.real);
printf("enter Imaginary part of complex number");
scanf("%f",&c.img);
return c;
}
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:
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
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
#include <stdio.h>
#include <conio.h>
#include<string.h>
#include <process.h>
int main()
{
FILE *fs;
char ch;
char *fname;
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:
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
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
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();
}
GNI 90
Computer Programming Lab Manual
Week 15:
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
GNI 93
Computer Programming Lab Manual
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
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:
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
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;
GNI 99
Computer Programming Lab Manual
{
p->next=head;
head=p;
return head;
}
}
GNI 100
Computer Programming Lab Manual
if(c==1)
{
p->next=head;
head=p;
}
else
{
q->next=p;
p->next=temp;
}
return head;
}
}
GNI 101
Computer Programming Lab Manual
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
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:
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:
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
GNI 111
Computer Programming Lab Manual
Week 19:
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>
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();
}
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
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
GNI 114
Computer Programming Lab Manual
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]);
}
GNI 116
Computer Programming Lab Manual
Week 21:
#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:
#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();
while(!(arr_x[i]>x)) /* Finding x0 */
i++;
i--;
p=(x-arr_x[i])/h;
y=arr_y[i];
GNI 118
Computer Programming Lab Manual
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:
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:
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