[go: up one dir, main page]

0% found this document useful (0 votes)
93 views85 pages

POP Lab Manual

Uploaded by

jovek32807
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)
93 views85 pages

POP Lab Manual

Uploaded by

jovek32807
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/ 85

ew

DON BOSCO INSTITUTE OF TECHNOLOGY


Kumbalgodu, Mysuru Road, Bengaluru – 560074
www.dbit.co.in Ph::+91-80-28437028/29/30 Fax:+91-80-28437031
Department of Information Science & Engineering

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,

5 Implement Binary Search on Integers / Names.

Implement Matrix multiplication and validate the rules of multiplication.


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

Sort the given set of N numbers using Bubble sort.


8
Write functions to implement string operations such as compare, concatenate, string
9
length. Convince the parameter passing techniques.
Implement structures to read, write and compute average- marks and the students scoring
10
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.
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.

Functions of Control unit


 Accessing data & instructions from memory unit Interpreting instructions
 controlling input and output units
 Overall supervision of a Computer system

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)

b. Secondary Memory / Auxiliary Memory

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.

Data Bus Address Bus Control Bus

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.

PCI Bus ISA Bus USB Bus


PCI stands for ISA stands for USB stands for
Peripheral Industry Standard Universal Serial Bus
Component Architecture
Interconnect

The motherboard will This is simple and It helps to connect


be having 3 or 4 PCI slowest bus used in various I / O devices like
connectors, so that we IBM PCs keyboard, mouse, pen
can insert various drives, printer, etc.
chips.
Fastest and presently Oldest, simplest and Newest and widely
more powerful bus slowest bus used 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 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.

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

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.

Basic components of a computer network: The basic components of a network are as


follows.

1. Protocol: Set of rules used during the data transmission.


2. Transmission Medium: The media used to connect computer to each other like
telephone lines, twisted pair wire, co - axial cable, fiber optics, satellite signals and radio
signals, etc.
3. Processors: Modem, Multiplexers, bridges, routers, gateways, hub etc. are the
processors used in the network for the flow of data.
4. Channels: Analog/Digital, Synchronous/Asynchronous, Switched/Non
switched, Simplex / duplex, etc.
5. Topology: Physical network layout used for networking. For example, bus topology,
star topology, ring topology, and mesh topology
6. Software: User interface software like Internet Explorer, Netscape Navigator, FTP (File
Transfer Protocol), Telnet (Telecommunication Network), PPP (Point to Point Protocol),
and SMTP (Simple Mail Transfer Protocol) etc.
Types of Networks: The computer networks are mainly classified into 3 types.

LAN MAN WAN


Local Area Network Metropolitan Area Network Wide Area Network

A group of computers that A network which Covers A network which covers a


are connected in a small large area like a city large area like a state,
area such as building, country or across a
home, office etc i.e. within continent.
a small campus
Distance covered by this Distance covered by this Distance covered by this
network is less than 1 KM network is 5 to 50 KM. network is 100 to 1000 KM
Used within a single Used by private Used all over the world. i.e.
building like home or organization like cable good example is internet
office television in our city.
Computers are connected A network device called It uses fibre optics, cables
through the twisted pair router is used to connect and even satellite signals as
cables and co axial cables. the LANs together a transmission media.

Transmitting data Transmitting data is costlier Transmitting data is more


is cheaper costlier

Transmission data is Transmission data is Transmission data is


generally error free generally error prone generally error free
Network Topologies: Topology refers to the schematic description of the arrangement of a
network. It is the actual geometric layout of computers and other devices connected to the
network.

Types of Network Topologies: These are mainly classified into 4 types.

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.

Network Interface Cards (NICs):


This is the important hardware component, which connects the machine to the computer network. This
will be fixed into one of the free slot on the mother board. It has one port for the connection of a
network cable. These cards typically use an Ethernet connection and are available in 10, 100, and 1000
Base - T configurations.
A 100 Base - T card can transfer data at 100 Mbps. The cards come in ISA and PCI versions and are
made by companies like 3Com and LinkSys.
Laboratory Session - 2

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.

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.

Synchronous Dynamic Random Access Memory (SDRAM):


It is an improvement to standard DRAM because it retrieves data alternately between two sets of
memory. This eliminates the delay caused when one bank of memory addresses is shut down while
another is prepared for reading. It is called "Synchronous" DRAM because the memory is
synchronized with the clock speed that the computer's CPU bus speed is optimized for. The faster
the bus speed, the faster the SDRAM can be. SDRAM speed is measured in Megahertz.

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.

Examples: CD - ROM, DVD etc.

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

Digital Video 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.
Advantages: Storage capacity is more compared to CDs.

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
 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

Dot Matrix Printer Inkjet Printer Laser Printer


Impact Printer Non - impact Printer Non - impact printer

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

Low quality printing High quality printing High quality printing

Less expensive High expensive High expensive

Generates much noise Generates less noise while No noise


while printing Printing
Speed is measured in Speed is measured in CPI Speed is measured in
DPI (Dots Per Inch) (Characters Per Inch) PPM (Pages Per Minute)

Monochrome e Color printer Monochrome and color


(Black & White) printer
Printers

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:

The process of working through details of a problem to reach a solution.


There are three approaches to problem solving:
 Algorithm
 Flowchart
 Pseudo Code

Algorithm: The algorithm is a step - by - step procedure to be followed in solving a problem. It


provides a scheme to solve a particular problem in finite number of unambiguous steps. It helps in
implementing the solution of a problem using any of the programming languages. In order to qualify
as an algorithm, a sequence of instructions must possess the following characteristics:

 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

Key features of an algorithm:


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.
Example: To compute the Area of Rectangle

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

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.

Symbol Name Description

Oval Represents the start / terminal point

Represents the process steps defined in


Rectangle algorithm
Indicate the reading Operation used for
Parallelogram input / output or data or information from /
to any device
Indicates the decisions (questions) and
Diamond consequently the branch points or the paths
to be followed based on the result of the
question

Arrows Shows the flowchart direction and connects


the various flow chart symbols

Small circle Shows the continuation from one point in


the process flow to another

Hexagon Represents Looping structures

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

Limitations of using Flowcharts:

 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 re - drawing 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

Start

Read length & breadth

Area = length * breadth

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.

e.g.: To compute the area of Rectangle

Begin
Input length, breadth
Area = length * breadth
Print Area
End.
Laboratory Experiments

1. Familiarization with computer hardware and programming environment, concept of


naming the program files, storing, compilation, execution and debugging. Taking any
simple C - code.

Exercise Programs:
a) Develop a Program to read length and breadth of a rectangle and find out area and
perimeter.

Program:
Algorithm:

Step 1. [Initialize] Start


Step 2. [input the length and breadth] Read l,b
Step 3. [calculate perimeter] peri= 2(l+b)
Step 4. [calculate area] area = l * b
Step 5. [Display area and perimeter] Print area, peri
Step 6. [finished] Stop.

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:

Enter principal (Amount) :15000 Enter rate :2.8


Enter time (in years) :2
Simple Interest is = 840.000000

Output 2:

Enter principal (Amount) :5400 Enter rate :2


Enter time (in years) :3
Simple Interest is = 324.000000

c) Develop a Program to read 3 sides of a triangle and find out area of a triangle.
Algorithm:

Step 1. [Initialize] Start


Step 2. [input the three sides]
Read a,b,c
Step 3. [calculate perimeter]
s = (a + b + c) / 2
Step 4. [calculate area]
area = sqrt(s(s - a)(s - b)(s - c))
Step 5. [Display area of a triangle]
Print area
Step 6. [finished] Stop.

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:

Step 1. [Initialize] Start


Step 2. [input Principle, rate of interest, time]
Read p, r, t
Step 3. [calculate Compound Interest]
ci = p * pow((1 + r / 100),t) - p
Step 4. [Display Compound Interest ]
Print ci
Step 5. [finished] Stop.

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

e) Develop a Program to read a number. Check whether it is divisible by 7 or not.

Algorithm:

Step 1. [Initialize] Start


Step 2. [input a integer]
Read n
Step 3. [calculate the remainder]
r=n%7
Step 4. [Check whether divisible by 7]
If (r = 0) print “ it is divisible by 7”
Else print “It is not divisible by 7”
Step 5. [finished] Stop.
Flow Chart:

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:

Step 1. [Initialize] Start


Step 2. [input a number of units consumed]
Read units
Step 3. [calculate bill amount base on condition]
If ( units> = 100) amt = units * 0.9 Else
amt = units * 0.8
Step 4. [Display the bill amount]
Print amt
Step 5. [finished] Stop.

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:

Step 1. [Initialize] Start


Step 2. [input a number] Read n
Step 3. [Initialize fact]
Fact = 1
Step 4. [Calculate factorial]
For i = 1 to n step in 1
Fact = Fact * i
Step 5. [Display the factorial of n]
Print Fact
Step 6. [finished] Stop.
Flow Chart :

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:

Step 1. [Initialize] Start


Step 2. [input the number] Read number
Step 3. [make a copy of the number]
temp=number
Step 4.[initialize the value of reverse]
reverse=0
Step 5. [reverse the given number] ,
while (temp! =0)
begin while
remain=temp%10,
temp=temp/10
reverse=reverse * 10+remain

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:

Step 1. [Initialize] Start


Step 2. [input the number] Read number
Step 3. [make a copy of the number]
temp=number
Step 4.[initialize the value of reverse]
reverse=0
Step 5. [reverse the given number] ,
while (temp! =0)
begin while
remain=temp%10,
temp=temp/10
reverse=reverse * 10+remain

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:

Step 1. [Initialize] Start


Step 2. [input the number] read n
Step 3. [check whether given number is real, then compute the square root otherwise
display an appropriate message]
If (n>0)
Begin if
s=n/2
for i = 0 to i<num in step 1 s = (s + (num / s)) / 2
end for print “square root ”, s
end if
else
print “Sorry Invalid Number ”
Step 4. [Finished] stop

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:

Enter a number to which square root to be found : 4


square root of a real number 4.00 is 2.000

Sample Output 2:

Enter a number to which square root to be found : 8.9


square root of a real number 8.9 is 2.893

Sample Output 3:

Enter a number to which square root to be found : - 7 Sorry


Invalid Number
1 Develop a program to solve simple computational problems using arithmetic expressions
and use of each operator leading to simulation of a commercial calculator. (No built - in
math function)

Objective: To understand the switch constructs and Perform arithmetic calculations


based on the operator chosen.

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:

#include<stdio.h> #include<math.h> int main()


{
int a,b,c,d;
float x1,x2;
printf("enter the three co - efficient \n");
scanf("%d %d %d ",&a,&b,&c);
if((a = = 0) || (b = = 0))
{
printf("invalid input!!!");
}
else
{
d = b * b - 4 * a * c;
if(d>0)
{
printf("roots are real and distinct\n");
x1 = - b + sqrt(d) / (2.0 * a);
x2 = - b - sqrt(d) / (2.0 * a);
printf("root1 = %f root2 = %f",x1,x2);
}
else if (d = = 0)
{
printf("root are real and equal\n");
x1 = x2 = - b / (2.0 * a);
printf("root1 = %f root2 = %f",x1,x1);
}
else
{
printf("roots are imaginary\n"); x1 = - b / (2.0 * a); x2
= sqrt(fabs(d)) / (2.0 * a);
printf("root1 = %.2f + %.2fi root2 = %.2f - %.2fi",x1,x2,x1,x2);
}
}

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:

Step 1. [Initialize] Start


Step 2. [input the consumer name] Read name
Step 3. [input the number of units consumes] Read units
Step 4. [Calculate the Electricity bill amount]
If (units = 0) amt = 100
else if(units< = 200) amt = 100 + noofunits * .8
else if((units>200) and (units< = 300))
amt = 100 + 200 * .8 + (units - 200) * .9
else
amt = 100 + 200 * .8 + 100 * .9 + (units - 300) * 1
Step 5. [ Calculate the service charge ]
if(amt>400) sur = 15 / 100.0 * amt
else sur = 0
Step 6. [Output the result]
Print “Consumer name, bill amount and service charges”, name , amt, sur
Step 7. [finished] Stop.
Flow Chart:

Program:

#include<stdio.h>
int main()
{
char name[20];
int noofunits;
float amt, sur;

printf("Enter a Consumer name :");


scanf("%s",name);
printf("Enter number of units consume :");
scanf("%d ",&noofunits);
if(noofunits = = 0)
amt = 100;
else if(noofunits < = 200)
amt = 100 + noofunits * 0.8;
else if((noofunits > 200) && (noofunits < = 300))
amt = 100 + 200 * .8 + (noofunits - 200) * 0.9;
else
amt = 100 + 200 * 0.8 + 100 * 0.9 + (noofunits - 300) * 1;

if(amt > 400)


sur = 15 / 100.0 * amt;
else sur = 0.0;
printf("The consumer name = %s\n",name);
printf("The number of units consumed = %d \n",noofunits);
printf("Electricity Bill Amount = %.2f\n",amt);
printf("service charge = %.2f",sur);
printf(“The Total Electricity Bill Amount : %.2f”, 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");
}
}

Input number of rows : 5

1
121
12321
1234321
123454321

5. Implement Binary Search on Integers / Names..


Objective: To understand one dimensional array and search the element in a given array using
Binary search.

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

Step 7. [Output the result] if (low>high) ) print “element is not found ”


else print “element is found ”
Step 8. [finished] Stop.
Flow Chart :
Program:

#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!

Department of CSE, DBIT, Bengaluru 40 | P a g e


6. Develop a program to introduce 2D Array manipulation and implement Matrix
multiplication and ensure the rules of multiplication are checked.
Algorithm:
Step 1. [Initialize] Start
Step 2. Input: matrices A and B
Step 3. Let C be a new matrix of the appropriate size
For i from 1 to n:
For j from 1 to p:
Let sum = 0
For k from 1 to m:
Set sum ← sum + Aik × Bkj
Set Cij ← sum
Step 4. [Display the C matrix] Print : matric C
Step 5. [Finished] Stop

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:

Step 1: [Initialize] Start


Step 2: [Input the degree value] Read degree
Step 3: [Calculate x]
x = (degree * pi) / 180;
Step 4: [ Initialize numerator and denominator]
Sum = 0, nume = x
denom = 1, i = 2
Step 5: [Loop to find term and sum it up]
Do
term = nume / denom,
nume = - nume * x * x
denom = denom * i * (i + 1),
sum = sum + term, i = i + 2
While (fabs(term)>0:00001)
Step 6: [Display the sum] Print sum, standard function sin(degree)
Step 7: [Finished] Stop

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 ", &degree);
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:

Step 1. [Initialize] Start


Step 2. [input the size of the array] read n
Step 3. [input the elements of the array]
for i = 0 to n - 1 in step 1 read a[i] end for
Step 4. [sort the elements using bubble sort technique]
for i = 0 to n - 1 in array a
for j = 0 to n - i - 1 in
array a begin for
if (a[j] > a[j + 1]) temp = a[j], a[j] = a[j + 1], a[j + 1]
= temp end for
end for
print a[i]
end for
Step 5. [Display the elements of an array after sorting]
for i = 0 to n - 1 in step 1
Step 6. [Finished] stop

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:

Enter the size of an array: 5


Enter the 5 elements of an array: 5 4 3 2
1
The given array before sorting is: 5
4
3
2
1

The sorted array is: 1


2
3
4
5
9.Write functions to implement string operations such as compare, concatenate, string length.
Convince the parameter passing techniques
Objective: To understand the function parameter passing techniques and implement the
string operation using the same technique.

Algorithm:

Step 1. [Initialize] Start


Step 2. Input the two strings] read s1, s2
Step 3. [perform two string compare using a function]
Call the function Str2cmp(s1,s2)
Step 4. [perform two string concatenation]
Call the function Str2cat(s1,s2)
Step 5. Find the length of two string using a function]
Call the function length(s1), length(s2)
Step 6. [Finished] Stop

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

void comp_str(char str1[100], char str2[100])


{
int i=0;
while(str1[i] = = str2[i])
{
if(str1[i] = = ‘\0’ || str2[i] = = ‘\0’)
break;
i++;
}
if (str1[i] = = '\0' && str2[i] = = '\0')
printf("Both strings are equal");
else
printf("Both strings are not equal");
}
void concat_str(char str1[100], char str2[100])
{
int i=0,j=0;
while(str1[i] != '\0')
i++;
while(str2[j] != '\0')
{
str1[i] = str2[j];
i++;
j++;
}

str1[i]='\0';
printf("\n Concatenated String is ");
puts(str1);
}

void length_str(char str1[100])


{
int len=0;
while(str1[len] != '\0')
len++;
printf("length of string %s is %d ",str1, len);
}

Sample Output 1:

Enter a first string : SCI Enter a


second string : ENCE
The length of first string :SCI = 3
The length of second string :ENCE = 4
Results of two strings compare : Both the strings are not equal …. Results
After concatenation of two strings :SCIENCE

Sample Output 2:

Enter a first string : MAT


Enter a second string :
MAT
The length of first string :MAT = 3
The length of second string :MAT
=3
Results of two strings compare : Both the strings are equal ….
Results After concatenation of two strings : MATMAT
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.

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 read the names and roll numbers */


for (i = 0; i < n; i ++ )
{
printf("\nEnter name and roll number for student %d : ", i + 1);
scanf("%s %d", &st[i].name, &st[i].rollno);
printf("\nEnter three subject marks for student %d : ", i + 1); for
(j = 0; j < 3; j ++ )
scanf("%d ", &st[i].sub[j]);
}

/* 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 :

Enter how many students : 3


Enter name and roll number for student 1 : ANITHA,1
Enter three subject marks for student 1 : 89,56,90 Enter
name and roll number for student 2 : BALU,2 Enter
three subject marks for student 2 : 90,87,67 Enter name
and roll number for student 3 : MADHU,3 Enter three
subject marks for student 1 : 34,36,20

Total marks obtained by ANITHA are : 235


Average marks obtained : 78.3333336
ANITHA scored above the average marks

Total marks obtained by BALU are : 244


Average marks obtained : 81.3333336
BALU scored above the average marks

Total marks obtained by MADHU are : 92


Average marks obtained : 30.666666
MADHU scored below the average marks
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.

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:

Enter a binary number = 1010101


The decimal equivalent of a binary num 1010101 = 85

Sample Output 2:

Enter a binary number = 11111


The decimal equivalent of a binary num 11111 = 31
COMPUTER PROGRAMMING VIVA QUESTIONS

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.

3. What is a flow chart?


Ans: A flowchart is a type of diagram that represents an algorithm or process, showing the steps
as boxes of various kinds, and their order by connecting these with arrows.

4. What is a C Pre - processor?


Ans: C Pre - processor is a program that processes our source program before it is passed to the
compiler.

5. What is the use of header files as used in C programming?


Ans: Header files are used to have declarations. It is simple to include a single header file than
writing all the needed functions prototypes.

6. What is the Structure of a C Program?


Ans: Documentation, Section, Linking Section, Definition Section, Global declaration Section,
main function, subprogram section.

7. Explain some Header


Files? Ans:

Sl. No. Header Description


1. stdio.h This is standard input / output header file in which Input / Output
functions are declared
2. conio.h This is console input / output header file
3. string.h All string related functions are defined in this header file
4. stdlib.h This header file contains general functions used in C programs

8. What is the use of main() function?


Ans: main() is the starting point of program execution.

9. What are the types of constants in c?


Ans: C constants can be divided into two categories:
Primary constants (Numerical)
Secondary constants (Character)
10) What is a Compiler?
Ans: A compiler is a computer program (or set of programs) that transforms source code written
in a programming language (the source language) into another computer language (the target
language, often having a binary form known as object code).

10) What is a Translator?


Ans: A translator is a computer program that translates a program written in a given
programming language into a functionally equivalent program in a different language.

11) What is a Interpreter?


Ans: An Interpreter is a computer program that directly executes, i.e. performs, instructions
written in a programming or scripting language, without previously batch - compiling them into
machine language.

12) What is a Token in C?


Ans: A Token is the basic building block of a C. (or) the basic element recognized by the
compiler is the "token."
C Tokens are:
Key Words, Identifier, Constants, String – literal, Operator, Punctuators

13) What are Printf() and scanf() Functions :


Ans: printf() and scanf() functions are inbuilt library functions in C which are available in
which are available in “ stdio.h” header file.
printf() function is used to print the “character, string, float, integer, octal and hexadecimal
values” onto the output screen.
scanf() function is used to read character, string, numeric data from keyboard.
Computer Programming Viva Questions

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

15) What is Integer Data Type? Ans:


Integer data type allows a variable to store numeric values.
 The storage size of int data type is 2 or 4 or 8 byte.
 int (2 byte) can store values from - 32,768 to + 32,767
 int (4 byte) can store values from - 2,147,483,648 to + 2,147,483,647.
Sl. C data type Size in Bytes Range
No.
1. Char 1 -127 to +127
2. Int 2 –32,767 to 32,767
3. float 4 1E–37 to 1E + 37 with six digits of Precision
4. double 8 1E–37 to 1E+37 with ten digits of precision
5. Long double 10 1E–37 to 1E + 37 with ten digits of precision
6. Long int 4 –2,147,483,647 to 2,147,483,647
7. Short int 2 –32,767 to 32,767
8. unsigned short 2 0 to 65,535
int
9. signed short int 2 –32,767 to 32,767
10. long long int 8 –(2power(63) –1) to 2(power)63 –1
11. signed long int 4 –2,147,483,647 to 2,147,483,647
12. unsigned long int 4 0 to 4,294,967,295

16) What is enum Data


Type? Ans:
· Enumeration data type consists of named integer constants as a list.
· It start with 0 (zero) by default and value is incremented by 1 for the
sequential identifiers in the list.
Syntax:
enum identifier { enumerator - list };

17) What is a Void Data Type?


Ans: Void is an empty data type that has no value.

18) What is a comment in C?


Ans: Comments are like helping text in your C program and they are ignored by the compiler.
We can write in between /* and */ or // (Line Comments)

19) What is an Identifier in C?


Ans: A C identifier is a name used to identify a variable, function, or any other user - defined item.
An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more
letters, underscores, and digits (0 to 9). C does not allow punctuation characters such as @, $,
and % within identifiers. C is a case sensitive programming language.

20) What is a Key word in C?


Ans: Keywords are reserved words in C and Keywords are may not be used as constant or variable
or any other identifier names.

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

22) Define a Variable?


Ans: A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C has a specific type, which determines the size and layout of the variable's memory.
Syntax for variable Declaration:
DataType
VariableList; int i,j;
char c, ch;

23) What are the steps to develop a C Program?

· Specifying the problem statement


· Designing an algorithm
· Coding
· Debugging
· Testing and Validating
· Documentation and Maintenance.

24) What is the process of debugging or compilation for C Programs?


Ans: To check the errors in a program is called debugging or compilation. This process done by
3 stage:
1) Checking Syntactic Errors: These errors occur due to the usage of wrong syntax for the
statements. (Short cut Key : ALT + F9)
2) Checking Run time Errors / Linkage Errors: These Errors are determined at the execution
time of the program (EX: Divide a number by Zero, finding logarithmof negative number,
finding square root of negative number ,etc.)
3) Checking Linker Errors: These errors are occurred due to the linking of header file to the
current program (Short cut Key : CTRL + F9)
4) Checking Logical Errors: These Errors occur due to incorrect usage of the instruction in the
program. Logical Errors are determined by analyzing the outputs for different possible inputs
that can be applied to the program.
26) List some Syntactic Errors or Syntax Errors?
Ans:
1) Missing semicolon(Statement Missing ;)
2) Undeclared a variable name or Undefined symbol (Then check variable declaration
syntax and check for header file for some keywords)
3) ’)’ expected (Then check the no of parenthesis o pened and closed)
4) Illegal string constant ( check for the last double quote in a string)
5) printf and scanf arguments should be placed in ( )
6) Compound statement missing (Check for the no of { and } are opened and closed)
7) Proto type missing error (Check for Function declaration statement)
8) Forgetting to put &,”, and comma operator in spe cific places.
9) Comparing strings with = = operator

27) List some Warnings? Ans:


1) Miss use of = and = =
2) Loop has no body ( remove the semicolon at last of the for loop or while loop)
3) Uninitialized a variable

28) What is an Operator and list different types of operators in C?


Ans: The symbols which are used to perform logical and mathematical operations in a C program are
called C operators. The different operators in C are: Arithmetic operators, Relational
operators, Logical operators, Assignment operators, Increment and Decrement operators,
Conditional operators, Bitwise operators, Special operators

29) What are Arithmetic Operators?


Ans: Arithmetic operators are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus in C programs. (Like + , - , * , / ,%)

30) What are Assignment Operators?


Ans: Values for the variables are assigned using assignment operators. There are two types assignment
operators are there:
1) Simple Assignment( = )
2) Compound Assignment ( + = , - = , * = , % = )

31) What are Relational Operators?


Ans: Relational operators are used to find the relation between two variables. i.e. to compare the
values of two variables in a C program.. (Like >, <, > = , < = , ! = , = = )

32) What are Logical Operators?


Ans: These operators are used to perform logical operations on the given expressions. (Like &&, ||,
!)

33) What are Bitwise Operators?


Ans: These operators are used to perform bit operations. Decimal values are converted into binary
values which are the sequence of bits and bit wise operators work on these bits. (Like &, |, ~, ^,
<<(Left Shift), >> (Right Shift))
34) What are Conditional (Ternary) Operators?
Ans: Conditional operators return one value if condition is true and returns another value is condition is
false. (Like : ? and : )

35) What are Increment / Decrement Operators?


Ans: Increment operators are used to increase the value of the variable by one and decrement operators
are used to decrease the value of the variable by one in C programs. (Like + + , - - )

36) What are Special Operators?


Ans: &(Address Operator), * (Pointer Operator), and Sizeof()

37) What is sizeof operator?


Ans: It returns the number of bytes the operand occupies.

38) What is pre - increment or post - increment?


Ans: + + n (pre increment) increments n before its value is used in an assignment operation or any
expression containing it. n + + (post increment) does increment after the value of n is used.

39) What is type casting?


Ans: Converting a variable of one type to another type.

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)

41) What is a Statement in C?


Ans: A statement is a block of code that does something.

42) Different Types of Statements?


Ans: Null Statement, Expression Statement, Compound Statement, Return Statement, Conditional
Statements, Iterative or Looping Statements, Unconditional Statements

43) Define Null Statement?


Ans: A "null statement" is a statement containing only a semicolon;

44) Define Expression Statement?


Ans: When an expression statement is executed, the expression is evaluated according to the rules
outlined in Expressions and Assignments.

45) Define Compound Statement?


Ans: A compound statement (also called a "block") typically appears as the body of another
statement which is in between { and }

46) Define Return Statement?


Ans: The return statement terminates the execution of a function and returns control to the calling
function. A return statement can also return a value to the calling function.

47) Define Conditional Statements and give the list of them?


Ans: Conditional Statements which allows to perform actions depending upon some conditions
provided by the programmer. The Different types of conditional statements are:

1) If Statement
2) If else statement
3) Nested - if else statement
4) Switch Statement

48) Write the Syntax for IF


Statement? Ans: if ( <expression> )
<statement>

49) Write the Syntax for IF - ELSE


Statement? Ans: if ( <expression> )
<statement
1> else
<statement 2>

50) Write the Syntax for NESTED - IF - ELSE Statement?


Ans:
if ( <expression1> )
{
if(<expression2>)
{
<Statements>
}
else
{
<Statements>
}
}
else
<statement>

51) Write the Syntax for Switch Case


Statement? Ans: switch ( <expression> )
{
<case list> where <case list> is a sequence of case <value>:
<statement
list> break;
and optionally one default: <statement
list> break;
}

52) What are Iterative or Looping Statements?


Ans: Iterative or Looping statement which executes the statements within the compound statement
by checking the condition, and performs same set of statements as a iterative process or as a loop
until the condition false.

The Iterative or Looping Statements are: While, do - while, for

53) Write Syntax for WHILE Statement?


Ans: while ( <expression> )
<statement>

54) Write Syntax for DO - WHILE Statement?


Ans: do <statement>
while ( <expression> );

55) Write Syntax for FOR Statement?


Ans: for ( <Initialization>;<Condition>;<Increment / Decrement>)
<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.

57) What are Unconditional Statements?


Ans: goto and labeled statements, break Statement continue Statement.

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

59) Define Break Statement, Write syntax for Break statement?


Ans: The break statement terminates the execution of the nearest enclosing do, for, switch, or
while statement in which it appears. Control passes to the statement that follows the terminated
statement.
Syntax:
break;

60) Define Continue Statement, Write syntax for Continue statement?


Ans: The continue statement passes control to the next iteration of the nearest enclosing
do, for, or while statement in which it appears
Syntax:
continue;

61) Define Type Qualifiers, and list them?


Ans: The keywords which are used to modify the properties of a variable are called type
qualifiers. There are two types of qualifiers available in C language. They are,1) const 2) volatile

62) Define const Keyword with Syntax?


Ans: Constants are also like normal variables. They refer to fixed values. They are also called as
literals.
Syntax:
const data_type variable_name; (or) const data_type * variable_name;
63) Define volatile Keyword with Syntax?
Ans: When a variable is defined as volatile, the program may not change the value of the
variable explicitly.
Syntax:
volatile data_type variable_name; (or) volatile data_type * variable_name;

64) What is a Macro?


Ans: Macros are the identifiers that represent statements or expressions. To associate meaningful
identifiers with constants, keywords, and statements or expressions.

65) What is the difference between #include< > and #include “ ” ?


Ans:
#include‹ ›
Specifically used for built in header files.
#include “ ”
Specifically used for used for user defined / created n header file.

66) Define Storage class with Syntax?


Ans: Storage class specifiers in C language tells the compiler where to store a variable, how to
store the variable, what is the initial value of the variable and life time of the variable.
Syntax: storage_specifier data_type variable _name

67) What are Different Storage Classes, Explain in brief?

Initial
Storage Storage
Sl. No. default Scope
Specifier place
value
CPU Garbage
1. auto local
Memory value

2. extern CPU Zero Global

3. static CPU Zero local


memory

4. register Registe Garbag local


r e value
memor
y

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…

70) What are the Characteristics of Arrays? Ans:


An array holds elements that have the same data type. Array elements are stored in
subsequent memory locations
Two - dimensional array elements are stored row by row in subsequent memory locations.
Array name represents the address of the starting element

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]

73) How we can read or print the array elements?


Ans: To read or print the array elements we need to use FOR Statement

74) Define a String?


Ans: C Strings are nothing but array of characters ended with null character (‘\0’). Strings are always
enclosed by double quotes. Whereas, character is enclosed by single quotes in C.
Example:
char string[20] = { ‘H’ , ‘e’ , ‘l’ , ‘l’ , ‘o’ , ‘ \0’}; (or) char string[20] = “Hello”;
(or)
char string [] = “Hello”;
75) Header used for String Functions?
Ans: #include<string.h>

76) List String Handling Functions or String Manipulation Functions?


Ans: strcat(), strncat(), strcmp(), strncmp(), strcmpi(), strcpy(), strncpy(), strlen(), strchr(), strrchr(),
strstr(),strrstr(), strrev()

Function Description Syntax


Name
strcat() Concatenates str2 at the end of str1. Strcat(str1,str2);
strncat() appends a portion of string to another Strcat(str1, str2,n);
string (First n Characters of
str2 are appends to str1)
strcmp() Returns 0 if str1 is same as str2. Returns Strcmp(str1,str2);
<0 if strl < str2. Returns >0 if str1 > str2.
strncmp() Compares some portion of a string in Strncmp(str1,str2,n);
another string
strcmpi() Same as strcmp() function. But, this Strcmpi(str1,str2);
function negotiates case. “A” and “a” are
treated as same.
strcpy() Copies str2 into str1 Strcpy(str1,str2);
strncpy() copies given number of characters of one Strcpy(str1,str2,n);
string to another
strlen() gives the length of string. Strlen(str);
strchr() Returns pointer to first occurrence of char Strrchr(str,’charcater’);
in str1.
strrchr() last occurrence of given character in a Strrchr(str,’charcater’);
string is found
strstr() Returns pointer to first occurrence of str2 Strstr(str1,str2);
in str1.
strrstr() Returns pointer to last occurrence of str2 Strstr(str1,str2);
in str1.
Strrev() reverses the given string Strstr(str1);

77) What is the difference between strings and arrays?


Ans: String is a sequence of characters ending with NULL .it can be treated as a one dimensional
array of characters terminated by a NULL character.

78) Define Pointer with Syntax and example?


Ans: C Pointer is a variable that stores / points the address of another variable. C Pointer is used to
allocate memory dynamically i.e. at run time.
Syntax: data_type * var_name;
Example : int * p; char * p;

79) What are the uses of Pointers?


Ans: Pointer is used in the following cases
It is used to access array elements.
It is used for dynamic memory allocation. It is used in Call by reference.
It is used in data structures like trees, graph, linked list etc.

80) What is the invalid pointer Arithmetic?


Ans:
adding ,multiplying and dividing two pointers. Shifting or masking pointer.
Addition of float or double to pointer
Assignment of a pointer of one type to a pointer of another type

81) What is a pointer value and address?


Ans: A pointer value is a data object that refers to a memory location. Each memory location is
numbered in the memory. The number attached to a memory location is called the address of the
location.

82) How are Pointer Variables initialized?


Ans: Pointer variable are initialized in two ways:
Static memory allocation and Dynamic memory allocation.

83) What is a pointer to pointer?


Ans: If a pointer variable points another pointer value. Such a situation is known as a pointer to a pointer.
Example : int * p1,
* * p2, v = 10;P1 = &v; p2 = &p1;
Here p2 is a pointer to a pointer.

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.

85) What are the pointer declarations used in C?


Ans:
Array of pointers, e.g , int * a[10]; Array of pointers to integer Pointers to an array,e.g , int ( * a)[10];
Pointer to an array of into
Function returning a pointer,e.g, float * f( ) ; Function returning a pointer to float Pointer to a pointer
,e.g, int * * x; Pointer to a pointer to int
pointer to a data type ,e.g, char * p; pointer to char

86) What are the Advantages of Functions?


Ans:
It reduces the Complexity in a program by reducing the code.
Function are easily understanding and reliability and execution is faster.
It also reduces the Time to run a program.In other way, Its directly proportional to Complexity.
Its easy to find - out the errors due to the blocks made as function definition outside the main function.

87) What is Recursion?


Ans: A recursion function is one which calls itself either directly or indirectly it must halt at a definite
point to avoid infinite recursion.
88) What is the difference between malloc( ) and calloc( ) Functions?
Ans: Malloc is used for memory allocation and initialize garbage
values.malloc () for allocating the single block of memory.
Syntax: * ptr - variable = (type - casting * )malloc(n * sizeof(DataType))
Example: * ptr = (int * )malloc(5 * sizeof(int));
Calloc is same as malloc but it initialize 0 value.calloc () for allocating multiple blocks of memory.
Syntax: * ptr - variable = (type - casting * )calloc(n,sizeof(DataType))
Example: * ptr = (int * )calloc(5,sizeof(int));

89) What is the purpose of realloc?


Ans: It increases or decreases the size of dynamically allocated array. The function realloc (ptr,n)
uses two arguments. The first argument ptr is a pointer to a block of memory for which the size is to
be altered. The second argument specifies the new size. The size may be increased or decreased. If
sufficient space is not available to the old region the function may create a new region.

90) What is an Argument?


Ans: An argument is an entity used to pass data from the calling to a called function.

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.

92) What are the uses of Functions?


Ans: C functions are used to avoid rewriting same logic / code again and again in a program.
There is no limit in calling C functions to make use of same functionality wherever required.
We can call functions any number of times in a program and from any place in a program.
A large C program can easily be tracked when it is divided into functions.
The core concept of C functions are, re - usability, dividing a big task into small pieces to achieve the
functionality and to improve understandability of very large C programs.

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

95) Define Call by Reference?


Ans: In call by reference method, the address of the variable is passed to the function as
parameter. The value of the actual parameter can be modified by formal parameter. Same memory
is used for both actual and formal parameters since only address is used by both parameters.

96) Explain the Categories of


Functions? Ans:

Sl. no C function Syntax


with return values int function (int ); //function declaration
function ( a ); //function call
1 int function( int a ) // function definition
{statements; return a;}
void function ( int ); // function declaration
Without return function( a ); // function call void function(
2 values
int a ) // function definition
{statements;}
Without arguments and void function(); // function declaration
without return values function(); // function call void
3 function() // function definition
{statements;}
4 Without arguments and int function ( ); // function declaration function
with return values ( ); // function call
int function( ) // function definition
{statements; return a;}
VIVA QUESTIONS

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?

You might also like