Professional Documents
Culture Documents
Table of Contents
SYLLABUS 3
PART-A: Demonstration of Personal Computer and its Accessories .............................................. 1
Laboratory Session-1 .......................................................................................................................... 1
Laboratory Session-2 .......................................................................................................................... 9
PART B :Problem Solving in C - Implementation with WINDOWS / LINUX platform using
appropriate C compiler. ............................................................................................... 17
1.
2.
3.
Algorithm .............................................................................................................................. 17
1.2
Flowchart .............................................................................................................................. 19
1.3
Program ................................................................................................................................. 20
1.4
Palindrome................................................................................................................................... 22
2.1
Algorithm .............................................................................................................................. 22
2.2
Program ................................................................................................................................. 23
2.3
3.1.1
Flowchart ...................................................................................................................... 25
3.1.2
Program ......................................................................................................................... 26
3.1.3
3.2
4.
5.
6.
3.2.1
Program ......................................................................................................................... 28
3.2.2
Polynomial Evaluation................................................................................................................ 30
4.1
Algorithm .............................................................................................................................. 30
4.2
Program ................................................................................................................................. 31
4.3
Flowchart .............................................................................................................................. 33
5.2
Program ................................................................................................................................. 34
5.3
Algorithm .............................................................................................................................. 36
6.2
Program ................................................................................................................................. 37
6.3
raichur
7.
8.
9.
Program ................................................................................................................................. 39
7.2
Program ................................................................................................................................. 41
8.2
9.1.1
Program ......................................................................................................................... 44
9.1.2
9.2
9.2.1
Program ......................................................................................................................... 46
9.2.2
10.1.1
Program ......................................................................................................................... 48
10.1.2
TestCases ...................................................................................................................... 49
10.2
10.2.1
Program ......................................................................................................................... 50
10.2.2
Program ................................................................................................................................. 52
11.2
Program ................................................................................................................................. 54
12.2
Program ................................................................................................................................. 56
13.2
TestCases .............................................................................................................................. 57
Program ................................................................................................................................. 58
14.2
APPENDIX - A ...................................................................................................................................... 60
General Viva & Exercise Problems .................................................................................................................................... 60
APENDIX - B ........................................................................................................................................ 69
raichur
SYLLABUS
SEMESTER I/ II
COMPUTER PROGRAMMING LABORATORY
Sub Code
: 14CPL 16 / 14CPL26
IA Marks
: 25
Hrs/ Week
: 03
Exam Hours : 03
Total Hrs.
: 42
Exam Marks : 50
PART A
Demonstration of Personal Computer andits Accessories Demonstration and Explanation on
Disassembly and Assembly of a Personal Computer by the Faculty-in-Charge. Students have
to prepare a write-up on the same and include it in the Lab record and evaluated.
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.
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. Note:
These TWO Laboratory sessions are used to fill the gap between theory classes and practical
sessions.
PART B
Problem Solving in C - Implement the following problems with WINDOWS / LINUX
platform using appropriate C compiler.
1.
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.
2.
Design and develop an algorithm to find the reverse of an integer number NUM and
check whether it is PALINDROME or NOT. Implement a C program for the
developed algorithm that takes an integer number as input and output the reverse of
the same with suitable messages. Ex: Num: 2014, Reverse: 4102, Not a
Palindrome.
3.
i)Design and develop a flowchart to find the square root of a given number N.
Implement a C program for the same and execute for all possible inputs with
appropriate messages. Note: Dont use library function sqrt(n).
4.
ii)Design and develop a C program to read a year as an input and find whether it is
leap year or not. Also consider end of the centuries.
Design and develop an algorithm for evaluating the polynomial f(x) = a4x4 + a3x3 +
a2x2 + a1x1 + a0x0, for a given value of x and its coefficients using Horners method.
Implement a C program for the developed algorithm and execute for different sets of
values of coefficients and x.
raichur
4
5.
Draw the flowchart and Write C Program to compute Sin(x) using Taylor series
approximation given by
the built- in Library function and print both the results with appropriate message.
6.
7.
Develop, implement and execute a C program that reads two matrices A (m x n ) and
B (p x q ) and Compute the product A and B. Read matrix A in row major order and
matrix B in column major order. Print both the input matrices and resultant matrix
with suitable headings and in matrix format. Program must check the compatibility of
orders of the matrices for multiplication. Report appropriate message in case of
incompatibility.
8.
13.
Given two university information files studentname.txt and usn.txt that contents
students Names and USN respectively. Write a C program to create a new file called
output.txt and copy the content of files studentname.txt and usn.txt into output
file in the sequence shows below. Display the contents of output file output.txt on
the screen.
Write a C program to maintain a record of n student details using an array of
Student Name
USN
Name 1
USN 1
Name 2
USN 2
Heading
.
.
structures with four fields (Roll number, Name, Marks, and Grade). Each field is of
Department of CSE& ISE, SLNCE
raichur
5
an appropriate data type. Print the marks of the student given student name as input.
14.
Write a C program using pointers to compute sum, mean and standard deviation of all
elements sorted in an array of n real numbers.
Reference Book:
1. Reema Thareja, Computer Fundamentals and Programming in C, Oxford Press, 2012.
2.
3.
Strictly follow the instructions as printed on the answer script for breakup of marks.
4.
Change of experiment is allowed only once and 15% Marks should be deducted
from the procedure part.
raichur
raichur
2
repeated until the program is executed. The CPU consists of sub units to perform different
operations namely ALU, CU and MU.
a) Arithmetic and Logic Unit: The arithmetic-logic unit (ALU) is the unit of the
computer that performs arithmetic and logical operations on the data. This section of
the machine can be relatively small consisting of circuits and registers which perform
arithmetic (+, -, *, /) and logic (>, <, <=,>=, etc) operations. Arithmetic-logic units
which can add and subtract and perform logical operations form the backbone for the
arithmetic and control operations in computers. To perform scientific calculations the
floating-point number system is used.
b) Control unit: The control unit controls the overall activities of the components of the
computer. It is mainly used to coordinate the activities among the units of the
computer. It will send commands signals and controls the sequence of instructions to
be executed. The control unit may be defined as the parts that effect the retrieval of
instructions in proper sequence and application of the proper signals to the arithmetic
unit and the other parts.
Functions of Control unit
c) Memory Unit: Computer memory is an internal storage area used to store data and
programs. It can be divided into two groups: primary memory and secondary memory. The
main memory holds instructions and data when a program is executing, the auxiliary or the
secondary memory holds data and programs for long-term storage.
d) Bus: A bus is a collection of wires that carries data/Instructions. It connectsphysical
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
control signals between
CPU, Memory and I/O
devices.
raichur
3
Bidirectional in nature
Unidirectional in nature
Unidirectional in nature
ISA Bus
ISA stands for
IndustryStandard
Architecture
This is simple and
slowest bus used in
IBM PCs
Oldest, simplest
slowest bus
USB Bus
USB stands for
Universal Serial Bus
It helps to connect
various I/O devices like
keyboard, mouse, pen
drives, printer, etc.
and Newest and widely
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.
Fig 3: Chip sets
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 includes: CPU Management, Memory Management, File
raichur
4
Management, Device Management, Process/Task/Job Management and Security
Management.
The primary goal of an OS is to make the computer system convenient and efficient to
use. An OS ensures that the system resources (such as CPU, memory, I/O devices, etc) are
utilized efficiently. For example, there may be many programs residing in the main memory.
Therefore, the system needs to determine which programs are active and which need to wait
for some I/O operation.
Some of the examples of Operating Systems:
Windows XP is an O.S.
isused
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.
Fig 4: Operating System
Types of Operating Systems:The operating systems are classified into 7 types based on their
capability and usage.
Fig 5: 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).
raichur
5
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 includeFile 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.
raichur
6
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
Transmission data is
generally error prone
raichur
7
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.
Fig 7: Bus Topology
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:
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:
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:
Disadvantages:
Department of CSE& ISE, SLNCE
raichur
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:
Disadvantages:
raichur
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
amemory module. These modules are installed in the RAM slots on the
motherboardof computer. Every time you open aprogram, it gets loaded from
thehard 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
standardDRAMbecause 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'sCPUbus speed is optimized for. The
faster thebusspeed, the faster the SDRAM can be. SDRAM speed is measured inMegahertz.
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.
Department of CSE& ISE, SLNCE
raichur
10
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 consists of the components like Disc drive, disk drive motor, laser pick up
assembly tracking drive and tracking motor and so on.
Compact Disk Recordable (CD-R): The CD-R allows you to create your own CD.CD-R
drives have the ability to create CDs but they can write data on the disk only once.CD-R
technology also called as Write Once-Read much (WORM) technology.Laser technology is
used to write the data on the compact disk.CD-R drives come in IDE, SCSI and USB models.
Compact Disc Rewritable (CD-RW): CD-RW is an erasable optical disk which is used to
write data multiple times on a disk, CD-RW disks are good for data backup, data archiving or
data distribution on CDs. The disk normally holds 700MB of data.Technology to write data
multiple times on a CD was known as the Phase change Dual (PD) technology.The reflective
properties of a CD-RW are different than regular CD-ROM disks.
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
raichur
11
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
raichur
12
2) Non-Impact Printers:No physical contact is established between the print head, ribbon
(cartridge) and paper.E.g. Inkjet Printers and Laser Printers
4
5
6
7
8
9
10
Inkjet Printer
Laser Printer
Impact Printer
Non-impact Printer
Non-impact printer
Its print head does not have
It uses metal pins in its
metal pins, instead it has The laser printer uses a
head to create text and
several tiny nozzles that spray beam of laser for
graphics in the form of
ink onto the paper. Each printing.
dots.
nozzle is thinner than hair.
The process of printing
The ink cartridges are attached The printer uses a
involves striking a pin
to the printer head that moves cylindrical drum, a toner
against a ribbon to
horizontally from left to right. and the laser beam.
produce its output.
Printing speed is slower Printing speed is slower than Printing speed is higher
than laser printer,
laser dot matrix.
than both.
Character by character
Line by line printing
It is a page printer
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 DPI Speed is measured in CPI Speed is measured in
(Dots Per Inch)
(Characters Per Inch)
PPM (Pages Per Minute)
Monochrome (Black &
Monochrome and color
Color printer
White) Printers
printer
raichur
13
Algorithm
Flowchart
Pseudo Code
raichur
14
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, aflowchart depicts the
flow of a program. The following table shows the symbols used in flowchart along with its
descriptions.
Symbol
Name
oval
Rectangle
Parallelogram
Diamond
Arrows
Small circle
Description
Represents the terminal point
Represents the process steps defined in
algorithm
Indicate the reading Operation used for
input/output or data or information from/to
any device
Indicates the decisions (questions) and
consequently the branch points or the paths to
be followed based on the result of the question
Shows the flowchart direction and connects
the various flow chart symbols
Shows the continuation from one point in the
process flow to another
Represents Looping structures
Hexagon
Predefined
Process
Indicates Subroutines
Advantages of Flowcharts:
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.
problems.
raichur
15
E.g.: To compute the Area of Rectangle
Start
Read length,
breadth
Area =length*breadth
Print Area
Stop
Limitations of using Flowcharts:
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
raichur
16
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
raichur
17
1. Quadratic Equation
1. 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 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.
Purpose: This program demonstrates IF, IF-ELSE conditional constructs.
Procedure: To read the coefficientsa, b, c and check if any of the coefficients value is 0. If
any coefficient value is 0, print appropriate messages and re-run the program. Otherwise,
calculate discriminant. Based on the discriminant value, classify and calculate all possible
roots and print them with suitable messages.
Input:Three coefficientsofquadratic equationax2+bx+c=0:a, b, c
ExpectedOutput: This program computes all possible roots for a given set of coefficients
with appropriate messages. The possible roots are:
1.
2.
3.
4.
1.1 Algorithm
ALGM:Quadratic Equation[This algorithm takes three coefficients as input and computes
the roots]
Steps:
1. [Initialize] Start
2. [Input coefficients of quadratic equation]
read a,b,c
3. [Check for valid coefficients]
Ifa =0andb= 0then
print Roots cannot be determined
[Check for linear equation]
else a=0then
root1 (-c/b)
print Linear equation,root1
goto step 5
4. [Compute discriminant value]
disc b*b-4*a*c
Department of CSE& ISE, SLNCE
raichur
18
5. [Based on discriminant value, classify and calculate all possible roots and print them]
5.1
5.2
5.3
6. [Finished] End
raichur
19
1.2 Flowchart
raichur
20
1.3 Program
/* Program to calculate all possible roots of a quadratic equation */
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
float a, b, c, disc;
float root1,root2,real,imag;
clrscr();
printf("Enter a,b,c values\n");
scanf("%f%f%f",&a,&b,&c);
if( (a == 0) && (b == 0) )
{
printf("Invalid coefficients\n");
printf(" Try Again with valid inputs !!!!\n");
}
elseif(a == 0)
{
printf("linear equation\n");
root1 = -c / b;
printf("Root=%.3f", root1);
}
else
{
disc = b*b - 4*a*c;
if(disc == 0)
{
printf("The roots are real and equal\n");
root1 = root2 = -b/(2*a);
printf("Root1 = %.3f \nRoot2 = %.3f", root1,root2);
}
elseif(disc>0)
{
printf("The roots are Real and Distinct\n");
root1 = (-b+sqrt(disc)) / (2*a);
root2 = (-b-sqrt(disc)) / (2*a);
printf("Root1 = %.3f \nRoot2 = %.3f",root1,root2);
}
else
{
printf("The roots are Real and Imaginary\n");
real = -b / (2*a);
imag = sqrt(fabs(disc)) / (2*a);//fabs() returns only numberignoring sign
printf("Root1 = %.3f + i %.3f \n",real,imag);
printf("Root2 = %.3f - i %.3f",real,imag);
}
}
return 0;
}
raichur
21
Input
Parameters
Expected output
Rema
rks
Obtained output
a =0,b=0,c=0
Invalid coefficients
Try Again with valid inputs !!!!
Invalid coefficients
Try Again with valid inputs !!!!
PASS
a =0,b=2,c= 8
Linear equation
Root = -4
Linear equation
Root =-4.000
PASS
a = 1,b= 6,c= 9
PASS
a = 1,b= -5,c= 3
PASS
a = 1,b= 4,c= 7
PASS
a =0,b= 4,c= 5
a = 2,b= -7,c=0
a = 2,b= -7,c=8
Viva Questions:
1. What is quadratic Equation?
2. What is math.h ?
3. What are decision making capabilities of C language?
4. Write the syntax of if statement?
5. Difference between if and switch statements?
6. Write an unconditional controlstatement in C.
7. Write a flowchart for if conditional construct?
Exercise Problems:
1. Write a program to swap two integers with and without using temporary variables
2. Write a program to check whether a person is eligible to vote
3. Write a program to check whether a number is even or odd
4. Write a program to check whether a number is positive negative or zero using nested if
statement
5. Write a program to find largest of two numbers
6. Write a program to find largest of three numbers using nested if else statement
7. Write a program to find largest of three numbers using else if ladder
8. Write a program to display the grade based on marks obtained by the students using else
if ladder
9. Write a program to perform arithmetic operations based on the users choice using else if
ladder
Other alternates:
Try the same quadratic equation program using switch statement.
Department of CSE& ISE, SLNCE
raichur
22
2. Palindrome
2. Design and develop an algorithm to find the reverse of an integer number NUM
andcheck whether it is PALINDROME or NOT. Implement a C program for the
developedalgorithm that takes an integer number as input and output the reverse of the
samewith suitable messages. Ex: Num: 2014, Reverse: 4102, Not a Palindrome.
Purpose: This program demonstrates the WHILE loop.
Procedure:Input the original number num, reverse itto rev. Check whether original
numbernum is same as its reverse number rev. If it is same, the number is palindrome.
Otherwise, the given number is not palindrome.
Input:An integer number num.
Expected Output: Reversed number revandchecks whether it is palindrome or not.
2.1 Algorithm
ALGM: Palindrome[This algorithm takesan integer number as input and output the reverse
of the same. Also checks the number is palindrome or not]
Steps:
1. [Initialize] Start
2. [Input the original number]
read num
3. [Set number num to a variable n]
n num
4. [Iterate until num is not equal to 0.
If num value becomes 0, control comes out of the loop. So nums original value is
lost. So, num value is stored in other variable n in step 3.
In step 4, reverse of the number is calculated.]
while ( num != 0) do
remainder num mod 10
num num/10
rev rev * 10 +remainder
5. [Print reverse number]
print rev
6. [Check if original number & reverse number are same. If it is, number is palindrome.
Otherwise, not palindrome]
if (rev = n)then
print palindrome
else
print not a palindrome
endif
7. [Finished]
End
raichur
23
2.2 Program
/* Program to calculate whether a given number is palindrome or not */
#include<stdio.h>
#include<conio.h>
int main()
{
int n,rev=0,num, remainder ;
clrscr();
printf("Enter the number\n");
scanf("%d",&num);
n=num;
while(num!=0)
//Reversing the number
{
remainder = num%10;
num = num/10;
rev = rev*10+ remainder;
}
printf("The reverse number is %d",rev);
if(rev == n)
printf("\n%d is a palindrome",n);
else
printf("\n%d is not a palindrome",n);
return 0;
}
Input
Parameters
N = 1441
N = 9987
N = -12221
4
5
Expected output
Obtained output
Remarks
N = -6758
PASS
N=0
Reverse number is 0
Palindrome
Reverse number : 0
0 is a palindrome
PASS
N=1010
Pass
N=0101
Pass
PASS
PASS
PASS
raichur
24
N = 1234
N = 1100
N = 0203
Viva Questions:
1. What are Looping control statements?
2. Explain while loop.
3. What is the output of this C code?
Faculty should give code here
4. What is the difference between while and for loops?
5. What are the Entry controlled and Exit controlled loops in C ?
6. Write the flowchart for while loop.
7. Write the flowchart for do..while loop
Exercise Problems:
1.
2.
3.
4.
5.
Other alternate:
Try the same palindrome program using for/do-whilestatement.
raichur
25
3.1.1 Flowchart
raichur
26
3.1.2 Program
/* Program to calculate square root of the given number without using built in function */
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()// Please add the logic
{
int s;
double x,d,n;
clrscr();
printf("Enter the number\n");
scanf("%lf",&n);
if(n>=0)
{
for(s=1;s*s<=n;s++);
//calculating decimal part of the square root
s--;
for(d = 0.001;d < 1.0;d += 0.001)
// calculating the fractional part
{
x = (double)s + d;
if((x*x > (double)n))
{
x = x - 0.001;
break;
}
}
printf("The square root of the given number is %.3lf\n", x);
printf("The square root as per built in function sqrt()is %.2lf", sqrt(n));
}
else
{
printf( "No square root to a negative number");
}
return 0;
}
Input
Parameters
Expected output
N=49
Square root is 7
N=30
N=50.5
N= -4
No square root to a
negative number
PASS
N=0
Square root is 0
Square root = 0
PASS
Obtained output
Square root is 7.000
Using built in function Sqrt() is 7.00
Square root is 5.477
Using built in function Sqrt() is 5.48
Square root is 7.106
Using built in function Sqrt() is 7.11
Rema
rks
PASS
PASS
PASS
N =2
N = 16.25
raichur
27
Viva Questions:
1.
2.
3.
4.
5.
Exercise Problems:
1. Write a program to find the sum of n natural numbers using for loop
2. Write a program to illustrate the usage of unconditional branching
statements(break,continue and goto)
3. Write a program to find sum of squares of n natural numbers using for loop
4. Write a program to generate Fibonacci series for a given number using for loop
5. Write a program to find factorial of a given number using for loop
6. Write a program to calculate xn using for loop
7. Write a program to evalvate ex series using for loop
8. Write a program to find the sum of digits of a number using for loop
9. Write a program to find the sum of series 1+1/2+1/3++1/n using for loop
10. Write a program to print the following patterns using nested for loop
a)
1
b)
* * *
c) 1 2 3
1 2
* * *
1 2
1 2 3
* * *
1
Other alternate :
This program can be done by using while loop also. Cant be done using other methods?
raichur
28
Input
Parameters
Expected output
Obtained output
Remarks
Year=2012
Leap year
PASS
Year=1900
PASS
Year=2000
Leap year
PASS
Year = 2045
Year = 2016
Viva Questions:
1.
2.
3.
4.
raichur
29
5. Which of the following operator has the highest precedence in the following?
a) ()
b) sizeof
c) * d) +
Exercise Problems:
1. Write a program to demonstrate the use of logical operators?
2. Write a program to demonstrate the use of relational operators?
3. Write a program to calculate number days between the two dates?
Alternate ways :
This program can be executed without using && and || operators.
raichur
30
4. Polynomial Equation
4.Design and develop an algorithm for evaluating the polynomial f(x) = a4x4 + a3x3 +
a2x2+ a1x + a0, for a given value of x and its coefficients using Horners
method.Implement a C program for the developed algorithm and execute for different
sets of values ofcoefficients and x.
Input:An array of different set of values of coefficientsa4, a3,a2, a1and constant a0-a[]
Indeterminate or variable -x
Number of coefficients- n
ExpectedOutput:Sum of all terms of the polynomial - sum
Purpose: This program describes FOR loop.
Procedure: To read x, n, a[ ] . Calculate the terms of polynomial and add each term to
sum by iterating from n to 0. Thenprint sum value.
4.1 Algorithm
ALGM: EVAL_POLYNOMIALf(x) = a4x4+ a3x3+ a2x2+ a1x+ a0using Horners
method
Steps:
1. [Initialize] Start
2. [Input the number of coefficients n]
read n
3. Set sum to 0
4. [Read all coefficients a1, a2, a3, a4and constanta0]
Foreach value i in array a(i)do
read n+1 coefficients
endfor
5. [Input variable x]
read x
6. [Iterate from n to 0. Calculate each term a4x4, a3x ,a2x2,a1x, a0 . ]
Foreach value iin array a(i) do
sum sum * x + a[i]
endfor
7. Print sum
8. [Finished]
Department of CSE& ISE, SLNCE
raichur
31
EndEnd
4.2 Program
/* Evaluating the polynomial f(x) = a4x4+ a3x3+ a2x2+ a1x+ a0 using Horners method
(n, i, sum, a[], x) */
#include<stdio.h>
#include<conio.h>
int main()
{
int n,i,sum=0,a[10],x;
clrscr();
printf("enter the number of co-efficients n>=0\n");
scanf("%d",&n);
printf("enter the n+1 co-efficients\n");
for(i=n;i>=0;i--)
{
printf("Enter a[%d] th coefficient : ",i);
scanf("%d",&a[i]);
}
printf("enter value of x\n");
scanf("%d",&x);
for(i=n;i>0;i--)
{
sum=sum+x*a[i];
}
sum=sum+a[0];
printf("the value of sum is %d",sum);
return 0;
}
Input Parameters
Expected
output
Obtained
output
Remarks
Sum = 15
PASS
Sum = 25
PASS
raichur
32
Viva Questions:
1. What is an array? Give an example
2. What is an multidimensional array?
3. How to declare and initialize one dimensional array?
4. What are the advantages of an array?
5. Differentiate between i++ and i-- ?
Exercise Problems
1. Write a program to Calculate the sum of polynomial without using Horners method
2. Write a program to add all the element of single dimensional array.
3. Write a program to find largest and smallest number in an array.
4. Write a c program to find out second largest element of an unsorted array.
5. Write a c program for delete an element at desired position in an array.
6. Write a c program for insert an element at desired position in an array.
raichur
33
5. Sine Series
5. Write C Program to compute Sin(x) using Taylor series approximation given by
Sin(x) = x - (x3/3!) + (x5/5!) - (x7/7!) + .Compare the result with the built- in Library
function and print both the results.
5.1 Flowchart
raichur
34
5.2 Program
/* Program to calculate sine value of given angle */
#include<stdio.h>
#include<conio.h>
#include<math.h>
#define PI 3.142
int main()
{
int i, degree;
float x, sum=0,term,nume,deno;
clrscr();
printf("Enter the value of degree");
scanf("%d",°ree);
x = degree * (PI/180);
//converting degree into radian
nume = x;
deno = 1;
i=2;
do
{
//calculating the sine value.
term = nume/deno;
nume = -nume*x*x;
deno = deno*i*(i+1);
sum=sum+term;
i=i+2;
} while (fabs(term) >= 0.00001);
// Accurate to 4 digits
printf("The sine of %d is %.3f\n", degree, sum);
printf("The sine function of %d is %.3f", degree, sin(x));
return 0;
}
5.3
Test Cases
Test
No
Input
Parameters
Expected output
Degree = 0
The sine of 0 is = 0
Degree = 30
Degree = 60
Degree = -10
Obtained output
The sine of 0 is= 0.000
Using inbuilt function sin(0)= 0.000
The sine of 30 is= 0.500
Using inbuilt function sin(30)= 0.500
The sine of 60 is= 0.866
Using inbuilt function sin(60)= 0.866
The sine of -10 is= - 0.174
Using inbuilt function sin(-10)= -0.174
Remarks
PASS
PASS
PASS
PASS
Degree = 90
Degree = 45
raichur
35
Viva Questions:
1. What is pre-processor directive?
2. What is difference between const and #define.
3. What is use of fabs().
4. What is variable initialization and why is it important?
5. What is the difference between the = symbol and == symbol?
6. Can the curly brackets { } be used to enclose a single line of code?
Exercise Problems:
1. Write C Program to compute cos(x) using Taylor series approximation.
2. Write C Program to compute exusing Taylor series approximation.
3. Write a C program to compute Log x
Other alternates:
This program can be executed by reading number of terms
raichur
36
6. Bubble Sort
6. Develop an algorithm, implement and execute a C program that reads N integer
numbers and arrange them in ascending order using Bubble Sort.
Purpose:This program demonstrates NESTED FOR loop.
Procedure: To read an array of elements a[ ] . While iterating, compare each pair of adjacent
items in every pass. If the former value is greater than the latter one, their positions are
swapped. Over a number of passes, at most equal to the number of elements in the list, all of
the values drift into their correct positions. Then print sorted array elements.
Input: Number of Elements n
An array of unsorted elements a[ ]
Output: An array of sorted elements a[ ]
6.1 Algorithm
ALGM: Bubble Sort[ This algorithm takes a list of unordered numbers and arrange them in
ascending order using Bubble Sort method]
Steps:
1. [Initialize] Start
2. [Input number of elements]
read n
3. [Input unsorted elements in array]
read elements in array a[ ]
4. print elements of array a[ ]
5. [Iterate array a[ ] in two loops. Outer loop gives number of passes. Inner loop does
swap task.
In each pass, compare each pair of adjacent items. If former element is greater than
latter one, swap them.]
[Iterate array a[ ] with
for each value i in array a[i] to n do
for each value j in array a[j] to n-1 do
[Compare each pair of adjacent elements]
if (a[j] > a[j+1])then
[Swap these elements using temp variable]
temp a[j]
a[j] a[j+1]
a[j+1] temp
endif
endfor
endfor
6. Print array with sorted elements
7. [Finished]
End
raichur
37
6.2 Program
#include<stdio.h>
#include<conio.h>
int main()
{
int n,i,j,a[10],temp;
clrscr();
printf("Enter the no. of elements : \n");
scanf("%d",&n);
printf("Enter the array elements \n");
for(i = 0 ; i < n ; i++)
scanf("%d",&a[i]);
printf("The original elements are \n");
for(i = 0 ; i < n ; i++)
printf("%d ",a[i]);
for(j= 1 ; j <= n-1 ; j++)
{
for(i = 0 ; i <= n-j-1; i++)
if(a[i] > a[i+1])
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}
printf("\n The Sorted elements are \n");
for(i = 0 ; i < n ; i++)
printf("%d ",a[i]);
return 0;
}
// Number of Passes
// Comparisons
Input Parameters
Expected output
Obtained output
Remarks
N=5
A[5]={23,4,6,12,40}
A ={23,4,6,12,40}
Sorted A ={4,6,12,23,40}
PASS
N=4
A[4]={67,5,0,34}
Org={67,5,0,34}
Sorted={0,5,34,67}
PASS
N=4
A[4]={-3,-9,12,6}
N=5
A[5]={12,23,6,54,6}
Org={-3,-9,12,6}
Sorted={-9,-3,6,12}
Org={12,23,6,54,6}
Sorted={6,6,12,23,54}
3
4
PASS
PASS
N=8
N=15
raichur
38
Viva Questions:
1.
2.
3.
4.
Exercise Problems:
1.
2.
3.
4.
5.
raichur
39
7. Matrix Multiplication
7. Develop, implement and execute a C program that reads two matrices A (m x n )and B (p x q
) and Compute the product A and B. Read matrix A in row major orderand matrix B in column
major order. Print both the input matrices and resultant matrixwith suitable headings and in
matrix format. Program must check the compatibility oforders of the matrices for
multiplication. Report appropriate message in case ofincompatibility.
7.1 Program
#include<stdio.h>
#include<conio.h>
int main()
{
int a[5][5],b[5][5],c[5][5],m,n,p,q,i,j,k;
clrscr();
printf("Enter the size of first matrix\n");
scanf("%d %d",&m,&n);
printf("Enter the size of second matrix\n");
scanf("%d %d",&p,&q);
if(n==p)
{
printf("Enter the elements of first matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the elements of the second matrix\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("The product of two matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",c[i][j]);
Department of CSE& ISE, SLNCE
raichur
40
}
printf("\n");
}
}
else
printf("Multiplication is not possible\n");
return 0;
}
Input Parameters
Matrix A Size= 2, 2
Matrix B Size= 2, 2
Elements=
1 2
5 6
3 4 * 7 8
Matrix A Size= 2, 3
Matrix B Size= 2, 2
Matrix A Size= 2, 3
Matrix B Size= 3, 2
Elements=
1 2 42 4
2 1 3 * 32
1 1
Matrix A Size= 2, 2
Matrix B Size= 2, 2
Elements=
4 -5
10 -7
8 9 * 3 2
Expected output
Obtained output
Remarks
The product of
two matrix
19 22
43 50
PASS
Invalid input
Multiplication
not possible
PASS
The product of
two matrix
12 12
1013
PASS
The product of
two matrix
-25 38
107 -38
PASS
Matrix A Size= 2, 3
Matrix B Size=3, 2
Viva Questions:
1.
2.
3.
4.
Exercise Problems:
1.
2.
3.
4.
raichur
41
8.1 Program
/* progrm to search an name using binary search */
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char name[10][20], key[20];
int n, i, low, high, mid, found=0;
clrscr();
printf("Enter the number of names to read, n=");
scanf("%d", &n);
printf("Enter the names in ascending order\n");
for(i=0;i<n;i++)
scanf("%s", name[i]);
printf("Enter the name to be search:");
scanf("%s", key);
low=0;
high=n-1;
while(low<=high && !found)
{
mid=(low + high)/2;
if(strcmp(name[mid],key)==0)
found=1;
elseif(strcmp(name[mid],key)<0)
low=mid+1;
else
high=mid-1;
}
if(found == 1)
printf("Name found in position : %d",mid+1);
else
printf("Name not found");
return 0;
}
raichur
42
Input Parameters
Expected output
name found in
N=5
name[0] = amar
position : 2
name[1] = chethan
name[2] = girish
name[3] = manoj
name[4] = yadu
key = chethan
2
name found in
N=5
position : 5
name[0] = amar
name[1] = chethan
name[2] = girish
name[3] = manoj
name[4] = yadu
key = yadu
3
name not found
N=6
name[0] = bhaskar
name[1] = darshan
name[2] = nagaraj
name[3] = sathish
name[4] = teju
name[5] = vishwas
key = prakash
4
Names are not in
N=4
name[0] = sathish
ascending order
name[1] = kiran
name[2] = adarash
name[3] = bhaskar
key = sathish
Test the following cases and record
5
N=4
name[0] = sathish
name[1] = kiran
name[2] = adarash
name[3] = bhaskar
key = kiran
6
N=3
name[0] = amar
name[1] = chethan
name[2] = girish
key = amarrr
Obtained output
Remarks
name found in
position : 2
PASS
name found in
position : 5
PASS
PASS
Fail
Note: Always
enter the
names in
ascending
order
Viva Questions:
1.
2.
3.
4.
raichur
43
Exercise Problems:
1. Write a program in C to a search an element using linear search.
2. Write a program in C to sort and search an element using binary search.
raichur
44
i.
ii.
Reads a sentence and prints frequency of each of the vowels and total count of
consonants.
raichur
45
Input
Parameters
Expected output
Str1=RNSIT
Str2=RNSIT
Obtained output
Destination string
Str2=hello
Destination string
Str2=CSE & ISE Dept
Remarks
PASS
PASS
Viva Questions
1. Define a Function?
2. What is the difference between User-defined and Standard library/Pre-defined
functions?
3. Is main() a user-defined function or pre-defined function?
4. What is the Calling function and Called function?
5. What are the Actual parameters /arguments and Formal parameters/arguments?
6. Explain the concept of pass by value / call by value?
7. Explain the void type in C ?
8. What is NULL Character ?
9. What is the difference between character and a string?
10. What are string constants?
11. What are character constants?
Exercise Problems
1.
2.
3.
4.
raichur
46
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[100],ch;
int i,vc=0,cc=0;
clrscr();
printf("Enter the sentence\n");
gets(s);
for(i=0;i<strlen(s);i++)
{
if(isalpha(s[i]))
{
ch=tolower(s[i]);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
vc++;
else
cc++;
}
}
printf("No of vowels=%d\n",vc);
printf("No of consonants=%d",cc);
}
9.2.2 Test Cases
Test No
Input Parameters
Expected output
Obtained output
Remarks
Vowels=7
Consonants=11
Vowels=7
Consonants=11
PASS
Str=FIRE FOX
Vowels=3
Consonants=4
Vowels=3
Consonants=4
PASS
Vowels=3
Consonants=8
Vowels=3
Consonants=8
PASS
Str = qwerty@#$
Str = DER$
gthy
raichur
47
Viva Questions:
1.
2.
3.
4.
5.
6.
7.
Exercise Problems:
1.
2.
3.
4.
5.
6.
raichur
48
raichur
49
10.1.2 TestCases
Test
No
Input Parameters
Expected output
Result=2
(hint : after rotation :
0000 0000 0000 0010)
Obtained
output
Remarks
Result=2
PASS
PASS
Viva Question
1.
2.
3.
4.
5.
Exercise Problems
1.
2.
3.
4.
5.
6.
raichur
50
raichur
51
Input Parameters
Expected output
Obtained output
Range
Prime numbers are
Prime numbers are
X=0 & Y=10
2 3 5 7
2 3 5 7
Range
Prime numbers are
Prime numbers are
2
X=5 & Y=15
5 7 11 13
5 7 11 13
Range
There are no prime
There are no prime
3
X=8 & Y=10
numbers
numbers
Test for the following cases and Record the observations
Range
4
X=10 & Y=30
Range
5
X=15 & Y=25
1
Remarks
PASS
PASS
PASS
Viva Question
1.
2.
3.
4.
Exercise Problem:
1. Write a program to generate a prime number between range 1 to 100.
raichur
52
11.1 Program
#include<stdio.h>
#include<conio.h>
int fact(int n)
{
if(n==0)
{
return 1;
}
Return (n*fact(n-1));
}
void main()
{
int n,r,res;
clrscr();
printf("Enter the value of n and r\n");
scanf("%d%d",&n,&r);
res=fact(n)/(fact(n-r)*fact(r));
printf("The NCR is = %d",res);
}
Input Parameters
Expected output
Obtained output
Remarks
C2 = 6
PASS
C5 = 1
PASS
C2 = 6
C5 = 1
N=3&R=1
raichur
53
Exercise Problems
1.
2.
3.
4.
5.
raichur
54
Student Name
Name1
Name2
.
.
USN
USN1
USN2
.
.
Heading
12.1 Program
/* program to merge two files */
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fptr1,*fptr2,*fptr3;
char ch1,ch2;
clrscr();
fptr1 = fopen("studentn.txt", "r");
if (fptr1 == NULL)
{
printf("Cannot open file \n");
exit(0);
}
fptr2 = fopen("usn.txt", "r");
if (fptr2 == NULL)
{
printf("Cannot open file \n");
exit(0);
}
fptr3 = fopen("output.txt" ,"w");
do
{
while ((ch1 = fgetc(fptr1)) != '\n')
{
if (ch1 == EOF)
break;
else
fputc(ch1, fptr3);
}
fputc('\t',fptr3);
while ((ch2 = fgetc(fptr2)) != '\n')
{
if (ch2 == EOF)
break;
else
fputc(ch2, fptr3);
}
fputc('\n', fptr3);
}while(ch1 !=EOF || ch2 !=EOF);
Department of CSE& ISE, SLNCE
raichur
55
fclose(fptr3);
fptr3 = fopen("output.txt", "r");
printf("Student Name \t USN\n");
printf("-----------------------\n");
while((ch1=fgetc(fptr3))!=EOF)
printf("%c",ch1);
fclose(fptr1);
fclose(fptr2);
fclose(fptr3);
}
Input Parameters
Expected output
Obtained output
Remarks
PASS
Create a file
student.txt
contains names
Manoj
Suresh
Kiran
Dont create
usn.txt
PASS
Create a file
student.txt
contains names
Manoj
Suresh
Kiran
Create file usn.txt
100
200
300
Creates output.txt
and contains
Manoj
100
Suresh
200
Kiran
300
In output device
Student name usn
--------------------------Manoj
100
Suresh
200
Kiran
300
In output.txt file
Manoj 100
Suresh 200
Kiran 300
&
In output device
Student name usn
--------------------------Manoj
100
Suresh
200
Kiran
300
PASS
Viva Questions:
1.
2.
3.
4.
5.
6.
7.
8.
9.
What is file?
File is type of ___________? Ans: Struct type
What is file mode ? Mention the different types of file mode ?
What is pointer and NULL pointer?
Write the syntax of fopen( ) and fclose ( )?
How the fgetc( ) and fputc( ) works ?
If there is any error while opening a file, fopen will return__________? Ans : NULL
EOF indicate________? Ans : End of file (EOF) is used to report end of file.
What is difference between fgetc( ) and fgets( )?
Exercise Problems:
1. Write a program in C to a copy one file to another file.
2. Write a program in C to count number of words, blank space, & number of lines in a
file.
3. Write a program in C to merge two files.
Department of CSE& ISE, SLNCE
raichur
56
13.
13. Write a C program to maintain a record of "n" student details using an array of
structures with four fields (Roll number, Name, marks, and Grade). Each field is of an
appropriate data type. Print the marks of the student given name as input.
13.1 Program
/* program to maintain a record of student using structrue */
#include<stdio.h>
#include<conio.h>
struct student
{
int rollno, marks;
char name[20], grade;
};
void main()
{
int i, n, count=0;
struct student s[10];
char sname[20];
clrscr();
printf("Enter the number of student details n=");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nenter the %d student details \n",i+1);
printf("enter the roll number:");
scanf("%d",&s[i].rollno);
printf("enter the student name without white spaces:");
scanf("%s", s[i].name);
printf("enter the marks : ");
scanf("%d", &s[i].marks);
printf("enter the grade : ");
fflush(stdin);
scanf("%c",&s[i].grade);
}
printf("\nStudent details are \n");
printf("\nRollno\tName\t\t\tMarks\tGrade\n");
for(i=0;i<n;i++)
printf("%d\t%s\t\t%d\t%c\n", s[i].rollno, s[i].name, s[i].marks, s[i].grade);
printf("\nEnter the student name to print the marks:");
scanf("%s", sname);
for(i=0;i<n;i++)
{
if(strcmp(s[i].name, sname)==0)
{
printf("\nMarks of the student is : %d", s[i].marks);
count++;
}
}
if(count==0)
printf("Given student name is not found");
}
Department of CSE& ISE, SLNCE
raichur
57
13.2 TestCases
Test
No
1
Input Parameters
Expected
output
Obtained
output
Rem
arks
Name
Marks
Grade
S[0]. 100
Divya
90
S[1]. 200
Pavithra
80
300
Tanisha
60
S[2]
Divya
Marks=
90
Divya
PASS
Marks= 90
Name
Marks
Grade
S[0]. 100
Krish
75
S[1]. 200
Krish
80
Krish
Marks=
75
80
Krish
Marks=
Given
student
name not
found
Given
student
name not
found
PASS
75
80
Name
Marks
Grade
S[0]. 100
Divya
90
S[1]. 200
Pavithra 80
Tanisha
S[2]
300
60
PASS
N=5
Viva Questions:
1.
2.
3.
4.
5.
6.
7.
8.
9.
What is a structure?
Give the difference between an array and a structure?
Does the definition of a structure create memory space?
How are individual elements of a structure accessed?
What is an enumerated data?
What is union?
What are the difference between structure and union?
What is the use of fflush( ).
Difference between strcmp() and strcmpi().
Exercise Problems:
1. Write a program in C to create employee details using a structure.(the members of
structure are empno, ename, basic salary, HRA, DA, Gross_salary).
raichur
58
Mean :is the average of the numbers. i.ethe sum of a collection of numbers divided by the
number of numbers in the collection
14.1 Program
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
float a[10], *ptr, mean, std, sum=0, sumstd=0;
int n,i;
clrscr();
printf("Enter the no of elements\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\t",sum);
printf("Mean=%f\t",mean);
printf("Standard deviation=%f\t",std);
}
raichur
59
Input Parameters
N=8
Array elements
2 4 4 4 5 5 7 9
N=4
Array elements
1 2 3 4
Expected output
Obtained output
Sum=40
Mean=5
Standard
deviation=2
Sum=10
Mean=2.5
Standard
deviation=0.790569
Sum=40
Mean=5
Standard
deviation=2
Sum=10
Mean=2.5
Standard
deviation=0.790569
Remarks
PASS
PASS
N=5
Array elements
2 3 4 8 10
N=6
Array elements
1 3 5 7 9 11
Viva Question :
Define pointer?
What does * and & operator indicate with respect to pointer.
What are the advantages of using pointer.
How is a pointer variable declared?
Give the difference between static allocation and dynamic allocation of memory
space.
6. Give the difference between call by value and call by reference
7. What is the effect of the ++ and --operators on pointer variable
1.
2.
3.
4.
5.
Exercise Problem:
1. Write a program to display the value and address of a variable.
2. Write a program to illustrate pointer initialization.
3. Write a program to show the amount of space required to store variables (i.e. int,
float, and char variable) and space reserved for pointers.
4. Write a c program to swap the contents of two variables by passing address to the
function.
raichur
60
APPENDIX - A
General Viva & Exercise Problems
Viva and Exercise problems on Basic concepts of C program
Define preprocessor directives.
What is the syntax for preprocessor directive?
What are header files?
What does include stands for?
Give some examples of built-in functions stored in math.h ,conoi.h ,stdio.h,string.h.
What type of a function is main()?
What are variables?
Name the basic data type available in C.
What is the size of following data type?
a) int b) float c) char d)long int e) double
10. What are format specifiers?
11. Name the format specifiers for the following data type.
a) int b) float c) char d)long int e) double
12. Name formatted input output functions.
13. Give the syntax for printf() and scanf().
14. In which header file, printf() is defined?
15. What are the arguments taken by the function printf( )?
16. What are the two arguments taken by scanf()?
17. What is the output of the following code?
void main()
{
int a;
printf (%d,x);
}
18. Name unformatted input output functions.
19. How many characters is read by the function getchar() and gets ()?
20. How do you differentiate getche() and getchar()?
21. What is the significance of using getch() in the program?
22. What are compound statements?
23. What are built-in functions?
24. How many keywords are available in C?
25. Keywords are also known as _________.
26. What are Identifiers?
27. What are Constants?
28. Name the three types of coding constants?
29. What are qualifiers?
30. What is the range of unsigned integer?
31. Give the syntax for defined constant?
32. What is const? Where is it used?
33. Give an example for character constant.
34. What is ASCII value?
1.
2.
3.
4.
5.
6.
7.
8.
9.
raichur
61
35.
36.
37.
38.
39.
Exercise
1. Write a program to print Hello World.
2. Write a program to print your name, college, usn.
3. Write a program to print the pattern * * * * *
*****
*****
4. Write a program to read a number and display the number.
5. Write a program to add,subtract,multiply and divide two integers.
6. Write a program to read a character and display it using unformatted input output
functions.
7. Write a program to find the ASCII value of a character.
What is an operator?
Name the different types of operators in C.
What is associativity?
Arithmetic operators are left to right associative.(True / false)
How multiple assignments are done? Is it left to right or right to left associative?
Name relational operators? It is also known as ______.
What are unary operators?
Give some examples for unary operators.
What is an address operator?
Give the syntax for ternary operator.
What type of operator is increment operator?
Which operator is used to know the size of all data type?
Name logical operator. Why is it used?
Which operator has highest precedence among logical operators?
What type of operators are >> and <<?
Is there any rotate operator in C?
= is an example of -------------------------- operator.
A=b. Explain this?
What is declaration?
Give an example of initialization of variable. How it works?
What are local variables?
What are global variables?
What is the significance of giving semicolon at the end of every statement?
What are backslash constants?
What does this indicates \a and \t?
raichur
62
26.
27.
28.
type
in
implicit
type
}
32. Differentiate post and pre increment operator.
33. Write the output for the following code?
void main ()
{
int a=8, b, c=10, d;
b = ++a;
printf(%d\n%d,a,b);
d=c++;
printf(%d\n%d,c,d);
}
Exercise
1. Write a program to demonstrate arithmetic operators.
2. Write a program to print the right most digit of a number.
3. Write a program to demonstrate relational operators.
4. Write a program to demonstrate logical operators.
5. Write a program to demonstrate bitwise operators.
6. Write a program to demonstrate post& pre increment of a variable(post & pre decrement)?
7. Write a program to find the size of all data type using sizeof( ) operator.
8. Write a program to find largest to two integers using conditional operator.
9. Write a program to demonstrate implicit and explicit type conversion .
10. Write a program to find the radius of a circle.
11. Write a program to swap two integers with and without using temporary variables.
12. Write a program to convert degrees into radians and vice versa.
13. Write a program to convert Celsius into Fahrenheit.
14. Write a program to demonstrate literal constant defined constant and memory constant.
Department of CSE& ISE, SLNCE
raichur
63
raichur
64
Exercise
Write a program to check whether a person is eligible to vote using if construct.
Write a program to check whether a number is even using if construct.
Write a program to check whether a student has secured distinction using if construct.
Write a program to check whether a number is positive negative or zero using
multiple if statement.
5. Write a program to find the roots of quadratic equation using multiple if statement.
6. Write a program to find largest of two numbers using if else statement.
7. Write a program to check whether a number is even or odd using if else statement.
8. Write a program to check whether the entered digit is vowel or consonant using if else
statement.
9. Write a program to find largest of three numbers using nested if else statement.
10. Write a program to find largest of three numbers using else if ladder.
11. Write a program to check whether a number is positive negative or zero using else if
ladder.
12. Write a program to display the grade based on marks obtained by the students using
else if ladder.
13. Write a program to perform arithmetic operations based on the users choice using
else if ladder.
14. Write a program to find the roots of quadratic equation using else if ladder.
15. Write a program to perform arithmetic operations based on users choice using switch
statement.
16. Write a program to calculate area of circle area of rectangle and area of square based
on users choice using switch statement.
17. Write a program to check whether an entered character is vowel or consonant using
switch statement.
18. Write a numbers program to print the numbers 1 to 10 using while loop.
19. Write a program to reverse a number using while loop.
20. Write a program to find factorial of a number using while loop.
21. Write a program to convert binary to decimal and vice versa using while loop.
22. Write a program to find sum of n natural numbers using while loop.
23. Write a program to find factorial of a number using do-while loop.
24. Write a program to convert binary to decimal and vice versa using do-while loop.
25. Write a program to print the numbers 1to 10 using for loop.
26. Write a program to find the sum of n natural numbers using for loop.
27. Write a program to find sum of squares of n natural numbers using for loop.
28. Write a program to find fibonacci of a given number using for loop.
29. Write a program to find factorial of a given number using for loop.
30. Write a program to determine whether a given number is prime or not using for loop.
31. Write a program to determine whether a given number is even or odd using for loop.
32. Write a program to check whether a number is divisible by 3 using for loop.
33. Write a program to calculate pow(x,n) using for loop.
34. Write a program to evaluate ex series using for loop.
35. Write a program to find the sum of digits of a number using for loop.
36. Write a program to find the sum of series 1+1/2+1/3++1/n using for loop
1.
2.
3.
4.
raichur
65
37. Write a program to print the following patterns using nestedfor loop
a) 1
b)
* * *
c) 1 2 3
1 2
* * *1 2
1 2 3
* * * 1
38. Write a program to illustrate the usage
statements(break,continue and goto).
of
unconditional
branching
raichur
66
1.
2.
3.
4.
5.
6.
7.
8.
Exercise
1.
2.
3.
4.
5.
6.
raichur
67
What is a pointer?
How to declare a pointer?
What does a pointer hold?
What is a null pointer?
In pass by address, the formal parameters should be declared as ____________.
* is also known as__________ operator.
Can we have pointer to pointer?
Differentiate a normal variable and a pointer.
What is the output of the following program?
void main()
{
int a=10;
int *p;
p=&a;
printf(%d,a);
printf(%u,p);
printf(%d,*p);
printf(%u,&a);
}
10. What is recursion?
11. Why base case is required in recursion?
12. When the return statement will be executed ?
13. Which data structure is used to implement recursion?
14. Give examples for recursion.
15. Differentiate iteration and recursion.
1.
2.
3.
4.
5.
6.
7.
8.
9.
Exercise
1.
2.
3.
4.
5.
raichur
68
Exercise
1. Write a program to create stack using arrays.
2. Write a program to create queue using arrays.
raichur
69
APENDIX - B
Screenshots Of C Program Execution In Windows Operating System:
Open
Turbo C and click on File -> New to open the editor to type the program.
raichur
70
Click Compile -> Compile (This is option within compile menu) to compile C program or
press alt+F9:
raichur
71
Compilation process:
Click Run -> Run (This the option within the run menu) or Press ctrl+F9to execute the C
program:
raichur
72
raichur
73
Enter vi command in following format: vi Hello.c where Hello is file name and it is
programmers choice.
Now, editor is opened. Press i key or insert key to change editor to insert mode, where
we can type the program.
raichur
74
After compilation, run the program using ./a.out command to see the output.
raichur