0% found this document useful (0 votes)
42 views45 pages

Lab Manual

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views45 pages

Lab Manual

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

RV Institute of Technology & Management®

PRINCIPLES OF PROGRAMMING LABORATORY


Course Code BPOPS13/23 CIE Marks 50
Teaching Hours/Week (L: T:P: S) 2:0:2:0 SEE Marks 50
Total Hours of Pedagogy -- Total Marks 100
Credits 02 Exam Hours 03
Course Objectives:
1. Explain problem statements and identify appropriate solutions
2. Demonstrate the use of IDE, C Compiler, and identify and rectify the syntax and
syntactic errors during programming.
3. Development of algorithms and programs using constructs of C programming language
4. Reporting the observations
1. Simulation of a Simple Calculator.
2. Compute the roots of a quadratic equation by accepting the coefficients. Print appropriate messages.
3. An electricity board charges the following rates for the use of electricity: for the first 200 units 80
paise per unit for the next 100 units 90 paise per unit beyond 300 units Rs. 1 per unit. All users are
charged a minimum of Rs. 100 as meter charge. If the total amount is more than Rs. 400, then an
additional surcharge of 15% of total amount is charged. Write a program to read the name of the user,
number of units consumed and print out the charges.
4. Write a C Program to display the following by reading the number of rows as input,
1
121
12321
1234321
5. Implement Binary Search on Integers.
6. Implement Matrix multiplication and validate the rules of multiplication.
7. Compute sin(x)/cos(x) using Taylor series approximation. Compare your result with
the built-in library function. Print both the results with appropriate inferences.
8. Sort the given set of N numbers using Bubble sort.
9. Write functions to implement string operations such as compare, concatenate, and find
String length. Use the parameter passing techniques.
10. 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.
11. Develop a program using pointers to compute the sum, mean and standard deviation of all
elements stored in an array of N real numbers.
12. Write a C program to copy a text file to another, read both the input file name and target file name.

I & II-Semester, BPOPS13/23 Page 1 | 42


RV Institute of Technology & Management®

1. Familiarization with programming environment, concept of naming the program files,


storing, compilation, execution and debugging. Taking any simple C- code.

Introduction

A computer is a machine that manipulates data according to a list of instructions called a


program. The block diagram of computer is shown in Fig 1.

Control Unit

Fig 2: Fundamental block diagram of a computer


Central Processing Unit (CPU) :A CPU is brain of a computer. It is responsible for all
functions and processes. Regarding computing power, the CPU is the most important element
of a computer system. The CPU is comprised of three main parts :

I & II-Semester, BPOPS13/23 Page 2 | 42


RV Institute of Technology & Management®

Arithmetic Logic Unit (ALU): Executes all arithmetic and logical operations. Arithmetic
calculations like as addition, subtraction, multiplication and division. Logical operation like
compare numbers, letters, or special characters

Control Unit (CU): controls and co-ordinates computer components.


● Read the code for the next instruction to be executed. 2.Increment the program counter
so it points to the next instruction.
● Read whatever data the instruction requires from cells in memory.
● Provide the necessary data to an ALU or register.
● If the instruction requires an ALU or specialized hardware to complete, instruct the
hardware to perform the requested operation.

Registers : Stores the data that is to be executed next, "very fast storage area".

Buses:
The buses on a computer system are sets of wires that carry information to or from memory or
I/O devices. They may be uni-directional (data travels one way) or bi-directional (data travels
both ways).
Buses can be seen on the computer motherboard as parallel metal tracks. It connects physical
components such as cables, printed circuits, CPU, Memory, Peripherals etc., for sharing of
Information and communication with one another. The purpose of buses is to reduce the
number of "pathways" needed for communication between the components, by carrying out all
communications over a single data channel. Fig 3 shows the different types of buses.

Types of buses:

Fig 3 : Different types of buses


Address Bus:
● The address bus carries the address of the piece of memory or I/O device to be read
from or written to.
● It is a unidirectional bus, which is to say that data travels only one way; from the CPU
to memory.
● The number of lines on the bus determines the number of addressable memory
elements. For example an 8 bit bus can represent 2 to the power of 8 unique addresses.

I & II-Semester, BPOPS13/23 Page 3 | 42


RV Institute of Technology & Management®

This equates to 256 unique memory addresses. A 16 bit bus can address 65536 unique
addresses and so on.

Data Bus:
● The data bus carries the data that is to be written or has been read from memory.
● It is a bidirectional bus as it can carry data to or from memory.
● The width of the data bus is directly related to the largest number that the bus can carry.
For example an 8 bit bus can represent 2 to the power of 8 unique values. This equates
to the numbers 0 to 255. A 16 bit bus can carry the values 0 to 65535 and so on.

Control Bus:
● The control bus carries signals that control the actions of the computer.
● For example one line of the control bus may be the read/write line. If the wire is low
(no electricity flowing) then the memory is read. If the wire is high (with electricity
flowing) then the memory is written.

Mother Board
A motherboard is one of the most essential parts of a computer system. It holds together many
of the crucial components of a computer, including the central processing unit (CPU), memory
and connectors for input and output devices. Fig 4 shows the picture of motherboard.

Fig 4 : Picture of a mother board

The base of a motherboard consists of a very firm sheet of non-conductive material, typically
some sort of rigid plastic. Thin layers of copper or aluminum foil, referred to as traces, are
printed onto this sheet. These traces are very narrow and form the circuits between the various
components. In addition to circuits, a motherboard contains a number of sockets and slots to
connect the other components.

A typical mother board contains the following components:

I & II-Semester, BPOPS13/23 Page 4 | 42


RV Institute of Technology & Management®

● A CPU socket - the actual CPU is directly soldered onto this socket. Since high speed
CPUs generate a lot of heat, there are heat sinks and mounting points for fans right next
to the CPU socket.
● A power connector to distribute power to the CPU and other components.
● Slots for the system's main memory, typically in the form of DRAM chips.
● A chip forms an interface between the CPU, the main memory and other components.
On many types of motherboards this is referred to as the Northbridge. This chip also
contains a large heat sink.
● A second chip controls the input and output (I/O) functions. It is not connected directly
to the CPU but to the Northbridge. This I/O controller is referred to as the Southbridge.
The Northbridge and Southbridge combined are referred to as the chipset.
● Several connectors, which provide the physical interface between input and output
devices and the motherboard. The Southbridge handles these connections.
● Slots for one or more hard drives to store files. The most common types of connections
are Integrated Drive Electronics (IDE) and Serial Advanced Technology Attachment
(SATA).
● A Read-only memory (ROM) chip, which contains the firmware, or startup instructions
for the computer system. This is also called the BIOS.
● A slot for a video or graphics card. There are a number of different types of slots,
including Accelerated Graphics Port (AGP) and Peripheral Component Interconnect
Express (PCIe).

Chipset :
The actual function of a chipset is to communicate between all components of the modern PC,
or, to put it in other words, the chipset is the infrastructure. The chipset contains numerous
components, and moreover, it makes various interfaces available for connecting additional
components (PCI, USB, AGP, IDE, etc). As a rule, the chipset consists of two units, the
Northbridge and the Southbridge. The reason that it is made of two units instead of one is that
it's difficult to integrate all components onto a single chip. The use of two chips also allows for
different combinations of Southbridge and Northbridge chips. Today, most manufacturers have
a small building-block type of system from which the motherboard makers can choose
components to suit customer requirements.

Network interface card (NIC): A network interface card (NIC) is a circuit board or card that
is installed in a computer so that it can be connected to a network.
A network interface card provides the computer with a dedicated, full-time connection to a
network. Personal computers and workstations on a local area network (LAN) typically contain
a network interface card specifically designed for the LAN transmission technology.

Computer Components:
A computer system consists of both hardware and information stored on hardware. Information
stored on computer hardware is often called software.

The hardware components of a computer system are the electronic and mechanical parts.

I & II-Semester, BPOPS13/23 Page 5 | 42


RV Institute of Technology & Management®

Computer hardware is the collection of physical elements that constitutes a computer system.
Computer hardware refers to the physical parts or components of a computer such as the
monitor, mouse, keyboard, computer data storage, hard drive disk (HDD), system unit (graphic
cards, sound cards, memory, motherboard and chips), etc. all of which are physical objects that
can be touched.

Hardware:
The major hardware components of a computer system are:

1. Primary Memory / Volatile Memory.


2. Secondary Memory / Non Volatile Memory.

1. Primary Memory / Volatile Memory– Primary memory is internal memory of the


computer. It is also known as main memory and Temporary memory .Primary Memory holds
the data and instruction on which computer is currently working. Primary Memory by is nature
volatile that is when power is switched off its data will be lost.

I & II-Semester, BPOPS13/23 Page 6 | 42


RV Institute of Technology & Management®

Types of Primary Memory– Primary memory is generally of two types:

1. RAM
2. ROM

1. RAM (Random Access Memory) – It stands for Random Access Memory. RAM is known
as read /writes memory. It generally refereed as main memory of the computer system. It is a
temporary memory. The information stored in this memory is lost as the power supply to the
computer is switched off. That’s why RAM is also called “Volatile Memory”.

Types of RAM– RAM is also of two types:

a) Static RAM- Static RAM also known as SRAM ,retain stored information as long as the
power supply is ON. SRAM are of higher coast and consume more power .They have higher
speed than Dynamic RAM

b) Dynamic RAM– Dynamic RAM also known as DRAM, its stored information in a very
short time (a few milliseconds) even though the power supply is ON. The Dynamic RAM are
cheaper and moderate speed and also they consume less power.

2. ROM (Read Only Memory) – It stands for Read Only Memory.ROM is a Permanent Type
memory. Its content are not lost when power supply is switched off. Content of ROM is decided
by the computer manufacturer and permanently stored at the time of manufacturing. ROM
cannot be overwritten by the computer. It is also called “Non-Volatile Memory”.

Type of ROM: ROM memory is three types names are following-

a) PROM(Programmable Read Only Memory)-PROM chip is programmable ROM.it is


PROM chips to write data once and read many.once chip has been programmed ,the recorded
information cannot be changed. PROM is also nonvolatile memory.
b) EPROM (Erasable Programmable Read Only Memory)- EPROM chip can be
programmed time and again by erasing the information stored earlier in it. Information stored
in EPROM exposing the chip for some time ultraviolet light .
c) EEPROM (Electrically Erasable Programmable Read Only Memory)-The EEPROM is
programmed and erased by special electrical waves in millisecond. A single byte of a data or
the entire contents of device can be erased.

2. Secondary Memory / Non Volatile Memory–


Secondary Memory is external memory of the computer. It is also known as Auxiliary memory
and permanent memory. It is used to store the different programs and the information
permanently.
Secondary Memory is nature non volatile. It means data is stored permanently even if power
is switched off.

The secondary storage devices are:


1. Floppy Disks

I & II-Semester, BPOPS13/23 Page 7 | 42


RV Institute of Technology & Management®

2. Magnetic (Hard) Disk


3. Magnetic Tapes
4. Pen Drive
5. Winchester Disk
6. Optical Disk(CD,DVD)

Input Devices :Input device is any peripheral (piece of computer hardware equipment to
provide data and control signals to an information processing system such as a computer or
other information appliance. Input device Translate data from form that humans understand to
one that the computer can work with. Most common are keyboard and mouse.

Output devices: Every computer system will need to have a way of displaying information or
printing information out so that it is useful to humans. There needs to be, therefore, some
‘output devices’. A very useful output device is a VDU (or Visual Display Unit). Another
handy one that allows you to produce ‘hardcopy’ (i.e. a printout on paper) is a printer.

Software:
Software is a set of programmes/commands designed to perform a well-defined task.
Software systems can be divided into two major classes:

• System software: Helps run the computer hardware and computer system itself. System
software includes operating systems, device drivers, diagnostic tools and more. System
software is almost always pre-installed on your computer.
• Application software: Allows users to accomplish one or more tasks. It includes word
processing, web browsing and almost any other task for which you might install software.
(Some application software is pre-installed on most computer systems.)

Software is generally created /written in a high-level programming language, one that is (more
or less) readable by people. These high -level instructions are converted into "machine
language" instructions, represented in binary code, before the hardware can "run the code".

Utility Software: is system software designed to help analyze, configure, optimize or maintain
a computer. Utility software, along with operating system software, is a type ofsystem software
used to support the computer infrastructure, distinguishing it from application software which
is aimed at directly performing tasks that benefit ordinary users. PDF Creator,File Archiving
and PDF Converters are commonly used utility software.

Operating System:
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.

I & II-Semester, BPOPS13/23 Page 8 | 42


RV Institute of Technology & 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 is an O.S. is used for Personal Computers (PCs) Unix and XENIX are the OSs
used for multi- user computers. Windows 7, Windows 8, Windows 10, Macintosh OS, Fedora,
and Android, etc.

Types of Operating Systems:


The operating systems are classified into 7 types based on their capability and usage.

Batch Processing 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.

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).

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.

Multi user and multitasking OS: The OS 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.

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.

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.,

Virtual machine OS: Allows several users of a computer system to operate as if each has the
only terminal attached to the computer.

I & II-Semester, BPOPS13/23 Page 9 | 42


RV Institute of Technology & Management®

Fundamentals of algorithms and flowcharts with examples


Algorithm:
An algorithm is defined as unambiguous, step by step procedure (instructions) to solve
a given problem in finite number of steps by accepting a set of inputs and producing the desired
output. After producing the result, the algorithm should terminate. An algorithm is ‘an effective
procedure for solving a problem in a finite number of steps. Usually, Algorithms are written in
simple English like statements along with simple mathematical expressions.

Algorithm to add 2 numbers:


Step 1: Start
Step 2: [Read 2 values a and b to be added] Read a,b.
Step 3: [Find the sum of 2 numbers] sum=a+b.
Step 4: [Output the result] Print sum.
Step 5: [End of Algorithm] Stop

Algorithm to find Area of Rectangle:


Step 1: Start
Step 2: [Read the values of length and breadth] Read length, breadth.
Step 3: [Find the area of rectangle] Area=length*breadth.
Step 4: [Output the result] Print area.
Step 5: [End of Algorithm] Stop

Algorithm to find swap 2 numbers:


Step 1: Start
Step 2: [Read the values A and B] Read A,B
Step 3: [Find A AND B] C=A A=B B=C
Step 4: [Output the result] Print A AND B.
Step 5: [End of Algorithm] Stop

Flowchart:

A flowchart is a pictorial representation of an algorithm. That is flowchart consists


of sequence of instructions that are carried out in an algorithm. All the steps are drawn in the
form of different shapes of boxes, circle and connecting arrows. Flowcharts are mainly used to
help programmer to understand the logic/the flow of the program.

The various types of geometric shapes, arrows and symbols used while drawing the flow chart
are called flowchart symbols. The symbols used and the meaning associated with each symbol
are shown below in Fig 6.

I & II-Semester, BPOPS13/23 Page 10 | 42


RV Institute of Technology & Management®

Fig 6: Flow chart symbols


Flow chart to find the area of rectangle:

I & II-Semester, BPOPS13/23 Page 11 | 42


RV Institute of Technology & Management®

Flowchart for swapping contents of 2 variables:

I & II-Semester, BPOPS13/23 Page 12 | 42


RV Institute of Technology & Management®

1. Simple Calculator Program

Procedure: This program takes an arithmetic operator +,-,*,/,% and two operands from the user and
performs the calculation on the two operands depending upon the operator entered by the user.
Input: An operator and two operands.
Expected Output: Performs calculation and display result depending upon the operator.

ALGORITHM
Algorithm Calculator

Step 1: Start
Step 2: Read num1 and num2
Step 3: Enter the operator
Step 4: Evaluate operator wit case statements
Step 4.1: case ‘+’ : result = num1+num2
goto step 6
Print result
Step 4.2: case ‘-’ : result = num1-num2
goto step 6
Print result
Step 4.3: case ‘*’ : result = num1*num2
goto step 6
Print result
Step 4.4: case ‘/’ : result = (float)num1/(float)num2
goto step 6
Print result
Step 4.5: case ‘%’ : result = num1%num2
goto step 6
Print result
Step 5: Enter operator is invalid then
Print “Invalid Operation”
Step 6: Print result
Step 7: Stop

I & II-Semester, BPOPS13/23 Page 13 | 42


RV Institute of Technology & Management®

FLOWCHART

I & II-Semester, BPOPS13/23 Page 14 | 42


RV Institute of Technology & Management®

/* Program to design simple commercial calculator */

#include <stdio.h>
int main()
{
int num1, num2;
float result=0;
char ch;
printf("Choose operation to perform (+,-,*,/,%): ");
scanf(" %c", &ch);
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);

switch(ch)
{
case '+':result=num1+num2;
break;
case '-':result=num1-num2;
break;
case '*': result=num1*num2;
break;
case '/':result=(float)num1/(float)num2;
break;
case '%': result=num1%num2;
break;
default: printf("Invalid operation.\n");
exit(0);
}
printf("Result: %d %c %d = %f\n",num1,ch,num2,result); //display output on screen

I & II-Semester, BPOPS13/23 Page 15 | 42


RV Institute of Technology & Management®

2. Compute the roots of a quadratic equation by accepting the coefficients. Print


appropriate messages.

Procedure: The equation in the form ax2+bx+c=0 is called quadratic equation. Read the
coefficients a,b,c and calculate discriminant. Based on the discriminant value, calculate roots and
print them with suitable messages.

Input: Three coefficients of quadratic equation ax2+bx+c=0: a, b, c

Expected Output: This program computes all possible roots for a given set of coefficients with
appropriate messages. The possible roots are: Real and Equal roots, Real and distinct roots,
imaginary roots.

ALGORITHM

Quadratic_Equation [This algorithm takes three coefficients as input and compute the roots]

Step 1: [Start of the algorithm]


Start
Step 2: [Read the coefficients]
Read non zero coefficients a,b,c
Step 3: [calculate the discriminant]
d◻b*b-4*a*c
Step 4: [check if roots are real and equal]
if (d=0)
x1-b/(2*a)
x2-b/ (2*a)
Print “Roots are equal”
Print x1, x2
Go to step 7
Step 5: [check if roots are real and distinct]
If(d>0)
x1(-b+sqrt (d)/ (2*a))
x2(-b-sqrt (d)/ (2*a))
Print “Roots are real and distinct”
Print x1, x2
Go to step 7
Step 6: [check if roots are imaginary]
If(d<0)
x1 -b/(2*a)
xsqrt (fabs(d))/(2*a)
Print “ The roots are complex”
Print “Root1  “, x1+ix2
Print “ Root2“, x1-ix2

Step 7: [terminate the algorithm]


Stop

I & II-Semester, BPOPS13/23 Page 16 | 42


RV Institute of Technology & Management®

Program:

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

int main()
{
float a,b,c,d,rpart,ipart,root1,root2;
printf("Enter three co-efficient\n");
scanf("%f%f%f",&a,&b,&c);

if(a==0 && b==0)


{
printf(“Invalid inputs”);

}
else if(a==0)
{
printf(“Linear Equation\n”);
root1=-c\b;
printf(“Root=%f\n”,root1);
}
else
{
d=(b*b)-(4*a*c);
if(d==0)
{
printf("The roots real and equal\n");
root1= -b/(2*a);
root2=root1;
printf("The roots are root1=%.3f and root2=%.3f\n",root1,root2);
}
else if(d>0)
{
printf("The roots are real and distinct\n");
root1=(-b+sqrt(d))/(2*a);
root2=(-b-sqrt(d))/(2*a);
printf("The roots are root1=%.3f and root2=%.3f\n",root1,root2);
}
else
{
printf("The roots are imaginary\n");
rpart=-b/(2*a);
ipart=sqrt(fabs(d))/(2*a);
printf("The first root root1=%.3f+i%.3f\n",rpart,ipart);
printf("The second root root2=%.3f-i%.3f\n",rpart,ipart);
}
}
}

I & II-Semester, BPOPS13/23 Page 17 | 42


RV Institute of Technology & Management®

3. An electricity board charges the following rates for the use of electricity: for the first 200
units 80 paise per unit: for the next 100 units 90 paise per unit: beyond 300 units Rs 1
per unit. All users are charged a minimum of Rs. 100 as meter charge. If the total
amount is more than Rs 400, then an additional surcharge of 15% of the total amount is
charged. Write a program to read the name of the user, the number of units consumed,
and print out the charges.

Input: Consumer name and number of units

Expected Output: This program checks all else if ladder conditions as per number of units
consumed by consumer and display appropriate output

ALGORITHM:

Step 1: Start
Step 2: Read name & unit
Step 3: if(unit <=200)
charge = unit *0.8+ 100
else if(unit<=300)
charge=(unit-200) *0.90+160;
else if(unit>300)
charge=(unit-300) *1+250;
if(charge>=400)
charge=charge + charge*0.15;

Step 4: Display the charges


Step 5: Stop

I & II-Semester, BPOPS13/23 Page 18 | 42


RV Institute of Technology & Management®

Flowchart:

I & II-Semester, BPOPS13/23 Page 19 | 42


RV Institute of Technology & Management®

PROGRAM

#include <stdio.h>
int main()
{
char name[10];
float unit, charge, min=100 ;
printf("Enter your name and unit Consumed:\n");
scanf("%s%f",name, &unit);

if(unit<=200)
charge=unit*.80+min;
else if(unit<=300)
charge=(unit-200)*0.90+160+min;
else
{
if(unit>300)
charge=(unit-300) *1+250+min;
}
if(charge>=400)
charge=charge + charge*0.15;

printf("Name: %s\n Charge: %.3f\n", name, charge);

I & II-Semester, BPOPS13/23 Page 20 | 42


RV Institute of Technology & Management®

4. Write a C Program to display the following by reading the number of rows as input,
1
121
12321
1234321

Procedure: Input n rows, display numbers in ascending order till middle and reverse the order when
reaches the middle.
Input: Number of rows
Expected Output: For each row after it reaches the corresponding element which matches with the row
number, the reversing of elements happens.

ALGORITHM:

Step 1: Start
Step 2: Read i, j, n
Step 3: if j=0; j<=n-1; j++
Display blank spaces
if j=1;j<=i;j++
Display numbers in ascending order up to middle
If j=i-1;j>=1;j--
Display number in reverse order after middle
Step 4: Display the result
Step 5: Stop

I & II-Semester, BPOPS13/23 Page 21 | 42


RV Institute of Technology & Management®

FLOWCHART

PROGRAM

#include <stdio.h>
void main()
{
int i,j,n;
printf("Input number of rows : ");
scanf("%d",&n);
for(i=0;i<=n;i++)
I & II-Semester, BPOPS13/23 Page 22 | 42
RV Institute of Technology & Management®

{
/* print blank spaces */
for(j=0;j<=n-1;j++)
printf(" ");
/* Display number in ascending order upto middle*/
for(j=1;j<=i;j++)
printf("%d",j);
/* Display number in reverse order after middle */
for(j=i-1;j>=1;j--)
printf("%d",j);

printf("\n");
}
}

5 Implement Binary Search on Integers / Names.

Introduce 1D Array manipulation and implement Binary search.

Procedure: Input N array elements and to find whether element is present or not.
Input: Array elements.
Expected Output: Successful search or unsuccessful search.

ALOGRITHM
Algorithm bubble_sort
Step 1: Start
Step 2: Read n
Step 3: Repeat for i=0 to n-1
Read a[i]
Step 4: read key
Step 5: Initialize low =0 high = n-1
Step 6: Repeat through step 6 while (low <= high)
mid = (low+ high)/2
if(key==a[mid])
found=1
else if(key>a[mid])
low=mid+1
else
high=mid-1
end while
Step 7: if(found ==1)
print “Item found”
else
print” Item not found”
Step 8: Stop

I & II-Semester, Principles of Programming Lab 22POP13/23 Page23 | 42


RV Institute of Technology & Management®

FLOWCHART:

I & II-Semester, Principles of Programming Lab 22POP13/23 Page24 | 42


RV Institute of Technology & Management®

PROGRAM

#include<stdio.h>
int main()
{
int i,n,a[10],mid,low,high,key, found=0;

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


scanf("%d", &n);
printf("Enter the array element in the ascending order\n");
for(i=0;i<n;i++)
{
scanf("%d", &a[i]);
}

printf("\n 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])
{
found=1;
exit(0);
}
else if(key>a[mid])
low=mid+1;
else
high=mid-1;
}

if(found ==1)
printf(“Item found in position : %d”,mid+1);
else
printf("\n Item not found\n");
}

I & II-Semester, Principles of Programming Lab 22POP13/23 Page25 | 42


RV Institute of Technology & Management®

6 Implement Matrix multiplication and validate the rules of multiplication.


Procedure: Input m*n and p*q size of 2 matrices elements to compute matrix multiplication.

ALGORITHM

Step 1: [Start of the algorithm]


Start
Step 2: [Read the order of the matrix A]
Read m,n
Step 3: [Read the order of the matrix B]
Read p,q
Step 4: [To check for compatibility condition of matrix multiplication]
if(n!=p)
print “Matrix multiplication not possible”
go to step 11
Step 5: [Read the elements of matrix A]
Repeat through step 5 for i0 to m-1
Repeat for j0 to n-1
Read a[i][j]
Step 6: [Read the elements of matrix B]
Repeat through step 6 for j0 to q-1
Repeat for i0 to p-1
Read b[i][j]
Step 7: [Display the elements of matrix A]
Repeat through step 7 for i0 to p-1
Repeat for j0 to q-1
Print a[i][j]
Step 8: [Display the elements of matrix B]
Repeat through step 8 for i0 to p-1
Repeat for j0 to q-1
Print b[i][j]
Step 9: [Calculate the product of two given matrices]
Repeat through step 9 for i0 to m-1
Repeat for j0 to q-1
c[i][j] 0
Repeat for k0 to n-1
c[i][j] c[i][j]+a[i][k]*b[k][j]
Step 10: [Print the resultant matrix]
Repeat step 10 for i0 to m-1
Repeat for j0 to n-1
Print c[i][j]
Step 11: [terminate the algorithm]
Stop

I & II-Semester, Principles of Programming Lab 22POP13/23 Page26 | 42


RV Institute of Technology & Management®

PROGRAM

#include<stdio.h>
#include<conio.h>
int main()
{
int m,n,p,q,i,j,k,a[10][10],b[10][10],c[10][10];
printf("Enter the size matrix A \n");
scanf("%d%d",&m,&n);
printf("Enter the size matrix B \n");
scanf("%d%d",&p,&q);

if(n!=p)
{
printf(“Matrix multiplication is not possible\n”);
}
else
{
printf("Enter the elements of matrix A \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf ("%d",&a[i][j]);
}
printf("Enter the elements of matrix B \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(‘A-matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}

printf("B- matrix is \n");

I & II-Semester, Principles of Programming Lab 22POP13/23 Page27 | 42


RV Institute of Technology & Management®

for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}

printf("The resultant matrix C is \n");


for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}

I & II-Semester, Principles of Programming Lab 22POP13/23 Page28 | 42


RV Institute of Technology & Management®

7. Compute sin(x)/cos(x) using Taylor series approximation. Compare your result with the built-
in library function. Print both the results with appropriate inferences.

ALGORITHM

Algorithm: Sine_series
Step 1:[Start the algorithm]
Start
Step 2:[Read the value of x]
Read x
Step 3:[Initialize the variables]
x1x;
xx*(3.142/180.0)
Step 4;[Read the value of no of terms]
Read n
Step 5:[Initialize the variables]
termx;
sinxterm;
Step 6:[Repeat the following steps for n=1 to n terms
den2*n*(2*n+1)
term-term*x*x/den;
sum=sum+term;
Step 7:Print the result
sum of sine series=sum
sum using library function=sin(x)
Step 8: Stop

I & II-Semester, Principles of Programming Lab 22POP13/23 Page29 | 42


RV Institute of Technology & Management®

FLOWCHART

x←degree*(PI/180)

nume←x
fact←1
sum←x

Term← nume/fact
nume← -nume*x*x
fact← fact*i *(i+1)
sum←sum+term
i-i+2

if
term>=

predefined sine

I & II-Semester, Principles of Programming Lab 22POP13/23 Page30 | 42


RV Institute of Technology & Management®

Program:
#include<stdio.h>
#include<math.h>
#define PI 3.142

int main()
{
int i, degree;
float x,sum=0,term,nume,fact;
printf("Enter value of degree \n");
scanf("%d", &degree);

x=degree*(PI/180);
nume=x;
fact=1;
i=2;
do
{
term= nume/fact;
nume=-nume*x*x;
fact=fact*i*(i+1);
sum= sum+term;
i=i+2;
}while(fabs(term)>=0.00001);
printf("The sine of %d is %.3f",degree,sum);
printf("Using inbuilt function sin(%d) is %.3f",degree,sin(x));

I & II-Semester, Principles of Programming Lab 22POP13/23 Page31 | 42


RV Institute of Technology & Management®

8. Sort the given set of N numbers using Bubble sort.

ALGORITHM

Bubble sort
Step 1: [Start of the algorithm]
Start
Step 2: [Read the size of the array]
read n
Step 3: [Read the array elements]
Repeat for i0 to n-1
read a[i]
Step 4: [Print the given array]
Repeat for i0 to n-1
print a[i]
Step 5: Repeat through step 5 for i1 to n-1
Repeat for j0 to n-i
if(a[j]>a[j+1])
tempa[j]
a[j] a[j+1]
a[j+1] temp
Step 5: [Print the sorted array]
Repeat for i 0 to n-1
print a[i]
Step 6 :[terminate the algorithm]
Stop

I & II-Semester, Principles of Programming Lab 22POP13/23 Page32 | 42


RV Institute of Technology & Management®

FLOWCHART

I & II-Semester, Principles of Programming Lab 22POP13/23 Page33 | 42


RV Institute of Technology & Management®

Program:
#include<stdio.h>

int main()
{
int a[100],n,i,j,temp;

printf("Enter the number of elements\n");


scanf("%d",&n);

printf("Enter the %d elements of array\n",n);


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

printf("The Input array is\n");


for(i=0;i<n;i++)
{
printf("%d\t",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("\nThe sorted array is\n");


for(i=0;i<n;i++)
printf("%d\t",a[i]);

I & II-Semester, Principles of Programming Lab 22POP13/23 Page34 | 42


RV Institute of Technology & Management®

9. Write functions to implement string operations such as compare, concatenate, string length.
Convince the parameter passing techniques.

ALGORITHM

Step 1: Start
Step 2: read string s1 & s2
Step 3: [call function strlength()]
i.e length =strlength
Step 4: Display length 1 and length 2
Step 5: [call function compare string]
if(compare_ string(s1,s2)==0)
print” equal strings”
else
print”unequl strings”
Step 6: call function concatenate
if(concatenate(s1,s2))
Step 7: print”concatenate string”
Step 8: Stop

Algorithm String_length()
Step 1: Start
Step 2: repeate step 2 through while(s1[i]!=’\0’)
i++
return i
end while
Step 3: Stop

Algorithm String_compare()
Step 1: Start
Step 2: repeatr step 2 trough while(s1[i]==s2[i])
if(s[i]==’\0’|| s2[i]==’\0’)
break
i++
end while

Step 3: if(s[i]==’\0’ && s2[i]==’\0’)


return 0
else
return 1
Step 4: Stop

Algorithm String_concatenate()
Step 1: Start
Step 2: Initilize i=0
Step 3: repeate step 3 through while (s1[i]!=’\0’)
i++
end while
Step 4: initialize j=0
Step 5: repeate step 5 through while(s2[i]1=’\0’)
s1[i]=s2[j]

I & II-Semester, Principles of Programming Lab 22POP13/23 Page35 | 42


RV Institute of Technology & Management®

i++ j++
end while
Step 6: s1[i]=’\0’
Step 7: Stop

PROGRAM

#include <stdio.h>

int compare_strings(char [], char []);


void concatenate(char [], char []);
int string_length(char []);

int main()
{
char s1[100], s2[100];
printf("Input a string1\n");
gets(s1);
printf("Input a string2\n");
gets(s2);

int length1 = string_length(s1);


int length2 = string_length(s2);
printf("Length of %s = %d\n", s1, length1);
printf("Length of %s = %d\n", s2, length2);

if (compare_strings(s1, s2) == 0)
printf("Equal strings.\n");
else
printf("Unequal strings.\n");

concatenate(s1, s2);
printf("String obtained on concatenation: \"%s\"\n", s1);

int string_length(char s1[])


{
int i = 0;
while (s1[i] != '\0')
i++;
return i;
}

int compare_strings(char s1[], char s2[])


{
int i = 0;
while (s1[i] == s2[i])
{
if (s1[i] == '\0' || s2[i] == '\0')
break;

I & II-Semester, Principles of Programming Lab 22POP13/23 Page36 | 42


RV Institute of Technology & Management®

i++;
}
if (s1[i] == '\0' && s2[i] == '\0')
return 0;
else
return 1;
}

void concatenate(char s1[], char s2[])


{
int i, j;
i = 0;
while (s1[i] != '\0')
{
i++;
}
j = 0;
while (s2[j] != '\0')
{
s1[i] = s2[j];
j++;
i++;
}
s1[i] = '\0';
}

I & II-Semester, Principles of Programming Lab 22POP13/23 Page37 | 42


RV Institute of Technology & Management®

10. Implement structures to read, write and compute average- marks and the students scoring
above and below the average marks for a class of N students.

ALGORITHM

Step 1: Start
Step 2: create the structure student with fields usn, name and marks and structure variable s[10].
Step 3: Initialize the variables countav=0, countbv=0
Step 4: read the number of students ‘n’
Step 5: read the value of usn name & marks for n number of students using structure variable
s[i] for i=0 to n-1
Step 6: Display the details
Step 7: repeat for i=0 to n-1
Compute the sum of students
Step 8: compute the average
Step 9: repeat for i=0 to n-1
if(s[i].marks >= average)
printf” total number of students above average”
else
printf” total number of students below average”
Step 10: Stop

PROGRAM

#include <stdio.h>
struct student
{
char usn[50];
char name[50];
int marks;
}
int main()
{
struct student s[10];
int i,n,countav=0,countbv=0;
float sum,average;
printf("Enter number of Students\n");
scanf("%d", &n);

printf("Enter information of students:\n");


for(i=0; i<n;i++)
{
printf("Enter USN: ");
scanf("%s",s[i].usn);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%d",&s[i].marks);
printf("\n");
}

I & II-Semester, Principles of Programming Lab 22POP13/23 Page38 | 42


RV Institute of Technology & Management®

printf("Displaying Information:\n\n");
for(i=0; i<n; i++)
{
printf("\nUSN: %s\n",s[i].usn);
printf("Name: %s\n ", s[i].name);
printf("Marks: %d",s[i].marks);
printf("\n");
}
for(i=0;i<n;i++)
{
sum=sum+s[i].marks;
}
average=sum/n;
printf("\nAverage marks: %f",average);
for(i=0;i<n;i++)
{
if(s[i].marks>=average)
countav++;
else
countbv++;
}
printf("\nTotal No of students above average= %d",countav);
printf("\nTotal No of students below average= %d",countbv);
}

I & II-Semester, Principles of Programming Lab 22POP13/23 Page39 | 42


RV Institute of Technology & Management®

11. Develop a program using pointers to compute the sum, mean and standard deviation of all
elements stored in an array of N real numbers.

ALGORITHM

Step 1: Start
Step 2: read n
Step 3: read for i=0 to n-1
Read a[i]
Step 4: prt=a
Step 5: repeat for i=0 to n-1
sum = sum+*prt
prt++
Step 6: mean=sum/n
Step 7: ptr=a
Step 8: repeat for i=0 to n-1
sumstd=sumstd+pow((*ptr-mean),2)
ptr++
Step 9: std=sqrt(stdsum/n)
Step 10: print mean sun and standard deviation
Step 11: Stop

I & II-Semester, Principles of Programming Lab 22POP13/23 Page40 | 42


RV Institute of Technology & Management®

FLOWCHART

I & II-Semester, Principles of Programming Lab 22POP13/23 Page41 | 42


RV Institute of Technology & Management®

Program:

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

int main()
{
float a[10],*ptr,mean,std,sum=0,sumstd=0;
int n,i;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Enter array elements\n");
for(i=0;i<n;i++)
{
scanf("%f",&a[i]);
}
ptr=a;
for(i=0;i<n;i++)
{
sum=sum+*ptr;
ptr++;
}
mean=sum/n;
ptr=a;
for(i=0;i<n;i++)
{
sumstd = sumstd + pow((*ptr-mean),2);
ptr++;
}
std=sqrt(sumstd/n);
printf("Sum=%.3f\t",sum);
printf("Mean=%.3f\t",mean);
printf("Standard Deviation =%.3f\t",std)

I & II-Semester, Principles of Programming Lab 22POP13/23 Page42 | 42


RV Institute of Technology & Management®

12. 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 *ptr1, *ptr2
Step 3: Input source file name fname1 and print fptr1
Step 4: Check if fptr1= NULL? If yes Print file doesn’t found or Error in opening if
no Input new file name fname2 and print fptr1
Step 5: Check if fptr2= NULL? If yes Print file doesn’t found or Error in opening if no
Print fclose(fptr1) fclose(fptr2) getchar()
Step 6: while exit1 print ch=fgetc(fptr1)
Step 7: check if ch==EOF if yes print fclose(fptr1) fclose(fptr2) getchar()
else Print fputc(ch, fptr2)
Step 8: print results
Step 9: Stop

I & II-Semester, Principles of Programming Lab 22POP13/23 Page43 | 42


RV Institute of Technology & Management®

PROGRAM

Assume that the content of the file test.txt is :


test line 1
test line 2
test line 3
test line 4

#include <stdio.h>
#include <stdlib.h>

void main()
{
FILE *fptr1, *fptr2;
char ch, fname1[20], fname2[20];

printf("\n\n Copy a file in another name :\n");


printf(" \n");

I & II-Semester, Principles of Programming Lab 22POP13/23 Page44 | 42


RV Institute of Technology & Management®

printf(" Input the source file name : ");


scanf("%s",fname1);

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
{
fputc(ch, fptr2);
}
}
printf(" The file %s copied successfully in the file %s. \n\n",fname1,fname2);
fclose(fptr1);
fclose(fptr2);
getchar();
}

I & II-Semester, Principles of Programming Lab 22POP13/23 Page45 | 42

You might also like