POP Lab Manual
POP Lab Manual
LAB MANUAL
Principles of Programming using C
BPOPS103
I / II SEMESTER
Name : ___
USN : ___
Batch: Section: _
CONTENTS
SL PROGRAMS
NO
1 Simulation of a Simple Calculator.
Compute the roots of a quadratic equation by accepting the coefficients. Print appropriate
2
messages.
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
3 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,
12 Write a C program to copy a text file to another, read both the input file name and target file name.
Laboratory Session - 1
Write - up on Functional block diagram of Computer, CPU, Buses, Mother Board, Chip
sets, Operating System & types of OS, Basics of Networking & Topology and NIC.
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:
Notations:
Data and Results flow
Control instructions to other units from control unit - - - - - - - - - - - - - - - - - -
Instructions from memory unit to control unit
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): 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): is the circuitry that controls the flow of information through the
processor and coordinates the activities of the other units within the processor.
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:
a. Main Memory / Primary Memory units
i. Random Access Memory (RAM)
ii. Read Only Memory (ROM)
e) Bus: A bus is a collection of wires that carries data / Instructions. 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.
Types of Buses:
1. System Buses: The system buses are used to transfer the data and instructions between Main
memory (Random Access Memory) and CPU. These are classified into following three types.
It is used to transfer the data It is used to transfer the It is used to transfer the
between Processor, Memory addresses of data and control signals between CPU,
and I / O devices. instructions stored in Memory and I / O devices.
memory.
Bidirectional in nature Unidirectional in nature Unidirectional or
Bidirectional in nature
Fig 2: Types of Buses
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.
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 a 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 include:
CPU Management
Memory Management,
File Management,
Device Management,
Process / Task / Job Management
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.
Types of Operating Systems: The operating systems are classified into 7 types based on their
capability and usage.
Fig 3: Types of OS
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.
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 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.
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.
Basics of Networking & Topology and Network Interface Card (NIC): Introduction to
Computer Network:
A computer network is a collection of computers and devices interconnected to facilitate sharing of
resources among interconnected devices. Advantages of Computer Networks include File Sharing,
Resource Sharing, Increased Storage Capacity, Load Sharing and Facilitate communications.
Computers in a network can be connected by using telephone lines, cables, satellite links, etc.,
Wireless network will use radio signals to exchange the information.
1. Bus Topology:
In this network structure, a single cable runs in a building or campus. All the nodes (terminals / computers)
are connected to this single cable. It is suitable for Local Area Network.
Advantages:
Failure of one node will not affect the whole network.
Well suited for quick setup
Easy to install and expand
High rate of data transmission as compare to star and ring topology
Disadvantages:
A cable break can disable the entire network
Trouble shouting is very difficult
Only a single message can travel at a time
2. Ring Topology:
In this network structure, all the computers are connected to each other in the form of a ring. i.e.
first node is connected to second, second to third and so on. Finally last node is connected to first
one.
Advantages:
All the nodes have equal chance to transfer the data
These are easily extensible
It can span longer distance than other type of networks
Disadvantages:
Difficult to install Expensive
Difficult to troubleshoot
Adding or removing computer can disturb the entire network
3. Star Topology:
In this network structure, all the computers are connected with a centralized system called server.
The central computer is also called a hub. To transmit Information from one node to another
node, it should be transmitted through a central hub. The central hub manages and controls all
the functions of network.
Advantages
Easy to install and expand.
Addition or deletion of a node is easier.
Failure of one node will not affect the entire network.
Well suited for quick setup
Easier to debug network problems through a hub
Disadvantages:
Failure of a central system i.e. hub will affect the whole network Cost of hub is expensive.
4. Mesh Topology:
In this network structure, all the computers and network devices are interconnected with one another
like a mesh. Every node has a connection to every other node in the network. This topology is not
commonly used for most computer networks because of its installation difficulty and expensive.
Advantages:
Failure of a single node will not affect the entire network
Data transfer rate is very fast because all the nodes are connected to each other.
Disadvantages:
Installation and re configuration is very difficult Costlier
5. Hybrid Topology:
Each of the topologies has their own advantages and disadvantages. So in the real world, a pure start or
pure ring or bus is rarely used. Rather a combination of two or more topologies is used. Hence, hybrid
network topology uses a combination of any two or more topologies in such a way that the resulting
network does not exhibit one of the standard topologies (e.g., bus, star, ring, etc.). Two very commonly
used hybrid network topologies include the star ring network and star bus network.
Write - up on RAM, SDRAM, FLASH memory, Hard disks, Optical media, CD - ROM / R /
RW, DVDs, Flash drives, Keyboard, Mouse, Printers and Plotters. Introduction to flowchart,
algorithm and pseudo code.
FLASH memory:
Flash memory is a type of Electrically Erasable Programmable Read - Only Memory
(EEPROM). The name comes from how the memory is designed - - a section of
memory cells can be erased in a single action or in a "flash.". Flash memory cards used for
digital cameras, cellular phones, networking hardware, and PC cards.
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.
The read / write heads are attached to single access mechanism so that they cannot move
independently. All read / write heads are moved together to position that heads on the required
track. The hard disks available today ranges from 200 GB to 2TB and so on. The present day hard
disk ranges from 3600 rpm to more than 10000 rpm and so on.
Advantages: High storage capacity, high data accessing rate and permanent storage medium.
Disadvantages: It is not portable.
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.
Advantages
Data stored on flash drives is impervious to scratches and dust Mechanically
very robust
Easily portable
Have higher data capacity than any other removable media.
Compared to hard drives, flash drives use little power
Flash drives are small and light - weight devices
Flash drives can be used without installing device drivers.
Disadvantages
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 otherwise 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.
Types of Printers:
1. Impact Printers: Impact printers are those printers in which a physical
contact is established between the print head, ribbon (cartridge) and paper.
E.g. Dot Matrix Printers
2. Non - Impact Printers: No physical contact is established between the print head,
ribbon (cartridge) and paper. E.g. Inkjet Printers and Laser Printer
Comparison between Dot matrix, Inkjet and Laser printers
It uses metal pins in Its print head does not have The laser printer uses a
its head to create text metal pins; instead it has beam of laser for printing.
and graphics in the several tiny nozzles that
form of dots. spray ink onto the paper.
Each nozzle is thinner than
hair.
The process of The ink cartridges are The printer uses a
printing involves attached to the printer head cylindrical drum, a toner
striking a pin against that moves horizontally from and the laser beam.
a ribbon to produce left to right.
its output.
Printing speed is Printing speed is slower than Printing speed is higher
slower than laser laser dot matrix. than both.
printer,
Character by Line by line printing It is a page printer
character printing
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.
Problem Solving Techniques:
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
ALGORITHM: AREA_of_RECTANGLE
Objective: 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
Step 1: [Initialize] Start
Step 2: [Input the sides of Rectangle]
Read length, breadth
Step 3: [Compute the area of rectangle]
Area = length * breadth
Step 4: [Display the Area]
Print Area
Step 5: [Finished] Stop
Predefined
Indicates Subroutines
Process
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 analyze the problem in a more effective manner
Flowchart can be used to debug programs that have error(s). 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.
Begin
Input length, breadth
Area = length * breadth
Print Area
End.
Laboratory Experiments
Exercise Programs:
a) Develop a Program to read length and breadth of a rectangle and find out area and
perimeter.
Program:
Algorithm:
Flowchart:
#include <stdio.h>
int main()
{
int area, peri,l,b;
printf("Enter length and breadth of a rectangle :");
scanf("%d %d ”,&l, &b);
area = l * b; peri
= 2 * (l + b);
printf("Area = %d \n", area);
printf(“Perimeter = %d ”, peri);
return 0;
}
Output 1:
Enter length and breadth of a rectangle:10 50
Area = 500 Perimeter = 120
Output 2:
Enter length and breadth of a rectangle:15 8
Area = 120 Perimeter = 46
b) Develop a Program to read principle amount, rate of interest, time. Find out
Simple Interest.
Algorithm:
Step 1. [Initialize] Start
Step 2. [input Principle, rate of interest, time]
Read p, r, t
Step 3. [calculate Simple Interest]
si = p * t * r / 100
Step 4. [Display Simple Interest]
Print “SI = “,si
Step 5. [finished] Stop.
Flowchart:
Program:
#include <stdio.h>
int main()
{
float amount,rate,time,si;
printf("Enter principal (Amount) :");
scanf("%f",&amount);
printf("Enter rate :");
scanf("%f",&rate);
printf("Enter time (in years) :");
scanf("%f",&time);
si = (amount * rate * time) / 100;
printf("\nSimple Interest is = %f", si);
return 0;
}
Output 1:
Output 2:
c) Develop a Program to read 3 sides of a triangle and find out area of a triangle.
Algorithm:
Flowchart:
Program:
#include <stdio.h>
#include <math.h>
int main()
{
float s, a, b, c, area;
printf("Enter the values of a, b and c \n");
scanf("%f %f %f", &a, &b, &c);
/ * compute s * /
s = (a + b + c) / 2;
area = sqrt(s * (s - a) * (s - b) * (s - c));
printf("Area of a triangle = %f \n", area);
return 0;
}
Output 1:
Enter the values of a, b and c :
5 5 6
Area of a triangle = 12.00000
Output 2:
Enter the values of a, b and c :
6 8 10
Area of a triangle = 24.00000
d) Develop a Program to read principle amount, rate of interest, time. Find out Compound
Interest.
Algorithm:
Flowchart:
Program:
#include <stdio.h>
int main()
{
float amount,rate,time,ci;
printf("Enter principal (Amount) :");
scanf("%f",&amount);
printf("Enter rate :");
scanf("%f",&rate);
printf("Enter time (in years) :");
scanf("%f",&time);
ci = amount * (pow((1 + rate / 100),time)) - amount;
printf("\nCompound Interest is = %f", ci);
return 0;
}
Output 1:
Enter principal (Amount) :5400
Enter rate :8
Enter time (in years) :3
Compound Interest is = 1402.444800
Output 2:
Enter principal (Amount) :7000
Enter rate :7.5
Enter time (in years) :4
Compound Interest is = 2348.283984
Algorithm:
Program:
#include <stdio.h>
int main()
{
int num,r ;
printf("Enter the number :");
scanf("%d ”,&num);
r = num % 7;
if (r = = 0)
printf(“The number is divisible by 7”);
else
printf(“The number is not divisible by 7”);
}
Output 1:
Enter the number: 35
The number is divisible by 7
Output 2:
Enter the number: 20
The number is not divisible by 7
f) Develop a Program to read number of units consumed by a customer. Find out electricity bill
amount paid base on following condition,
If units > = 100 then per unit 90 paisa otherwise 80 paisa charges.
Algorithm:
Flow Chart:
Program:
#include <stdio.h>
int main()
{
int units;
float amt;
printf("Enter the number of units consumed:");
scanf("%d ”,&units);
if (units> = 100)
amt = units * 0.9;
else
amt = units * 0.8;
printf("Electricity Bill amount = %f”, amt);
return 0;
}
Output 1:
Enter the number of units consumed: 350
Electricity Bill amount = 315.000000
Output 2:
Enter the number of units consumed: 80
Electricity Bill amount = 64.000000
g) Develop a Program to read number ‘n’ and find out factorial of n. Algorithm:
Program:
#include <stdio.h>
int main()
{
int n, fact;
printf("Enter the value for n :");
scanf("%d ”,&n);
fact = 1;
for ( i = 1;i< = n; i + + )
fact = fact * i;
printf("The factorial of %d is = %d ”, n, fact);
return 0;
}
Output 1:
Enter the value of n :6
The factorial of 6 is = 720
Output 2:
Enter the value of n :8
The factorial of 8 is = 40320
h) Develop a program to find the reverse of a positive integer and check for palindrome
or not. Display appropriate messages.
Objective: To understand the while loop construct and find if a given number is palindrome
Algorithm:
Flow chart:
Program:
#include<stdio.h>
int main()
{
int num,temp,rev,rem;
printf("enter the number\n");
scanf("%d ",&num);
rev = 0;
temp = num;
while(num ! = 0)
{
rem = num % 10;
num = num / 10;
rev = ((rev * 10) + rem);
}
if(temp = = rev)
{
printf("%d is a palindrome \ n", temp);
}
else
{
printf("%d is not a palindrome \ n", temp);
}
}
Sample Output 1:
Enter a number: 5642
5642 is not Palindrome
Sample Output 2:
Enter a number: 1221
1221 is Palindrome
i). Develop a program to find the reverse of a positive integer and check for palindrome or
not. Display appropriate messages.
Objective: To understand the while loop construct and find if a given number is palindrome
Algorithm:
Flow chart:
Program:
#include<stdio.h>
int main()
{
int num,temp,rev,rem;
printf("enter the number\n");
scanf("%d ",&num);
rev = 0;
temp = num;
while(num ! = 0)
{
rem = num % 10;
num = num / 10;
rev = ((rev * 10) + rem);
}
if(temp = = rev)
{
printf("%d is a palindrome \ n", temp);
}
else
{
printf("%d is not a palindrome \ n", temp);
}
}
Sample Output 1:
Enter a number: 5642
5642 is not Palindrome
Sample Output 2:
Enter a number: 1221
1221 is Palindrome
j).Implement using functions to check whether the given number is prime and display
appropriate messages. (No built - in math function)
Algorithm:
Step 1. [Initialize] Start
Step 2. [Input an integer number] Read num
Step 3. res = isprime(num)
Step 4. [Output]
If (res = 1)
Print(“The entered number is a prime”)
Else
Print(“The entered number is not prime”)
Step 5. [Stop]
End
Flow Chart:
Program:
#include<stdio.h>
int is_prime(int x);
int main()
{
int n, flag = 0;
printf("Enter any positive Integer :");
scanf("%d ",&n);
flag = is_prime(n);
if(flag = = 1)
printf("The given number %d is not prime\n",n);
else
printf("The given number %d is a prime\n",n);
}
int is_prime(int x)
{
int i;
for(i = 2; i <= (x/2); i++ )
{
if((x % i) = = 0)
{
return 1;
}
}
return 0;
}
Sample Output 1:
Enter any positive Integer : 7
The given number 7 is prime
Sample Output 2:
Enter any positive Integer : 100 The
given number 100 is not prime
k). Develop a program to find the square root of a given number N and execute for all possible
inputs with appropriate messages. Note: Don’t use library function sqrt(n).
Objective: To implement square root of a number without using built in function and find
out the square root for all the possible numbers.
Algorithm:
Flow Chart:
Program:
#include<stdio.h>
int main()
{
float num,s;
int i;
printf("Enter a number to which square root to be found :");
scanf("%f",&num);
if(num > 0)
{
s = num / 2;
for(i = 0; i<num; i ++ )
s = (s + (num / s)) / 2;
printf("square root of a real number %.3f is %.3f", num, s);
}
else
printf("Sorry Invalid Number \n");
}
Sample Output 1:
Sample Output 2:
Sample Output 3:
Algorithm:
Step 1. [Initialize] Start
Step 2. [input the values of two operands] read num1, num2
Step 3. [Get the operator from the keyboard ] read ch
Step 4. [check the operator read]
Switch (ch)
Case ‘ + ’ then res = num1 + num2
Case ‘ - ’ then res = num1 - num2
Case ‘ * ’ then res = num1 * num2
Case ‘ / ’ then res = num1 / num2
Case ‘%’ then res = num1 % num2
Otherwise Print “Invalid Entry” : Stop
Step 5: [Display the result] Print “result = ”, res
Step 6: [Finished] Stop
Flow Chart:
Program:
#include <stdio.h>
int main()
{
int num1, num2;
float result;
char ch; / / to store operator choice
printf("Enter first number: ");
scanf("%d ",&num1);
printf("Enter second number: ");
scanf("% + d",&num2);
printf("Choose operation to perform ( + , - , * , / ,%): ");
ch = getch();
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");
}
printf("Result: %d %c %d = %f\n",num1,ch,num2,result);
}
Output Sample 1:
Enter first number: 10
Enter second number: 20
Choose operation to perform ( + , - , * , / ,%): +
Result: 10 + 20 = 30.000000
Output Sample 2:
Enter first number: 10
Enter second number: 3
/
Choose operation to perform ( + , - , * , / ,%):
Result: 10 / 3 = 3.333333
Output Sample 3 :
Enter first number: 10
Enter second number: 3
>
Choose operation to perform ( + , - , * , / ,%):
Invalid operation.
2. Design and develop a flowchart or an algorithm that takes three coefficients (a, b, and c) of a
Quadratic equation (ax2 + bx + c = 0) as input and compute all possible roots. Implement a C
program for the developed flowchart / algorithm and execute the same to output the possible
roots for a given set of coefficients with appropriate messages.
Objective: To understand the decision making constructs and find the roots of a quadratic equation
Algorithm:
Step 1. [Initialize] Start
Step 2. [input the values of a,b,c] read a,b,c
Step 3. [check if a or b are zero]
if(a = 0 or b = 0) output “invalid input” goto step 8
Step 4. [calculate the discriminant] d = b * b - 4ac
Step 5. [find two distinct roots]
if(d>0)
r1 = ( - b + sqrt(d)) / 2a
r2 = ( - b - sqrt(d)) / 2a
Output r1 and r2 with suitable message goto step 7
Step 6. [find two equal roots]
if(d = 0) r1 = r2 = - b / 2a
Output r1 and r2 with suitable message
goto step 7
Step 7. [find two complex roots] p1 = - b / 2a p2 = sqrt( - d) / 2a Output
r1 and r2 with suitable message
Step 8. [Finished] Stop
Flow chart:
Program:
Sample Output 1:
Enter the three co - efficient:
1 4 4
The roots are real and equal
root1 = - 2.0000 root2 =2.0000
Sample Output 2:
Enter the three co - efficient:
1 5 6
The roots are real and distinct
root1 = - 2.0000
root2 = - 3.0000
Sample Output 3:
Enter the three co - efficient:
2 3 4
The roots are imaginary
root1 = - 0.75 + i 1.19
root2 = - 0.75 - i 1.19
Sample Output 4:
Enter the three co - efficient:
105
invalid input!!!
3 An electricity board charges the following rates for the use of electricity: for the first 200
units 80 paisa per unit: for the next 100 units 90 paisa 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.
Objective: To understand the if - else ladder and find the electricity bill base on the number of
units consumed.
Algorithm:
Program:
#include<stdio.h>
int main()
{
char name[20];
int noofunits;
float amt, sur;
Sample Output 1:
Enter the consumer name : JOHN
Enter number of units consume :200
The consumer name = JOHN
The number of units consumed =
200 Electricity Bill Amount =
260.00 service charge = 0.00
The Total Electricity Bill Amount : 260.00
Sample Output 2 :
Enter the consumer name: RAMESH
Enter number of units consume :460
The consumer name = RAMESH The
number of units consumed = 460
Electricity Bill Amount =
510.00 service charge = 61.50
The Total Electricity Bill Amount: 571.50
Sample Output 3 :
Enter the consumer name: VINOD
Enter number of units consume :0
The consumer name = VINOD
The number of units consumed = 0
Electricity Bill Amount =
100.00 service charge = 0.00
The Total Electricity Bill Amount :100.00
4. Write a C Program to display the following by reading the number of rows as input,
Algorithm:
Step1: Start
Step 2: Read number of rows
Step 3: Repeat the process to n
Display number in ascending order upto middle
Display number in reverse order after middle
Step: Stop
Flow Chart:
Start
Read n
i<n
Print
number
Stop
Program:
void main()
{
int i,j,n;
printf("Input number of rows : ");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
/* print blank spaces */
for(j=1;j<=n-i;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");
}
}
1
121
12321
1234321
123454321
Algorithm:
Step 1: [Initialize] Start
Step 2: [input value for ‘n’] Read n
Step 3: [Enter the n elements of single dimensional array in ascending order ]
for i=0 to n-1 read Ai
Step 4:[input a element to be search] read key
Step 5: [Initialize low, high and middle]
assume low = 0, high = n – 1 and mid= (low+high)/2 Step
6: [Implement binary search with n elements of an array]
while (low <= high)
begin while
if (Amid = key) goto step 7
else if (Amid < key) low = mid+ 1
else high = mid – 1
mid=(low+high)/2
end while
#include <stdio.h>
int main()
{
int i, low, high, mid, n, key, a [100],flag = 0;
printf("Enter number of elements\n");
scanf("%d ",&n);
printf("Enter %d integers in ascending order \n", n);
for (i = 0; i < n; i + + )
scanf("%d ",&a[i]);
printf("Enter the key value to find\n");
scanf("%d ", &key);
low = 0;
high = n - 1;
mid = (low + high) / 2;
while (low < = high)
{
mid = (low + high) / 2;
if (a[mid] = = key)
{
flag =
1;
break;
}
else if (a[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
if (flag = = 0)
printf("Key Not found”);
else
printf("%d found at location %d .\n", key, mid+1);
Sample Output 1:
Enter number of elements : 5 Enter
5 integers in ascending order 4
7
8
9
45
Enter value to find
9
9 found at location 4.
Sample Output 2 :
Enter number of elements :7
Enter 7 integers in ascending order
9
23
41
90
132
290
301
Enter value to find
10
Key Not found!
Flow Chart:
Program:
#include<stdio.h>
#include<math.h>
int main()
{
int A[50][50],B[50][50],C[50][50],m,n,p,q,i,j,k;
printf("enter the size of the first matrix\n");
scanf("%d %d ",&m,&n);
printf("enter the size of the second matrix\n");
scanf("%d %d ",&p,&q);
if (n = = p)
{
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("matrix A is \n");
for(i = 0;i<m;i + + )
{
for(j = 0;j<n;j + + )
{
printf("%d \t",A[i][j]);
}
printf("\n");
}
printf("enter the elements of second matrix\n");
for(i = 0;i<p;i + + )
{
for(j = 0;j<q;j + + )
{
scanf("%d ",&B[i][j]);
}
}
printf("matrix B is\n");
for(i = 0;i<p;i + + )
{
for(j = 0;j<q;j + + )
{
printf("%d \",B[i][j]);
}
printf("\n");
}
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("the product of 2 matrices is \n");
for(i = 0;i<m;i + + )
{
for(j = 0;j<q;j + + )
{
printf("%d \t",C[i][j]);
}
printf("\n");
}
} / / if ends here
else
{
printf("multiplication is not possible\n");
}
}\\End of Main
Sample Output 1:
Enter the size of the first matrix A : 2 2
Enter the size of the second matrix B : 2 2
Enter the elements of first matrix
1 2
3 4
Enter the elements of second matrix
2 3
4 5
Matrix A is
1 2
3 4
Matrix B is
2 3
4 5
the product of 2 matrices is
10 13
22 29
Output 2:
Enter the order of the matrix A : 2 3
Enter the order of the matrix B : 2 3
multiplication is not possible
7).Develop a Program to compute Sin(x) using Taylor series approximation. Compare your
result with the built- in Library function. Print both the results with appropriate messages.
Objective: To understand the implementation of sin(x) series using Taylor series
Algorithm:
Flow Chart:
Program:
#include <stdio.h>
#include<math.h>
#define PI 3.142
int main()
{
int degree,i;
float x, nume, denom, sum = 0, term;
printf("enter the value of degree\n");
scanf ("%d ", °ree);
x = (degree * PI ) / 180;
nume = x;
denom = 1;
i = 2;
do
{
term = nume / denom;
nume = - nume * x * x;
denom = denom * i * (i + 1);
sum = sum + term;
i = i + 2;
}
while(fabs(term)>0.00001);
printf("sin(%d ) = %f without using built in function \n",degree, sum); printf("sin(%d
) = %f using built in function \n",degree, sin(x));
}
Sample Output 1:
Enter the value of degree: 90
sin(90) = 1.000000 without using built in function
sin(90) = 1.000000 using built in function
Sample Output 2:
Enter the value of degree 45
sin(45) = 0.707179 without using built in function
sin(45) = 0.707179 using built in function
8).Develop a program to sort the given set of N numbers using Bubble sort.
Objective: To understand the technique of bubble sort and sort the integer in an array of n elements.
Algorithm:
Flow Chart:
Program:
#include<stdio.h>
int main()
{
int a[50], n, i, j, temp = 0;
printf("Enter the size an array:\n");
scanf("%d ", &n);
printf("Enter the %d elements of an array:\n", n);
for (i = 0; i < n; i ++ )
{
scanf("%d ", &a[i]);
}
printf("\n \n \t The given array before sorting is: \n");
for (i = 0; i < n; i ++ )
{
printf("\n\t\t %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\n\n\t\tThe sorted array is:\n");
for (i = 0; i < n; i ++ )
{
printf("\n\t\t %d ", a[i]);
}
}
Sample Output:
Algorithm:
Flow Chart:
Program:
#include<stdio.h>
#include<string.h>
void comp_str(char str1[100], char str2[100]);
void concat_str(char str1[100], char str2[100]);
void length_str(char str[100]);
int main()
{
int ch;
char s1[100], s2[100];
printf("Enter a first string :");
scanf("%s",s1);
printf("Enter a second string :");
scanf("%s",s2);
printf("The length of first string :");
length_str (s1);
printf("\nThe length of second string :");
length_str (s2);
printf("\nResults of two strings compare :");
comp_str(s1,s2);
printf("Results After concatenation of two strings :");
concat_str(s1,s2);
str1[i]='\0';
printf("\n Concatenated String is ");
puts(str1);
}
Sample Output 1:
Sample Output 2:
Objective: To maintain a record of “n” student details with four fields, calculate average
marks and find out the students above or below average.
Algorithm :
Step 1. [Initialize] Start
Step 2. [Input the number of students]
Read n
Step 3. [Input roll number, name, marks of 3 subjects of n students]
for i - 0 to n - 1 in step of 1
Read roll[i], name[i], m1[i],m2[i],m3[i]
End for
Step 4. [Compute average and display above score or below score for n students]
For i = 0 to n - 1 in steps of 1
avg[i] = ( m1[i] + m2[i] + m3[i] ) / 3
if ( avg[i] > = 50) print “ i th student score above average”
Else
print “ i th student score below average”
end for
Step 5. [Finished] Stop
Flow Chart:
Program:
#include<stdio.h>
#define SIZE 50
struct student
{
char name[30];
int rollno;
int sub[3];
float avg;
};
int main()
{
int i, j, count, total, n, a[SIZE];
struct student st[SIZE];
printf("Enter the number of students: ");
scanf("%d ", &n);
/* for loop to calculate total marks and average obtained by each student * /
for (i = 0; i < n; i + + )
{
total = 0;
for (j = 0; j < 3; j + + )
{
total = total + st[i].sub[j];
}
st[i].avg = total / 3.0;
printf("\n Total marks obtained by %s is : %d ", st[i].name, total);
printf("\n Average marks obtained is : %f", st[i].avg);
if (st[i].avg > = 50)
printf("\n %s scored above the average marks\n",st[i].name);
else
printf("\n %s scored below the average marks\n",st[i].name);
}
}
Sample Output :
Objective: To implement the sum, mean and standard deviation for n real numbers
Algorithm:
Step 1: [Initialize] Start Step
2: [Input the elements]
Read n, a[i]
Step 3: [Initialize]
sum=0, sumstd=0
Step 4: [Compute sum, mean, standard
deviation] Ptr=a
For i = 0 thru n in steps of 1
sum=sum+ * ptr , Ptr++ , mean=sum/n , Ptr=a
For i= 0 thru n in steps of 1
sumstd=sumstd+pow(( * ptr-mean),2)
Ptr++
Step 5 : std=sqrt(sumstd/n)
Step 6: [Output sum, mean and standard deviation]
Print sum, mean, std
Step 7: [ Finished ] Stop
Flow Chart:
Program:
#include<stdio.h>
#include<math.h>
int main()
{
float a[50], *ptr, mean, std, sum = 0, sumstd = 0;
int n,i;
printf ("enter the number of elements in an array \n");
scanf("%d", &n);
printf("enter the 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 = %f\n", sum);
printf("mean = %f\n", mean);
printf("standard deviation = %f\n", std);
}
Output:
Enter the number of elements in an array: 5
Enter the array elements: 1 2 3 4 5
sum=15.000000
Mean=3.000000
Standard deviation=1.414214
12). Implement Recursive functions for Binary to Decimal Conversion.
Objective: To implement the recursive function and perform binary to decimal conversion.
Algorithm:
Step 1: [Initialize] Start
Step 2: [Input the binary number]
Read dig
Step 3: [call the binary to decimal recursive function by sending the binary digit]
res = conBintoDec(dig)
Step 4: [display the result which gives decimal equivalent]
print res
Step 5: [ Finished] Stop
Flow Chart:
Program:
#include<stdio.h>
int iter = 0, count = 1;
int conBintoDec(long int num)
{
iter ++ ;
if(iter! = 1)
count *= 2;
if(!(num / 10))
return num * count;
return ( (num%10) * count + conBintoDec(num / 10));
}
int main()
{
long int dig;
int res;
printf("Enter a binary number = ");
scanf("%ld",&dig);
res = conBintoDec(dig);
printf("The decimal equivalent of a binary num %ld = %d ",dig, res);
}
Sample Output 1:
Sample Output 2:
1. What is C language?
Ans:
C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972.
The C programming language is a standardized programming language developed in the early
1970s by Ken Thompson and Dennis Ritchie for use on the UNIX operating system. It has since
spread to many other operating systems, and is one of the most widely used programming
languages.
2. What is an algorithm?
Ans: An algorithm is a step - by - step method of performing any task.
14) What is a Data Type and List the different Data types?
Ans: C data types are defined as the data storage format that a variable can store a data to perform a
specific operation.
List of Data Types:
1) Basic Data Types: Int, Float, Char, Double, long int
2) Enumeration Data Type: enum
3) Derived Data Type: Pointer, array, structure, union
4) Void Data Type: void
21) How many Keywords are there in C and List out the
Keywords? Ans : There are 33 reserved keywords are there in C.
They are:
auto Else long switch
break Enum register typedef
case Extern return union
char Float short unsigned
const For signed void
continue Goto sizeof volatile
default If static while
do Int struct _Packed
double
40) What are the Format Specifiers or Type Specifiers or Conversion Specifiers?
Ans: %d (Integer), %f (Float), %c (Character), %l (Long Integer), %s (Strings), %u (Address
with decimal value), %p (Address with Hexa Decimal Value in Small Letters),
%x ((Address with Hexa Decimal Value in Capital Letters)
1) If Statement
2) If else statement
3) Nested - if else statement
4) Switch Statement
56) What is the difference between for loop and while loop?
Ans: For Loop is used to execute a set of statements in fixed number of times. We use While loop
when the number of iterations to be performed is not known in advance we use while loop.
58) Define goto and labeled Statement, Write syntax for goto and labeled statements? Ans:
The goto statement transfers control to a label. The given label must reside in the same
function and can appear before only one statement in the same function.
Syntax: goto
<label>;
<label>: <Statement
Initial
Storage Storage
Sl. No. default Scope
Specifier place
value
CPU Garbage
1. auto local
Memory value
68. Ans: C Array is a collection of variables belongings to the same data type. OR
An Array is a collection of Homogeneous or similar data type elements having unique
values, and stored ata different locations. You can store group of data of same data type
in an array.
69) Types of an Array?
Ans: There are 2 types of C arrays. They are,
1) One dimensional array
2) Multi-dimensional array
i) Two dimensional array
ii) Three dimensional array, four dimensional array etc…
71) What is the syntax for One Dimensional Array, explain declaration,
Initialization, accessing the elements?
Ans:
Syntax : data - type arr_name[array_size];
Array
Array Initialization Array Access
Declaration
Syntax:
data_type arr_name [arr_size] arr_name [index];
data_type
= {value1, value2, value 3…}
arr_name [size]
age[0]; / * 0 is accessed * /
int age [5]; int age[5] = {0, 1, 2, 3, 4, 5}; age[1]; / * 1 is accessed * /
age[2]; / * 2 is accessed * /
char str[10] = {‘H’,‘a’,‘i’};
(or) str[0]; /* H is accessed */
Char str[10]; char str[0] =‘H’; str[1]; /* a is accessed */
char str[1] = ‘a’; str[2]; /* i is accessed */
char str[2] = ‘i’;
72) What is the syntax for One Dimensional Array, explain declaration, Initialization,
accessing the elements?
Ans: Two dimensional array is nothing but array of array.
syntax : data_type array_name[num_of_rows][num_of_column]
84) What are the advantages of using array of pointers to string instead of an array of strings?
Ans: Efficient use of memory.
Easier to exchange the strings by moving their pointers while sorting.
91) What are Built - in - Functions / Pre Defined Functions / Library Functions?
Ans: The functions that are predefined and supplied along with the compiler are known as built in
functions. They are also known as library functions.
93) Define Function Declaration, Function Call and Function Definition with Syntaxes:
Ans:
Function declaration or prototype - This informs compiler about the function name, function
parameters and return value’s data type.
Function call – This calls the actual function
Function definition – This contains all the statements to be executed.
C function
S.no aspects syntax
function return_type function_name ( arguments list )
1 definition { Body of function; }
2 function call function_name ( arguments list );
function
3 declaration return_type function_name ( argument list );
94) Define Call by Value?
Ans: In call by value method, the value of the variable is passed to the function as parameter.
The value of the actual parameter cannot be modified by formal parameter. Different Memory
is allocated for both actual and formal parameters.
· Actual parameter – This is the argument which is used in function call.
· Formal parameter – This is the argument which is used in function definition
1) What is an algorithm?
2) What is high level language?
3) What is compiler?
4) What are tokens?
5) What are identifiers?
6) What are keywords? How many keywords are ther e in C programming language?
7) What is a variable?
8) What are the rules to be followed while declaring a variable?
9) What is a constant?
10) What is a data type? What are the different data types?
11) What are escape sequence characters?
12) List the size and range of basic data types.
13) What is the difference between a character and string?
14) What is implicit type conversion and explicit type conversion (type casting)?
15) What is precedence of an operator means?
16) What is the difference between printf() and puts() functions.
17) What is function? What are the advantages of functions?
18) What are the different types of functions?
19) What is a library function?
20) What is calling function and called function?
21) What is the meaning of actual parameter and formal parameter?
22) What is the purpose of switch statement? Explain with syntax.
23) What is loop? List the differences between pre - test and post - test loop.
24) What is the meaning of event controlled loop and counter controlled loop?
25) What are the advantages of loops?
26) What is control statement? What are the various types of control statements
available in C language?
27) Explain for loop with syntax.
28) What is the difference between while and do - while loop?
29) What are unconditional control statements?
30) What is the use of break statement?
31) What is an array? What is the difference between an ordinary variable and an array
variable?
32) What are the differences between recursion and iteration?
33) What is a pointer?
34) What is a NULL pointer?
35) What is a Structure? What are the differences between structures and arrays?
36) What is memory leak? Why it should be avoided.
37) Which header file should be included to use functions like malloc() and calloc()?
38) List string.h Library functions in C.
39) What is the purpose of main() function?
40) What is the difference between static and dynamic memory allocation in C?