C programming reading materials
C programming reading materials
LAB MANUAL
PRINCIPLES OF PROGRAMMING USING C LABORATORY / BPOPS203
(Effective from the academic year 2022 -2023)
II SEMESTER
Prepared by,
nth row
INTRODUCTION
Description about Functional block diagram of Computer:
A computer is an electronic device, which mainly performs the four functions as reading,
processing, displaying and storing on data. These functions of a computer system can be carried out by
using the three main units namely input unit, system unit and output unit. The block diagram of a computer
system is as follows:
System or Central Processing Unit (CPU): is commonly known as “processor” that executes the instructions of a
computer program. It has Control Unit (CU) and Arithmetic & Logical Unit (ALU). These two units perform the basic
arithmetic, logical, and input/output operations.
a) Input unit: is used to enter data and information into a computer. The devices like keyboard, mouse and scanner
are commonly used input devices.
A keyboard is used to enter alphanumeric characters and symbols.
The mouse is used to pick or select a command from the monitor screen.
A scanner is used to scan an image or read a barcode and so on.
b) Arithmetic and Logic Unit (ALU): ALU is a digital circuit that perform arithmetic (Add, Sub, Multiplication,
Division) and logical (AND, OR, NOT) operations. It helps in fast computation of scientific calculations on
floating-point number.
c) Control unit (CU): CU is the circuitry that controls the flow of information through the processor and
coordinates the activities of the other units within the processor.
Functions of Control unit
Accessing data & instructions from memory unit
Interpreting instructions, Controlling I/O Units
d) Memory Unit (MU): is the unit where all the input data and results are stored either temporarily or
permanently. The CPU memory is also called as memory register. The memory of a computer has two
types:
2. I/O Buses: The buses which are used to connect all I/O devices with CPU and Memory are called I/O
buses. These are classified into following three types.
The motherboard will be This is simple and slowest It helps to connect various
having 3 or 4 PCI bus used in IBM PCs I/O devices like keyboard,
connectors, so that we can mouse, pen drives, printer,
insert various chips. etc.
Fastest and presently more Oldest, simplest and slowest Newest and widely used bus
powerful bus Bus
Main Board or Mother Board: Mother Board is a set of Integrated Chips (ICs) which are designed to work together.
It controls the flow of data/instructions within our computer. It is the main board on which other hardware components
are connected to enable the computer system to work as an integrated unit. It consists of sockets, slots, power
connectors and bus.
Chip sets: Chip set is the set of integrated chips that are designed to work together. These set of chips controls the
flow of information on computer. The chips may be controllers for memory, cache, hard drive, key board and
peripherals.
Operating System and its types: An Operating System (OS) is system software that controls and supervises the
hardware components of a computer system and it provides the services to computer users. Also called as Resource
Manager that manages the resources such as CPU, Memory, I/O devices, Job/Task/Process etc., a computer cannot
run without it. The major functions of OS includes:
CPU Management,
Memory Management,
File Management,
Device Management,
Process/Task/Job Management and Security Management.
The primary goal of an OS is to make the computer system convenient and efficient to use. An OS ensures that the
system resources (such as CPU, memory, I/O devices, etc) are utilized efficiently. For example, there may be many
programs residing in the main memory. Therefore, the system needs to determine which programs are active and
which need to wait for some I/O operation.
Some of the examples of Operating Systems:
Windows –XP, Unix, Windows 7, Windows 8, Macintosh OS, Fedora, and Android, etc.
Types of Operating Systems: The operating systems are classified into 7 types based on their capability and usage.
Fig 3: Types of OS
1. Batch Processing Tasking OS: The data is collected into a group called batch and provides only one
batch (one after another) of jobs as input to the computer system at a time. The jobs in a batch are
processed on first come first serve basis. In this type, the process takes place at specified time intervals
i.e. weekly or monthly without user interaction. E.g. Punch cards were using to store the data in batch
processing and in payroll preparation in a business batch processing was helpful.
2. Single user and single tasking OS: The OS that allows only one program to execute at a time is
called single user single tasking operating system. Using this operating system user can do
only one task at a time. E.g. DOS (Disk Operating System).
3. Single user and multi-tasking OS: The OS that allows a single use to perform more than
one task at a time is called single user multi-tasking operating system. While working with
the Ms-Word user can perform other work like print a document, listen music. E.g. Windows-
XP, Windows Vista, Windows – 7, etc.
4. Multi user and multitasking OS: The O.S. that allows two or more users to use a main
computer system to do more than one task is called multiuser and multitasking operating
system. E.g. UNIX is a multiuser and multitasking operating system.
5. Multiprocessing OS: The OS that allows multiple programs to be executed by multiple CPUs
(Processors) is called multiprocessing operating system. Super and main frame computers
have more than one CPU and multiprocessing operating system.
6. Real Time Operating System (RTOS): The OS that is used for real time applications and to
carry out certain calculations within the specified time constraint. This OS is used in
applications such as mobile phones, supporting systems in hospitals, nuclear power plants, oil
refining, chemical processing, environmental applications and air -traffic control systems, disaster
management etc.,
7. Virtual machine OS: Allows several users of a computer system to operate as if each has the
only terminal attached to the computer.
Random Access Memory (RAM): RAM is basically main memory of the
computer. RAM is a semiconductor memory made up of small memory chips that
form a memory module. These modules are installed in the RAM slots on the
motherboard of computer. Every time you open a program, it gets loaded from the
hard drive into the RAM. This is because reading data from the RAM is much faster than reading
data from the hard drive.
Hard disks: Hard disk is prime unit of storage of the computer. Huge amount of data can be stored and
accessed in few milliseconds. The hard disk consists of more number of disks arranged in the
cylindrical order, one above another on a spindle.
Optical media: An optical storage media is kind of storage, which is coated with thin metal on which bits
are stored. The data can be stored in to optical storage media or read form the optical storage media.
The devices which perform read or write operation on optical storage media are called optical
storage media. The laser technology is used to read the data or write the data on optical storage
devices.
Compact Disc Read-Only-Memory (CD-ROM): It is a type of optical disc that uses laser technology to
read and write data on the disc. The information stored on CDROM becomes permanent and cannot be
altered. This means that the stored information can only be read for processing.
A CD-ROM uses the round shaped optical disk to store data, applications, games and
audio files. It can store up to 700 MB of data. It has become integral part of every
organization due to its features like reliability, reasonable, storage capacity and easy to use
of carry.
CD-Drive will be with motor to rotate the disks to perform read and write operations. A CD-drive will
consists of the components like Disc drive, disk drive motor, laser pick up assembly tracking drive and
tracking motor and so on.
Compact Disk Recordable (CD-R): The CD-R allows you to create your own CD.CD-R drives have the
ability to create CDs but they can write data on the disk only once.CD-R technology also called as Write
Once-Read much (WORM) technology. Laser technology is used to write the data on the compact disk.CD-
R drives come in IDE, SCSI and USB models.
Compact Disc Rewritable (CD-RW): CD-RW is an erasable optical disk which is used to write data
multiple times on a disk, CD-RW disks are good for data backup, data archiving or data distribution on
CDs. The disk normally holds 700MB of data. Technology to write data multiple times on a CD was known
as the Phase change Dual (PD) technology. The reflective properties of a CD-RW are different than regular
CD-ROM disks.
Disk or Digital Versatile Disc (DVD-ROM): A DVD is a small optical disk having high density medium
and capable of storing a full-length movie on a single disk. The high density is achieved by using both
sides of the disk, special data-compression technology, and extremely small tracks to store the data.
Flash Drives (Pen drives): USB flash drives are removable, rewritable, and physically much smaller drives
weighing even less than 30 g. A flash drive consists of a small printed circuit board carrying the circuit
elements and a USB connector, insulated electrically and protected inside a plastic, metal, or rubberized
case which can be carried in a pocket or on a key chain.
Advantages
Can sustain only a limited number of write and erase cycles before the drive fails. Most
flash drives do not have a write-protect mechanism
Flash drives are very small devices that can easily be misplaced, left behind, or otherwCSE lost. The
cost per unit of storage in a flash drive is higher than that of hard disks
Keyboard: A keyboard is the primary input device used in all computers. Keyboard has a group of switches
resembling the keys on an ordinary typewriter machine. Normally keyboard has around 101 keys. The
keyboard includes key that allows us to type letters, numbers and various special symbols such as *, /, [, %
etc.
Mouse: The mouse is the key input device to be used in a Graphical User Interface (GUI). The users can
use mouse to handle the cursor pointer easily on the screen to perform various functions like opening a
program or file.
With mouse, the users no longer need to memorize commands, which was earlier a necessity when working
with text-based command line environment such as MS-DOS.
Advantages:
Easy to use; Cheap; Can be used to quickly place the cursor anywhere on the screen Helps to
quickly and easily draw figures
Point and click capabilities makes it unnecessary to remember certain commands
Disadvantages:
Needs extra desk space to be placed and moved easily
The ball in the mechanical mouse needs to be cleaned very often for smooth movements
Printers: The printer is an output device, which is used to get hard copy of the text displayed on the screen.
The printer is an external optional device that is connected to the computer system using cables. The printer
driver software is required to make the printer working. The performance of a printer is measured in terms
of Dots Per Inch (DPI) and Pages Per Minute (PPM) produced by the printer.
Plotters: A plotter is similar to printer that produces hard-copy output with high-quality color graphics.
Plotters are generally more expensive than printers, ranging from about $1000 to $75000.
1. Algorithm
2. Flowchart
3. Pseudo Code
Definiteness: Instructions must be precise and unambiguous i.e. each and every instruction
should be clear and should have only one meaning.
Finiteness: Not even a single instruction must be repeated infinitely. i.e., each instruction should
be performed in finite time.
Termination: After the algorithm gets executed, the user should get the desired result
Any algorithm has a finite number of steps and some steps may involve decision making, repetition.
Broadly speaking, an algorithm exhibits three key features that can be given as:
Sequence: Sequence means that each step of the algorithm is executed in the specified order.
Decision: Decision statements are used when the outcome of the process depends on some
condition.
Repetition: Repetition which involves executing one or more steps for a number of times can be
implemented using constructs like the while, do-while and for loops. These loops executed one or
more steps until some condition is true.
ALGM: AREA_of_RECTANGLE [This algorithm takes length and breadth, the sides of the rectangle as
input and computes the area of rectangle using the formula area=length * breadth. Finally it prints the area
of rectangle]
STEPS:
Step 1: Start
Area length*breadth
Print Area
Step 5: [Finished]
Stop
Flowcharts: A flowchart is a graphical or symbolic representation of an algorithm. They are basically used
to design and develop complex programs to help the users to visualize the logic of the program so that they
can gain a better understanding of the program and find flaws, bottlenecks, and other less obvious features
within it. Basically, a flowchart depicts the “flow” of a program. The following table shows the symbols
used in flowchart along with its descriptions.
Small circle Shows the continuation from one point in the process
flow to another.
Process
Subroutine function
Hexagon Represents Looping structures
Advantages of Flowcharts:
A flowchart is a diagrammatic representation that illustrates the sequence of steps that must
be performed to solve a problem. They are usually drawn in the early stages of formulating
computer solutions to facilitate communication between programmers and business people.
Flowcharts help programmers to understand the logic of complicated and lengthy problems.
They help to analyse the problem in a more effective manner
Flowchart can be used to debug programs that have error(s).
Drawing flowcharts is a laborious and a time consuming activity. Flowchart of a complex program becomes,
complex and clumsy. At times, a little bit of alteration in the solution may require complete redrawing of
the flowchart Essentials of what is done may get lost in the technical details of how it is done. There are no
well-defined standards that limits the details that must be incorporated in a flowchart
E.g.: To compute the Area of Rectangle
start
Print Area
Stop
Pseudo code: It is a form of structured English that describes algorithms. It facilitates the designers to focus
on the logic of the algorithm without getting bogged down by the details of language syntax.
Pseudocode is a compact and informal high-level description of an algorithm that uses the structural
conventions of a programming language. It is meant for human reading rather than machine reading, so it
omits the details that are not essential for humans. Such details include keywords, variable declarations,
system-specific code and subroutines. There are no standards defined for writing a pseudocode because it is
not an executable program. Flowcharts can be considered as a graphical alternative to pseudocode, but are
more spacious on paper.
Laboratory 1
Step 1: Locate the TC.exe file and open it. You will find it at location C:\TC\BIN\.
Step 2: File > New (as shown in the below picture) and then write your C program
Step 3: Save the program using F2 (OR file > Save), remember the extension should be “.c”. In the
below screenshot I have given the name as summ.c.
Step 4: Compile the program using Alt + F9 OR Compile > Compile (as shown in the below screenshot).
Step 5: Press Ctrl + F9 to Run (or select Run > Run in menu bar ) the C program.
Step 6: Alt+F5 to view the output of the program at the output screen.
peri
Program Output
#include<stdio.h> Enter length and breadth
{ 2
int l, b, area, peri; 4
printf(“Enter length and breadth\n”); The area is 8
scanf(“%d%d”, &l, &b); The perimeter is 12
area = l * b;
peri = 2 * (l + b);
printf(“The area is %d\n”, area);
printf(“The perimeter is %d\n”, peri);
}
Laboratory Program 1
ALGORITHM
Step 1: Start
Step 2: Read the value of operator op.
Step 3: Read the values of num1 and num2.
Step 4: Verify op value by using switch statement
if op=’+’ then goto step 5 (or)
if op=’-’ then goto step 6 (or)
if op=’*’ then goto step 7 (or)
if op=’/’ then goto step 8 (or)
otherwise goto step 9
Step 5: if op=’+’ then compute result=num1+num2
print result and goto step 10
Step 6: if op=’-’ then compute result=num1-num2
print result and goto step 10
Step 7: if op=’*’ then compute result=num1*num2
print result and goto step 10
Step 8: if op=’/’ then compute divresult=num1/num2
print divresult and goto step 10
Step 9: if op value is other than above options then
print “Invalid input, Try again” goto step 10
Step 10: Stop
FLOWCHART
Start
Read op
Switch (op)
+ - * / default
Stop
PROGRAM
#include <stdio.h>
#include <conio.h>
void main()
{
int num1,num2,result;
float divresult;
char op;
clrscr();
printf("Enter the operation to be done \n");
scanf("%c",&op);
printf("Enter the value of num1 and num2 \n");
scanf("%d%d",&num1,&num2);
switch(op)
{
case '+': result = num1 + num2;
printf(“Addition=%d\n”,result);
break;
case '-': result = num1 - num2;
printf(“Subtraction=%d\n”,result);
break;
case '*': result = num1 * num2;
printf(“Multiplication=%d\n”,result);
break;
case '/': divresult = num1 / (float)num2;
printf(“Division=%.2f\n”,divresult);
break;
default: printf("Invalid Input ,Try Again\n");
}
getch();
}
OUTPUT
First Run:
Enter the operation to be done
+
Enter the value of num1 and num2
10
20
Addition=30
Second Run:
Enter the operation to be done
-
Enter the value of num1 and num2
10
20
Subtraction=-10
Third Run:
Enter the operation to be done
*
Enter the value of num1 and num2
20
30
Multiplication=600
Fourth Run:
Enter the operation to be done
/
Enter the value of num1 and num2
40
50
Division=0.80
Fifth Run:
Enter the operation to be done
@
Enter the value of num1 and num2
40
50
Invalid Input ,Try Again
RESULT: Thus, the program to implement the simple calculator has been executed
successfully and the output was verified.
VIVA QUESTIONS:-
a. What is switch statement?
b. What is a case in a switch statement?
c. Is Default necessary in switch case?
d. How many cases can you have in a switch statement?
Laboratory Program 2
AIM: To write a C Program to Compute the roots of a quadratic equation by accepting the
coefficients
ALGORITHM
Step 1: Start
Step 2: Read the value of non-zero coefficient a.
Step 3: If a is zero goto Step 10. Otherwise read the values of coefficients b and c.
Step 4: Compute the value of discriminant (disc) using the formula (b*b) - (4*a*c).
Step 5: Check if disc is equal to 0. If true, then go to Step 6. Otherwise, goto Step 7
Step 6: Compute the equal roots.
root1 = root2 = (-b)/(2*a)
Print the values of roots, root1 and root2. Go to Step 10.
Step 7: Check if disc is greater than zero or not. If true, then go to Step 8. Otherwise, goto
Step 9.
Step 8: Compute the real and distinct roots
root1 = (-b+sqrt(disc))/(2*a)
root2 = (-b-sqrt(disc))/(2*a)
Print the values of roots, root1 and root2. Go to Step 10.
Step 9: Compute the complex and imaginary roots.
Compute the real part, realp = (-b)/(2*a)
Compute the imaginary part, imagp = sqrt(-disc)/(2*a)
Print roots as
root1 = realp + imagp
root2 = realp – imagp
Step 10: Stop.
FLOWCHART
PROGRAM
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <stdlib.h>
void main()
{
float a,b,c,root1,root2,realp,imagp,disc;
clrscr();
if(a == 0)
{
printf("\n Invalid input...Retry again");
exit(0);
}
printf(" Enter the value of coefficients b and c:\n ");
scanf("%f%f",&b,&c);
disc = b*b-4*a*c; // compute discriminant
if(disc == 0)
{
printf("The roots are real and equal\n");
root1 = root2 = -b / (2.0*a);
printf(" Root1 = Root2 = %.2f\n", root1);
}
else
{
if(disc > 0)
{
printf("The roots are real and distinct\n");
root1 = (-b + sqrt(disc))/(2.0*a);
root2 = (-b - sqrt(disc))/(2.0*a);
printf("Root1 = %.2f\n", root1);
printf("Root2 = %.2f\n", root2);
}
else
{
printf("The roots are complex\n");
realp = -b/(2.0*a);
disc=-disc;
imagp = sqrt(disc)/(2.0*a);
printf("Root1 = %.2f + i%.2f\n",realp,imagp);
printf("Root2 = %.2f - i %.2f\n",realp, imagp);
}
}
getch();
}
OUTPUT
First Run:
Enter the value of coefficient a: 1
Enter the value of coefficients b and c:
44
The roots are real and equal
Root1 = Root2 = -2.00
Second Run:
Enter the value of coefficient a: 1
Enter the value of coefficients b and c:
-7 10
The roots are real and distinct
Root1 = 5.00
Root2 = 2.00
Third Run:
Enter the value of coefficient a: 2
Enter the value of coefficients b and c:
-3 6
The roots are complex
Root1 = 0.75 + i 1.56
Root2 = 0.75 - i 1.56
Fourth Run:
Enter the value of coefficient a: 0
RESULT: Thus, the program to compute the roots of quadratic equation has been executed successfully
and the output was verified.
VIVA QUESTIONS:-
AIM
To write a C program to read the Name of the User, Number of Units Consumed and
Print out the charges.
ALGORITHM
Step 1: Start
Step 2: Read the name of customer and the unit consumed by the customer.
Step 3: Check if the unit consumed is greater than 1 and less than 200, if true goto
step 4 else goto step 5.
Step 5: if unit is greater than 200 and less than 300,if true goto step 6 else goto step 7
Step 8: Check if the amt is greater than or equal to 400, if true goto step 9 otherwise
Step 10:. Print the amount charged and goto step 11.
#include <stdio.h>
#include<conio.h>
void main()
{
char name[10];
clrscr();
printf("Enter your name and unit Consumed:");
scanf("%s %f",name,&unit);
if(unit<=200)
amt=unit*0.80+100;
else if((unit>200)&&(unit<=300))
amt=200*0.80+((unit-200)*0.90)+100;
else
amt=200*0.80+100*0.90+((unit-300)*1)+100;
if(amt>400)
amt=1.15*amt;
printf("Name: %s\n Unit=%f \n charge=%f ",name,unit,amt);
getch();
}
OUTPUT
First Run:
Enter your name and unit Consumed: Siri 52Name: Siri
Unit=52 charge=141.600000Second Run:
Enter your name and unit Consumed: Rajesh 460Name: Rajesh
Unit=460 charge=586.500000
RESULT: -
Thus, the program to read the Name of the User, Number of Units Consumed and Print out the
charges has been executed successfully and the output was verified.
VIVA QUESTIONS: -
a. Difference between float and double data types.
b. Write syntax of for loop?
c. What is the use of break statement?
d. Difference between continue and break statement?
Laboratory Program 4
AIM
To write a C program to display the pattern by reading the number of rows as input.
ALGORITHM
Step 1: Start
Step 2: Read the number of rows.
Step 3: Let i=0, if i<=n, go to step 14
Step 4: Initialize j=1 if j<=n-i, Go to step 8
Step 5: Print blank spaces
Step 6: Increment j (ie. j=j+1) Go to step 5
Step 7: Initialize j=1 if j<=i Go to step 11
Step 8: Display number in ascending order up to middle.
Step 9: Increment j (ie. j=j+1) Go to step 8
Step 10: initialize j=i-1 if j>=1 Go to step 14
Step 11: Display number in reverse order after middle
Step 12: Increment j (ie. j=j+1) Go to step 13
Step 13: Increment i (ie. i=i+1) Go to step 3
Step 14: Stop.
FLOWCHART
PROGRAM
#include <stdio.h>
#include <conio.h>
void main()
{
int i,j,n;
clrscr( );
printf("Input number of rows : ");
scanf("%d",&n);
for(i=0; i<=n;i++)
{
for(j=1;j<=n-i;j++)
{
printf(" ");
}
for(j=1;j<=i;j++)
{
printf("%d",j);
}
for(j=i-1;j>=1;j--)
{
printf("%d",j);
}
printf("\n");
}
getch();
}
OUTPUT
First Run:
Second Run:
1
121
12321
1234321
123454321
12345654321
RESULT: -
Thus, the program to display the pattern by reading the number of rows as input has been
executed successfully and the output was verified.
VIVA QUESTIONS:-
a. Write syntax of for loop?
b. What is the use of nested for loop?
c. Define Pattern.
Laboratory Program 5
ALGORITHM
Step 1: Start
Step 2: Read size of the array n
Step 3: Read the list of elements in sorted order a[i].
Step 4: Read the key element in key
Step 5: initialize low=0 and high= n-1
Step 6: Check if low is less than or equal to high. If condition is true, goto step 7,
otherwise goto Step 11
Step 7: find the middle element.i.e. mid=(low+high)/2;
Step 8: if key element is equal to mid element, then initialize loc value, loc = mid+1;
otherwise goto step 9
Step 9: Check if key element is less than mid element is true, then initialize high=mid-1
then goto step 6, if it is false goto step10.
Step 10: Check if key element is greater than mid element is true, then initialize
low=mid+1 then goto step 6.
Step 11: Check if loc value is greater than zero then print the search is successful then
goto step 13, otherwise goto step 12.
Step 12: print search is unsuccessful, then goto step 13.
Step 13: Stop
PROGRAM
#include <stdio.h>
#include <conio.h>
void main()
{
int n, a[100], i, key, high, low, mid, loc=-1;
clrscr( );
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter the elements of array in sorted order\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key element to be searched\n");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key= =a[mid])
{
loc = mid+1;
break;
}
else
{
if(key<a[mid])
high=mid-1;
else
low=mid+1;
}
}
if(loc>0)
printf("\n The element %d is found at %d ",key,loc);
else
printf("\nThe search is unsuccessful");
getch();
}
OUTPUT
First Run:
Enter the size of the array 5
Enter the elements of array in sorted order 10
20
30
40
50
Enter the element to be searched 40
The element 40 is found at 4
Second Run:
Enter the size of the array
4
Enter the elements of array in sorted order
4
6
8
9
Enter the key element to be searched
2
The search is unsuccessful
RESULT: -Thus, the program to implement the binary search on integers has been executed successfully
and the output was verified.
VIVA QUESTIONS: -
a. What is an array/definition of array.
b. What are the types of array?
c. What is a multidimensional array?
d. How to declare and initialize one dimensional array?
e. What are the advantages of an array?
f. What is the difference between array & string?
g. Write the syntax of declaring an array.
Principles of Programming using C Laboratory 22POP13/23
Laboratory Program 6
AIM: To develop a program to introduce 2D Array manipulation and implement Matrix multiplication
and ensure the rules of multiplication are checked.
ALGORITHM:
c[i][j]=0
For k=0, k< n, k++
c[i][j]=c[i][j]+a[i][k]*b[k][j]
End for
End for
Step 7: DISPLAY RESULT
For i=0, i<m, i++
For j=0, j<q, j++
Print c[i][j]
End for
End for
Step 8: STOP
FLOWCHART
Page 38
Principles of Programming using C Laboratory 22POP13/23
Page 39
Principles of Programming using C Laboratory 22POP13/23
PROGRAM
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],m,n,p,q,i,j,k;
clrscr();
printf("Enter the size of first matrix\n");
scanf("%d %d",&m,&n);
printf("Enter the size of second matrix\n");
scanf("%d %d",&p,&q);
if(n!=p)
printf(“Matrix multiplication is not possible”);
else
{
printf("Enter the elements of first matrix\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("Enter the elements of the second matrix\n");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
for(i=0;i<m;i++)
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
printf("\n A- matrix is\n");
Page 40
Principles of Programming using C Laboratory 22POP13/23
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
printf("\n B- matrix is\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
printf("%d\t",b[i][j]);
printf("\n");
}
printf("The product of two matrices is\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%d\t",c[i][j]);
printf("\n");
}
}
getch();
}
OUTPUT:
Enter the size of first matrix
23
Enter the size of second matrix
32
Enter the elements of first matrix
123456
Enter the elements of the second matrix
123456
A- matrix is
1 2 3
Page 41
Principles of Programming using C Laboratory 22POP13/23
4 5 6
B - matrix is
1 2
3 4
5 6
The product of two matrices is
22 28
49 64
RESULT: -Thus, the program to implement matrix multiplication has been executed successfully and the
output was verified.
VIVA QUESTIONS: -
a. How to initialize two dimensional arrays?
b. How to pass a two dimensional array as function parameter?
c. How the memory is allocated for two dimensional array
d. Write the program to add and subtract two matrices.
e. Program to find the transpose of a matrix.
f. Program to find determinants of a matrix.
g. Program to find the diagonal elements of a matrix.
Page 42
Principles of Programming using C Laboratory 22POP13/23
Laboratory Program 7
ALGORITHM:
Step-1: Start
Step-2: [Read the value of x in degree]- Read x
Step-3: [Initialization and Radians Conversion]
Temp = x
x=x*(3.142/180.0)
Term = x
sinx = term
n=1
Step-4: [Computer sin value]
Repeat while (term>FLT_EPSILON)
Fact = 2*n*(2*n+1)
Term = term * x * x /fact Sinx
sinx +term = n + 1n
Step-5: [Output]- Print sin(x) without using library function of Print sin(x) and with
using library function
Step-6: Stop
Page 43
Principles of Programming using C Laboratory 22POP13/23
FLOWCHART
Page 44
Principles of Programming using C Laboratory 22POP13/23
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
int fact(int m)
{
int i,f=1;
for(i=1;i<=m;i++)
{
f=f*i;
}
return f;
}
void main()
{
int x,n,i;
float rad, res, sum=0;
clrscr();
printf("Enter degree\n");
scanf("%d",&x);
printf("Enter number of terms\n");
scanf("%d",&n);
rad=x*3.14/180;
for(i=1;i<=n;i+=2)
{
if ((i-1)%4==0)
sum=sum+pow(rad,i)/fact(i);
else
sum=sum-pow(rad,i)/fact(i);
Page 45
Principles of Programming using C Laboratory 22POP13/23
}
printf("Calculate sin(%d) = %f", x,sum);
printf("\nLibrary sin(%d) = %f", x,sin(rad));
getch();
}
OUTPUT
First Run:
Enter degree
30
Enter number of terms
5
Calculate sin(30) = 0.499772
Library sin(30) = 0.499770
Second Run:
Enter degree
60
Enter number of terms
2
Calculate sin(60) = 0.866029
Library sin(60) = 0.865760
RESULT: -Thus, the program to calculate sin(x) has been executed successfully and the output was
verified.
VIVA QUESTIONS: -
Page 46
Principles of Programming using C Laboratory 22POP13/23
Laboratory Program 8
AIM: To develop a program to sort the given set of N numbers using Bubble sort.
ALGORITHM
Page 47
Principles of Programming using C Laboratory 22POP13/23
FLOWCHART
Page 48
Principles of Programming using C Laboratory 22POP13/23
PROGRAM
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,a[10],temp;
clrscr();
printf("Enter the no. of elements : \n");
scanf("%d",&n);
printf("Enter the array elements \n");
for(i = 0 ; i < n ; i++)
scanf("%d",&a[i]);
printf("The original elements are \n");
for(i = 0 ; i < n ; i++)
printf("%d ",a[i]);
for(i = 0 ; i < n-1 ; i++)
{
for(j = 0 ; j< (n-i)-1; j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf("\n The Sorted elements are \n");
for(i = 0 ; i < n ; i++)
printf("%d ",a[i]);
getch();
}
Page 49
Principles of Programming using C Laboratory 22POP13/23
OUTPUT
First Run:
Enter the no. of elements : 5
Enter the array elements
30 10 50 20 40
The original elements are
30 10 50 20 40
The Sorted elements are
10 20 30 40 50
Second Run:
Enter the no. of elements : 6
Enter the array elements
6 5 4 3 2 1
The original elements are
654321
The Sorted elements are
123456
RESULT: -Thus, the program to sort the elements using bubble sort has been executed successfully and
the output was verified.
VIVA QUESTIONS: -
Page 50
Principles of Programming using C Laboratory 22POP13/23
Laboratory Program 9
ALGORITHM
Step 1: Start
Step 2: [Input two source strings]
read source1,source2
Step 3: [Calculate length1 of source1 by calling the user defined function,strlength();
Repeat the same for length2 of source2 ]
length1=strlength(source1)
length2=strlength(source2)
Step 4: [Ouput length1,length2]
Print length1,length2
Step 5: [Compare the two strings by calling the user defined function, strcompare()]
k=strcompare(source1,source2)
Step 6: [check k, to find the whether the strings are same or not]
if(k==0)
print Both strings are same
else
print strings are different
end if
Step 7: [Concatenate two strings by calling the user defined function, strconcat() and the concatenated
string is stored in source1]
strconcat(source1,source2)
print source1
Step 8: Stop
User Defined Function - strlength()
Page 51
Principles of Programming using C Laboratory 22POP13/23
Step 1: Start
Step 2: [set i=0]
i=0
Step 3: [receive the source string as str, read character by character, count one by one until we reach
NULL character]
while(str[i]!=’\0')
i++ end while
Step 4: [return i to the calling function]
return i
User Defined Function - strcompare( )
Step 1: Start
Step 2: [set i=0]
i=0
Step 3: [Receive both the source strings as str1 and str2, read character by character until they match, if
the matched character is a NULL then go out of while loop, when any unmatched character then go out of
loop]
while(str1[i] = = str2[i])
if(str1[i] = = ’\0')
break
end if
i++
end while
Step 4: [calculate k]
k=str1[i]-str2[j]
Step 5: [return i to the calling function]
return k
User Defined Function - strconcat( )
Step 1: Start
Step 2: [set i=0]
i=0
Step 3: [Receive both the source strings as str1 and str2, calculate length of str1 using strlength() as l]
Page 52
Principles of Programming using C Laboratory 22POP13/23
l=strlength(str1)
Step 4: [read str2 character by character and store it from the end of str1]
while(str2[i]!=’\0')
str1[l+i]=str2[i]
i++
end while
Step 5: [return to the calling function]
return;
Page 53
Principles of Programming using C Laboratory 22POP13/23
Page 54
Principles of Programming using C Laboratory 22POP13/23
PROGRAM
#include<stdio.h>
#include<conio.h>
int strlength(char str1[50]);
Page 55
Principles of Programming using C Laboratory 22POP13/23
i++;
}
str1[l+i]=’\0';
}
int strcompare(char str1[50],char str2[50])
{
int i=0, k;
while(str1[i]==str2[i])
{
if(str1[i]==’\0')
break;
i++;
}
k=str1[i]-str2[i];
return k;
}
void main()
{
char source1[50],source2[50],dest[50];
int length1,length2,k;
clrscr();
printf(“\n Enter the source string 1:”);
gets(source1);
printf(“\n Enter the source string 2:”);
gets(source2);
length1=strlength(source1);
length2=strlength(source2);
printf(“\n string length of string 1 is %d”,length1);
printf(“\n string length of string 2 is %d”,length2);
k=strcompare(source1,source2);
if(k==0)
printf(“\n Both string are same”);
Page 56
Principles of Programming using C Laboratory 22POP13/23
else
printf(“\n Both string are different”);
strconcat(source1,source2);
printf(“\n concatenated string is “);
puts(source1);
getch();
}
OUTPUT
First Run:
Enter the source string1: good
Enter the source string2: night
String length of string1 is: 4
String length of string2 is: 5
strings are different
concatenated string is: goodnight
Second Run:
Enter the source string1: good
Enter the source string2: good
String length of string1 is: 4
String length of string2 is: 4
Both strings are same
concatenated string is: goodgood
RESULT: - Thus, the program to implement string operations such as compare, concatenate, string
length has been executed successfully and the output was verified.
VIVA QUESTIONS: -
a. What is string?
b. How to declare string?
c. What are the string manipulation function?
d. What is gets() and puts() function in string?
Page 57
Principles of Programming using C Laboratory 22POP13/23
Laboratory Program 10
AIM: To write a C Program to implement structures to read, write and compute average-
marks of the students, list the students scoring above and below the average marks for a
class of N students.
ALGORITHM
Step-1: Start
Step-2: Read number of students
Step-3: For every student, read the student id, name , marks for all the subjects
Step-4: Calculate the average marks and store it in the avg field
Step-5: Print the results
Step-6: Initialise loop
Step-7: Read the average of every student
Step-8: Check for if avg>35.00
Step-9: If yes than print the result else goto next iteration
Step-10: Initialise the loop
Step-11: Read average of every student
Step-12: Check if avg<35.00
Step-13: If yes than print result else goto next iteration
Step-14: Stop
Page 58
Principles of Programming using C Laboratory 22POP13/23
FLOWCHART
Page 59
Principles of Programming using C Laboratory 22POP13/23
PROGRAM
#include<stdio.h>
#include<conio.h>
struct student
{
char usn[10];
char name[10];
int m1,m2,m3;
float avg, total;
};
void main()
{
struct student s[20];
int n,i;
float tavg,sum=0.0;
clrscr();
printf("Enter the number of students");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the detail of %d students\n",i+1);
printf("\n Enter USN=");
scanf("%s",s[i].usn);
printf("\n Enter Name=");
scanf("%s",s[i].name);
printf("\nEnter the three subjects marks\n");
scanf("%d%d%d",&s[i].m1,&s[i].m2,&s[i].m3);
s[i].total=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].total/3;
}
for(i=0;i<n;i++)
{
Page 60
Principles of Programming using C Laboratory 22POP13/23
if(s[i].avg>=35)
printf("\n %s has scored above the average marks",s[i].name);
else
printf("\n %s has scored below the average marks",s[i].name);
}
getch();
}
OUTPUT
Enter the number of students2
Enter the detail of student 1
Enter USN=1
Enter Name=Arun
Enter the three-subject score
23 45 67
Enter the detail of student 2
Enter USN=2
Enter Name=Tharun
Enter the three-subject score
532
Arun has scored above the average marks
Tharun has scored below the average marks
RESULT: -Thus, the program to implement structures to read, write and compute average- marks of the
students, list the students scoring above and below the average marks for a class of N students has been
executed successfully and the output was verified.
VIVA QUESTIONS: -
a. What is structure?
b. How to declare a structure?
c. What is structure member?
d. What is difference between array and structure?
e. What is nested structure?
f. What is typedef?
Page 61
Principles of Programming using C Laboratory 22POP13/23
Laboratory Program 11
Page 62
Principles of Programming using C Laboratory 22POP13/23
FLOWCHART
Page 63
Principles of Programming using C Laboratory 22POP13/23
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int n , i;
float x[20],sum,mean;
float variance , deviation;
clrscr();
printf("Enter the value of n \n");
scanf("%d",&n);
printf("enter %d real values \n",n);
for (i=0;i<n;i++)
{
scanf("%f",(x+i));
}
sum=0;
for(i=0;i<n;i++)
{
sum= sum+*(x+i);
}
printf("sum=%f\n",sum);
mean=sum/n;
sum=0;
for(i=0;i<n;i++)
{
sum=sum+(*(x+i)-mean)*(*(x+i)-mean);
}
variance=sum/n;
deviation=sqrt(variance);
printf("mean(Average)=%f\n",mean);
Page 64
Principles of Programming using C Laboratory 22POP13/23
printf("variance=%f\n",variance);
printf("standard deviation=%f\n",deviation);
getch();
}
Output:
Enter the value of n
5
Enter the 5 real values
3
7
23
1
4
Sum = 38.0000
Mean ( Average ) = 7.6000
Variance = 63.039997
Standard deviation = 7.9397
RESULT: -Thus, the program to implement pointers to compute the sum, mean and standard deviation of
all elements stored in an array of n real numbers has been executed successfully and the output was verified.
VIVA QUESTIONS:-
a. Define pointer
b. Define array of pointer
c. Difference between (x+i) and *(x+i)
d. Define array
Page 65
Principles of Programming using C Laboratory 22POP13/23
Laboratory Program 12
WRITE A C PROGRAM TO COPY A TEXT FILE TO ANOTHER, READ BOTH THE INPUT
FILE NAME AND TARGET FILE NAME.
AIM: To Write a C program to copy a text file to another, read both the input file name
and target file name.
ALGORITHM
Step 1 : Start
Step 2: Read the source file name fname1
Step 3: Open the file fname1 in read mode
Step 4: if fptr1 is equal to NULL
print " File does not found or error in opening.!!”
goto Step 12
Step 5: Read the new file name fname2
Step 6: Open the file fname2 in write mode
Step 7: if fptr2 is equal to NULL
print " File does not found or error in opening.!!"
goto Step 12
Step 8: Repeat while(1)
ch=fgetc(fptr1);
if ch is equal to EOF
break;
else
fputc(ch, fptr2);
Step 9: print “The file fname1 copied successfully in the file fname2”
Step 10: close file pointer fptr1
Step 11: close file pointer fptr2
Step 12: Stop
Page 66
Principles of Programming using C Laboratory 22POP13/23
FLOWCHART
Page 67
Principles of Programming using C Laboratory 22POP13/23
PROGRAM
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
FILE *fptr1, *fptr2;
char ch, fname1[20], fname2[20];
clrscr();
fptr1=fopen(fname1, "r");
if(fptr1==NULL)
{
printf(" File does not found or error in opening.!!");
exit(1);
}
printf(" Input the new file name : ");
scanf("%s",fname2);
fptr2=fopen(fname2, "w");
if(fptr2==NULL)
{
printf(" File does not found or error in opening.!!");
fclose(fptr1);
exit(2);
}
while(1)
{
ch=fgetc(fptr1);
if(ch==EOF)
{
break;
}
else
Page 68
Principles of Programming using C Laboratory 22POP13/23
{
fputc(ch, fptr2);
}
}
printf(" The file %s copied successfully in the file %s. \n\n",fname1,fname2);
fclose(fptr1);
fclose(fptr2);
getchar();
}
OUTPUT:
RESULT: - Thus, the program to copy a text file to another, read both the input file name and target file
name has been executed successfully and the output was verified.
VIVA QUESTIONS:-
a. Define file.
b. What is fopen() and fclose() in file?
c. What is fgetc() and fputc() in file?
Page 69