1
Department of CSE& ISE, SLNCE raichur
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. Quadratic Equation .................................................................................................................... 17
1.1 Algorithm .............................................................................................................................. 17
1.2 Flowchart .............................................................................................................................. 19
1.3 Program ................................................................................................................................. 20
1.4 Test Cases ............................................................................................................................. 21
2. Palindrome ................................................................................................................................... 22
2.1 Algorithm .............................................................................................................................. 22
2.2 Program ................................................................................................................................. 23
2.3 Test cases .............................................................................................................................. 23
3. Square Root and Leap Year ....................................................................................................... 25
3.1 Square root of a given Number ............................................................................................. 25
3.1.1 Flowchart ...................................................................................................................... 25
3.1.2 Program ......................................................................................................................... 26
3.1.3 Test cases ...................................................................................................................... 26
3.2 Leap Year .............................................................................................................................. 28
3.2.1 Program ......................................................................................................................... 28
3.2.2 Test Cases ..................................................................................................................... 28
4. Polynomial Evaluation ................................................................................................................ 30
4.1 Algorithm .............................................................................................................................. 30
4.2 Program ................................................................................................................................. 31
4.3 Test Cases ............................................................................................................................. 31
5. Sine Series .................................................................................................................................... 33
5.1 Flowchart .............................................................................................................................. 33
5.2 Program ................................................................................................................................. 34
5.3 Test Cases ............................................................................................................................. 34
6. Bubble Sort .................................................................................................................................. 36
6.1 Algorithm .............................................................................................................................. 36
6.2 Program ................................................................................................................................. 37
6.3 Test Cases ............................................................................................................................. 37
Vijay Kumar HosaGoudar
2
Department of CSE& ISE, SLNCE raichur
7. Matrix Multiplication ................................................................................................................. 39
7.1 Program ................................................................................................................................. 39
7.2 Test Cases ............................................................................................................................. 40
8. Binary Searching Technique ...................................................................................................... 41
8.1 Program ................................................................................................................................. 41
8.2 Test Cases ............................................................................................................................. 42
9. String Copy and Frequency of Vowels ...................................................................................... 44
9.1 String copy without using library function ........................................................................... 44
9.1.1 Program ......................................................................................................................... 44
9.1.2 Test Cases ..................................................................................................................... 45
9.2 Vowels and Consonants Count ............................................................................................. 46
9.2.1 Program ......................................................................................................................... 46
9.2.2 Test Cases ..................................................................................................................... 46
10. Right Rotate and isprime or not ................................................................................................ 48
10.1 Right Rotate by n Positions ................................................................................................... 48
10.1.1 Program ......................................................................................................................... 48
10.1.2 TestCases ...................................................................................................................... 49
10.2 To Check Prime or Not ......................................................................................................... 50
10.2.1 Program ......................................................................................................................... 50
10.2.2 Test Cases ..................................................................................................................... 51
11. Factorial of Number using Recursive function ........................................................................ 52
11.1 Program ................................................................................................................................. 52
11.2 Test Cases: ............................................................................................................................ 52
12. Copy the Contents Of File .......................................................................................................... 54
12.1 Program ................................................................................................................................. 54
12.2 Test Cases ............................................................................................................................. 55
13. Student Records - using Array of Structures .......................................................................... 56
13.1 Program ................................................................................................................................. 56
13.2 TestCases .............................................................................................................................. 57
14. Use of Pointers ............................................................................................................................. 58
14.1 Program ................................................................................................................................. 58
14.2 Test Cases ............................................................................................................................. 59
APPENDIX - A ...................................................................................................................................... 60
General Viva & Exercise Problems .................................................................................................................................... 60
APENDIX - B ........................................................................................................................................ 69
Screenshots Of C Program Execution’ In Windows Operating System: ....................................... 69
Screenshots of C Program Execution’ in Linux Operating System: .............................................................. 73
Vijay Kumar HosaGoudar
3
Department of CSE& ISE, SLNCE 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 (ax
2+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: Don’t use library function sqrt(n).
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.
4. Design and develop an algorithm for evaluating the polynomial f(x) = a4x4 + a3x
3 +
a2x2 + a1x
1 + a0x
0, for a given value of x and its coefficients using Horner’s method. Implement a C program for the developed algorithm and execute for different sets of values of coefficients and x.
Vijay Kumar HosaGoudar
4
Department of CSE& ISE, SLNCE raichur
5. Draw the flowchart and Write C Program to compute Sin(x) using Taylor series
approximation given by Compare the result with
the built- in Library function and print both the results with appropriate message.
6. Develop an algorithm, implement and execute a C program that reads N integer numbers and arrange them in ascending order using Bubble Sort.
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. Develop, implement and execute a C program to search a Name in a list ofnames using Binary Searching Technique.
9. Write and execute a C program that i. Implements string copy operation STRCOPY(str1,str2) that copies a string str1 to
another string str2 without using library function. ii. Reads a sentence and prints frequency of each of the vowels and total count of
consonants. 10. i)Design and develop a C function RightShift(x ,n) that takes two integers x and n as
input and returns value of the integer x rotated to the right by n positions. Assume the integers are unsigned. Write a C program that invokes this function with different values for x and n and tabulate the results with suitable headings. ii)Design and develop a C function isprime(num) that accepts an integer argument and returns 1 if the argument is prime, a 0 otherwise. Write a C program that invokes this function to generate prime numbers between the given ranges
11. Draw the flowchart and write a recursive C function to find the factorial of a number, n!, defined by fact(n)=1, if n=0. Otherwise fact(n)=n*fact(n-1). Using this function,
write a C program to compute the binomial coefficient n
r . Tabulate the results for
different values of n and r with suitable messages.
12. 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.
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
Student Name USN
Name 1 USN 1
Name 2 USN 2
……… ……. ……… …….
Heading
Vijay Kumar HosaGoudar
5
Department of CSE& ISE, SLNCE raichur
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.
Practical Examination Procedure:
Part – A: Experiment is a demo experiment only and shall not be included in practical exam.
Part – B:
1. All experiments are to be included for practical examination.
2. Students are allowed to pick one experiment from the lot.
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.
Vijay Kumar HosaGoudar
1
Department of CSE& ISE, SLNCE raichur
PART-A: Demonstration of Personal Computer and its
Accessories
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:
Fig 1: Block Diagram of a Computer
Notations:
Data and Results flow
Control instructions to other units from control unit
Instructions from memory unit to control unit
1) Input unit: The input unit helps to enter (feed) 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.
2) System or Central Processing Unit: The processing unit interprets the program
instructions in memory, controls the flow of data and performs arithmetic and logical
operations. The program instructions are processed one at a time along with the necessary
data. The results are sent to memory and the next instruction is processed. This method is
Vijay Kumar HosaGoudar
2
Department of CSE& ISE, SLNCE raichur
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
Accessing data & instructions from memory unit
Interpreting instructions
Controlling input and output units
Overall supervision of a Computer system
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
data between Processor,
Memory and I/O devices
It is used to transfer the
addresses of data and
instructions stored in
memory.
It is used to transfer the
control signals between
CPU, Memory and I/O
devices.
Vijay Kumar HosaGoudar
3
Department of CSE& ISE, SLNCE raichur
Bidirectional in nature Unidirectional in nature Unidirectional 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
Peripheral Component
Interconnect
ISA stands for
IndustryStandard
Architecture
USB stands for
Universal Serial Bus
The motherboard will
be having 3 or 4 PCI
connectors, so that we
can insert various chips.
This is simple and
slowest bus used in
IBM PCs
It helps to connect
various I/O devices like
keyboard, mouse, pen
drives, printer, etc.
Fastest and presently
more powerful bus
Oldest, simplest and
slowest bus
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
Vijay Kumar HosaGoudar
4
Department of CSE& ISE, SLNCE raichur
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).
Vijay Kumar HosaGoudar
5
Department of CSE& ISE, SLNCE raichur
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.
Fig 6: Computer Network
Basic components of a computer network: The basic components of a network are as
follows.
1. Protocols: Set of rules used during the data transmission.
Vijay Kumar HosaGoudar
6
Department of CSE& ISE, SLNCE raichur
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 are
connected in a small area such
as building, home, office etc
i.e. within a small campus
A network which covers
large area like a city
A network which covers a
large area like a state,
country or across a
continent.
Distance covered by this
network is less than 1 KM
Distance covered by this
network is 5 to 50 KM.
Distance covered by this
network is 100 to 1000 KM
Used within a single building
like home or office
Used by private organization
like cable television in our
city.
Used all over the world. i.e.
good example is internet
Computers are connected
through the twisted pair cables
and co axial cables.
A network device called
router is used to connect the
LANs together
It uses fibre optics, cables
and even satellite signals as
a transmission media.
Transmitting data is cheaper Transmitting data is costlier Transmitting data is more
costlier
Transmission data is generally
error free
Transmission data is
generally error prone
Transmission data is
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:
Vijay Kumar HosaGoudar
7
Department of CSE& ISE, SLNCE raichur
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:
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:
Vijay Kumar HosaGoudar
8
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:
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
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.
Vijay Kumar HosaGoudar
9
Department of CSE& ISE, SLNCE 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.
Vijay Kumar HosaGoudar
10
Department of CSE& ISE, SLNCE raichur
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
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.
Vijay Kumar HosaGoudar
11
Department of CSE& ISE, SLNCE raichur
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 hasa groupof switches resembling the
keyson 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
Vijay Kumar HosaGoudar
12
Department of CSE& ISE, SLNCE raichur
2) Non-Impact Printers:No physical contact is established between the print head, ribbon
(cartridge) and paper.E.g. Inkjet Printers and Laser Printers
Dot matrix, Inkjet and Laser printers
Sl.
No. Dot Matrix Printer Inkjet Printer Laser Printer
1 Impact Printer Non-impact Printer Non-impact printer
2
It uses metal pins in its
head to create text and
graphics in the form of
dots.
Its print head does not have
metal pins, instead it has
several tiny nozzles that spray
ink onto the paper. Each
nozzle is thinner than hair.
The laser printer uses a
beam of laser for
printing.
3
The process of printing
involves striking a pin
against a ribbon to
produce its output.
The ink cartridges are attached
to the printer head that moves
horizontally from left to right.
The printer uses a
cylindrical drum, a toner
and the laser beam.
4 Printing speed is slower
than laser printer,
Printing speed is slower than
laser dot matrix.
Printing speed is higher
than both.
5 Character by character
printing Line by line printing It is a page printer
6 Low quality printing High quality printing High quality printing
7 Less expensive High expensive High expensive
8 Generates much noise
while printing
Generates less noise while
printing No noise
9 Speed is measured in DPI
(Dots Per Inch)
Speed is measured in CPI
(Characters Per Inch)
Speed is measured in
PPM (Pages Per Minute)
10 Monochrome (Black &
White) Printers Color printer
Monochrome and color
printer
Plotters: A plotter is similar to printer that produces hard-copy output
with high-quality colour graphics. Plotters are generally more
expensive than printers, ranging from about $1000 to $75000.
Vijay Kumar HosaGoudar
13
Department of CSE& ISE, SLNCE raichur
Problem Solving Techniques:
Theprocessofworkingthrough details of aproblemtoreachasolution.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 andunambiguous i.e. each and every
instruction should be clear and should have only one meaning.
Finiteness: Noteven 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 ALGM: AREA_of_RECTANGLE [This algorithm takes length and breadth, the sides of the rectangle as input and computes the area of rectangle using the formula area=length * breadth. Finally it prints the area of rectangle]
STEPS: Step 1:[Initialize]
Start Step 2: [Input the sides of Rectangle]
Read length, breadth
Step 3:[Compute the area of rectangle] Arealength*breadth
Step 4:[Display the Area]
Print Area Step 5: [Finished]
Stop
Vijay Kumar HosaGoudar
14
Department of CSE& ISE, SLNCE raichur
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 Description
oval Represents the terminal point
Rectangle
Represents the process steps defined in algorithm
Parallelogram Indicate the reading Operation used for input/output or data or information from/to any device
Diamond Indicates the decisions (questions) and 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 Process
Indicates Subroutines
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).
Vijay Kumar HosaGoudar
15
Department of CSE& ISE, SLNCE raichur
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
Vijay Kumar HosaGoudar
16
Department of CSE& ISE, SLNCE raichur
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
Vijay Kumar HosaGoudar
17
Department of CSE& ISE, SLNCE raichur
PART – B: Problem Solving in C- Implement thefollowing problems with WINDOWS
/ LINUX platform using appropriate C compiler.
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. Linear equation and its roots 2. Real & equal roots 3. Real & distinct roots 4. Imaginary roots
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
Vijay Kumar HosaGoudar
18
Department of CSE& ISE, SLNCE raichur
5. [Based on discriminant value, classify and calculate all possible roots and print them]
5.1 [If discriminant value is 0, roots are real & equal.]
if disc=0 then
root1← root2 ← (-b/2*a)
print “Real & equal roots”, root1, root2
5.2 [ If discriminant value is >0, roots are real & distinct.]
else ifdisc>0then
root1← (-b+√disc)/(2*a) root2 ← (-b-√disc)/(2*a) print “Real & distinct roots”, root1, root2
5.3 [ If discriminant value is <0, roots are imaginary.]
else
real ← -b/(2*a)
imag ← √(fabs(disc))/(2*a) root1 ← (real) + i (imag)
root2 ← (real) - i (imag)
print “Imaginary roots”, root1, root2
endif
endif
6. [Finished] End
Vijay Kumar HosaGoudar
19
Department of CSE& ISE, SLNCE raichur
1.2 Flowchart
T
Vijay Kumar HosaGoudar
20
Department of CSE& ISE, SLNCE raichur
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; }
Vijay Kumar HosaGoudar
21
Department of CSE& ISE, SLNCE raichur
1.4 Test Cases
Test
No
Input
Parameters Expected output Obtained output
Rema
rks
1 a =0,b=0,c=0 Invalid coefficients Try Again with valid inputs !!!!
Invalid coefficients Try Again with valid inputs !!!!
PASS
2 a =0,b=2,c= 8 Linear equation Root = -4
Linear equation Root =-4.000
PASS
3 a = 1,b= 6,c= 9 Roots are real and equal Root1 = -3 and Root2= -3
Roots are real and equal Root1 = -3.000 and Root2= -3.000
PASS
4 a = 1,b= -5,c= 3 Roots are real and distinct Root1 = 4.30 and Root2= 0.69
Roots are real and distinct Root1 = 4.303 and Root2= 0.697
PASS
6 a = 1,b= 4,c= 7 Roots are real and imaginary Root1 = -2 + i 1.73 Root2 = -2 – i 1.73
Roots are real and imaginary Root1 = -2.000 + i 1.732 Root2 = -2.000 – i 1.732
PASS
Test for the following cases & record your observations
7 a =0,b= 4,c= 5
8 a = 2,b= -7,c=0
9 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.
Vijay Kumar HosaGoudar
22
Department of CSE& ISE, SLNCE raichur
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 num’s 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
Vijay Kumar HosaGoudar
23
Department of CSE& ISE, SLNCE raichur
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; }
2.3 Test cases
Test
No
Input
Parameters Expected output Obtained output Remarks
1 N = 1441 Reverse number is 1441
Palindrome Reverse number is: 1441
1441 is a palindrome PASS
2 N = 9987 Reverse number is 7899
Not a palindrome Reverse Number: 7899
9987 is not a palindrome PASS
3 N = -12221 Reverse number is -12221
Palindrome Reverse number : -12221 -12221 is a palindrome
PASS
4 N = -6758 Reverse number is -8576
Not a palindrome Reverse Number: -8576
-6758 is not a palindrome PASS
5 N = 0 Reverse number is 0
Palindrome Reverse number : 0 0 is a palindrome
PASS
6
N=1010 Reverse number is 0101
Not a Palindrome Reverse number :101
1010 is not a palindrome Pass
7 N=0101 Reverse number is 101
Palindrome Reverse number :101 101 is a palindrome
Pass
Vijay Kumar HosaGoudar
24
Department of CSE& ISE, SLNCE raichur
Test for the following cases & record your observations
6 N = 1234
7 N = 1100
8 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. Write a program to find factorial of a number using while loop
2. Write a program to convert binary to decimal and vice versa using while loop
3. Write a program to find sum of n natural numbers using while loop
4. Write a program to find factorial of a number using do-while loop
5. Write a program to convert binary to decimal and vice versa using do-while loop
Other alternate:
Try the same palindrome program using for/do-whilestatement.
Vijay Kumar HosaGoudar
25
Department of CSE& ISE, SLNCE raichur
3. Square Root and Leap Year
3.1 Square Root of a given Number
3a. 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 withappropriate
messages. Note: Don’t use library function sqrt(n).
3.1.1 Flowchart
Vijay Kumar HosaGoudar
26
Department of CSE& ISE, SLNCE raichur
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; }
3.1.3 Test cases
Test
No
Input
Parameters Expected output Obtained output
Rema
rks
1 N=49 Square root is 7 Square root is 7.000
Using built in function Sqrt() is 7.00 PASS
2 N=30 Square root is 5.477 Square root is 5.477
Using built in function Sqrt() is 5.48 PASS
3 N=50.5 Square root is 7.106 Square root is 7.106
Using built in function Sqrt() is 7.11 PASS
4 N= -4 No square root to a negative number
No square root to a negative number PASS
5 N = 0 Square root is 0 Square root = 0 PASS
Test for the following cases & record your observations
6 N = 2
7 N = 16.25
Vijay Kumar HosaGoudar
27
Department of CSE& ISE, SLNCE raichur
Viva Questions:
1. What is typecasting? Explain with an examples.
2. Difference between float and double data types.
3. Explain for loop?
4. What is a use of break statement?
5. Difference between continue and break statement?
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?
Vijay Kumar HosaGoudar
28
Department of CSE& ISE, SLNCE raichur
3.2 Leap Year
3b. Design and develop a C program to read a year as an input and find whether it is
leapyear or not. Also consider end of the centuries.
3.2.1 Program
/* Program to find whether given year is leap year or not */ #include<stdio.h> #include<conio.h> int main() { int year; clrscr(); printf("Enter valid year\n"); scanf("%d",&year); if((year%4==0) && (year%100!=0) || (year%400 ==0)) //check for leap year { printf("%d is leap year", year); } else { printf("%d is not a leap year",year); } return 0; }
3.2.2 Test Cases
Test
No
Input
Parameters Expected output Obtained output Remarks
1 Year=2012 Leap year 2012 is a leap year PASS
2 Year=1900 Not a leap year 1900 is not a leap year PASS
3 Year=2000 Leap year 2000 is a leap year PASS
Test for the following cases & record your observations.
4 Year = 1786
5 Year = 2045
6 Year = 2016
Viva Questions:
1. Why n++ executes faster than n+1?
2. Explain about % and ! operator.
3. Which of the operators has associativity from Right to Left?
4. List the operators having same precedence?
Vijay Kumar HosaGoudar
29
Department of CSE& ISE, SLNCE raichur
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.
Vijay Kumar HosaGoudar
30
Department of CSE& ISE, SLNCE raichur
4. Polynomial Equation
4.Design and develop an algorithm for evaluating the polynomial f(x) = a4x4 + a3x
3 +
a2x2+ a1x + a0, for a given value of x and its coefficients using Horner’s
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+ a3x
3+ a2x
2+ a1x+ a0using Horner’s
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 ,a2x
2,a1x, a0 . ]
Foreach value iin array a(i) do
sum ← sum * x + a[i]
endfor
7. Print sum
8. [Finished]
Vijay Kumar HosaGoudar
31
Department of CSE& ISE, SLNCE raichur
EndEnd
4.2 Program
/* Evaluating the polynomial f(x) = a4x4+ a3x
3+ a2x
2+ a1x+ a0 using Horner’s 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; }
4.3 Test Cases
Test
No
Input Parameters Expected
output
Obtained
output
Remarks
1
Enter the no of coefficients of N= 4 enter the coefficient n+1 of array a
a[4]=1 a[3]=2 a[2]=3 a[1]=4 a[0]=5
Enter the value of x = 1
Sum = 15 Sum = 15 PASS
2 N= 0 enter the coefficient n+1 of array a
a[0]=25 Enter the value of x = 2
Sum = 25 Sum = 25 PASS
Test for the following cases & record your observations
5 N=2 and X=3 a[2]= -3, a[1]= 4,a[0] = -5
6 N=5 and X=2 Give negative coefficients
Vijay Kumar HosaGoudar
32
Department of CSE& ISE, SLNCE raichur
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.
Vijay Kumar HosaGoudar
33
Department of CSE& ISE, SLNCE raichur
5. Sine Series 5. Write C Program to compute Sin(x) using Taylor series approximation given by
Sin(x) = x - (x3/3!) + (x
5/5!) - (x
7/7!) + …….Compare the result with the built- in Library
function and print both the results.
5.1 Flowchart
Vijay Kumar HosaGoudar
34
Department of CSE& ISE, SLNCE raichur
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 Obtained output Remarks
1 Degree = 0 The sine of 0 is = 0 The sine of 0 is= 0.000
Using inbuilt function sin(0)= 0.000 PASS
2 Degree = 30 The sine of 30=0.500 The sine of 30 is= 0.500
Using inbuilt function sin(30)= 0.500 PASS
3 Degree = 60 The sine of 600 = 0.866 The sine of 60 is= 0.866
Using inbuilt function sin(60)= 0.866 PASS
4 Degree = -10 The sine of -100 = -0.17 The sine of -10 is= - 0.174
Using inbuilt function sin(-10)= -0.174 PASS
Test for the following cases & record your observations.
5 Degree = 90
6 Degree = 45
Vijay Kumar HosaGoudar
35
Department of CSE& ISE, SLNCE raichur
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
Vijay Kumar HosaGoudar
36
Department of CSE& ISE, SLNCE raichur
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
Vijay Kumar HosaGoudar
37
Department of CSE& ISE, SLNCE raichur
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++) // Number of Passes { for(i = 0 ; i <= n-j-1; i++) // Comparisons 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; }
6.3 Test Cases
Test
No Input Parameters Expected output Obtained output Remarks
1 N=5
A[5]={23,4,6,12,40} Sorted ele are:
A[5]={4,6,12,23,40} A ={23,4,6,12,40}
Sorted A ={4,6,12,23,40} PASS
2 N=4
A[4]={67,5,0,34} Sorted ele are:
A[4]={0,5,34,67} Org={67,5,0,34}
Sorted={0,5,34,67} PASS
3 N=4
A[4]={-3,-9,12,6} Sorted ele are:
A[4]={-9,-3,6,12} Org={-3,-9,12,6}
Sorted={-9,-3,6,12} PASS
4 N=5
A[5]={12,23,6,54,6} Sorted ele are:
A[5]={6,6,12,23,54} Org={12,23,6,54,6}
Sorted={6,6,12,23,54} PASS
Test for the following cases & record your observations
5 N=8
6 N=15
Vijay Kumar HosaGoudar
38
Department of CSE& ISE, SLNCE raichur
Viva Questions:
1. Why the name bubble sort? 2. Mention the different types of sorting techniques? 3. Explain the logic of bubble sort with an example. 4. What is nested for loop?
Exercise Problems:
1. Write a program in c to swap two numbers without using temporary variable. 2. Write a program to sort elements using selection sort. 3. Write a program to reverse the element of an array number without using another array. 4. Write a program to sort an element in descending order bubble sort. 5. Write a program to find the first and second largest element in array.
Vijay Kumar HosaGoudar
39
Department of CSE& ISE, SLNCE raichur
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]);
Vijay Kumar HosaGoudar
40
Department of CSE& ISE, SLNCE raichur
} printf("\n"); } } else printf("Multiplication is not possible\n"); return 0; }
7.2 Test Cases
Test No Input Parameters Expected output Obtained output Remarks
1
Matrix A Size= 2, 2 Matrix B Size= 2, 2
Elements= 1 2 5 6
3 4 * 7 8
The product of two matrix 19 22 43 50
The product of two matrix
19 22 43 50
PASS
2 Matrix A Size= 2, 3 Matrix B Size= 2, 2
Invalid input
Multiplication not possible
PASS
3
Matrix A Size= 2, 3 Matrix B Size= 3, 2
Elements= 1 2 42 4 2 1 3 * 32 1 1
The product of two matrix 12 12 1013
The product of two matrix
12 12 1013
PASS
4
Matrix A Size= 2, 2 Matrix B Size= 2, 2
Elements= 4 -5 10 -7 8 9 * 3 2
The product of two matrix
-25 38 107 -38
The product of two matrix -25 38 107 -38
PASS
Test for the following cases & record your observations.
5 Matrix A Size= 2, 3 Matrix B Size=3, 2
Viva Questions:
1. What are multi dimensional arrays? 2. How to initialize two dimensional arrays? 3. How to pass a two dimensional array as function parameter? 4. How the memory is allocated for two dimensional array
Exercise Problems:
1. Write the program to add and subtract two matrix. 2. Program to find the transpose of a matrices. 3. Program to find determinants of a matrices.
4. Program to find the diagonal elements of a matrix.
Vijay Kumar HosaGoudar
41
Department of CSE& ISE, SLNCE raichur
8. Binary Searching Technique
8. Develop, implement and execute a c program to search a name in list of names using
Binary Searching Technique
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; }
Vijay Kumar HosaGoudar
42
Department of CSE& ISE, SLNCE raichur
8.2 Test Cases
Test
No
Input Parameters Expected output Obtained output Remarks
1 N=5 name[0] = amar name[1] = chethan name[2] = girish name[3] = manoj name[4] = yadu key = chethan
name found in position : 2
name found in position : 2
PASS
2 N=5 name[0] = amar name[1] = chethan name[2] = girish name[3] = manoj name[4] = yadu key = yadu
name found in position : 5
name found in position : 5
PASS
3 N=6
name[0] = bhaskar name[1] = darshan name[2] = nagaraj name[3] = sathish name[4] = teju name[5] = vishwas key = prakash
name not found name not found PASS
4 N=4 name[0] = sathish name[1] = kiran name[2] = adarash name[3] = bhaskar key = sathish
Names are not in ascending order
Name not found Fail Note: Always
enter the
names in
ascending
order
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
Viva Questions:
1. Explain how the binary search program works? 2. Which arethe different types of searching techniques? 3. What is difference between linear search and binary search?
4. What are the advantages and disadvantages of binary search techniques?
Vijay Kumar HosaGoudar
43
Department of CSE& ISE, SLNCE raichur
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.
Vijay Kumar HosaGoudar
44
Department of CSE& ISE, SLNCE raichur
9. String Copy and Frequency of Vowels
9.Write and execute a C program that
i. Implements string copy operation STRCOPY(str1,str2) that copies a string str1 to
another string str2 without using library function.
ii. Reads a sentence and prints frequency of each of the vowels and total count of
consonants.
9.1 String Copy without using library function
Implements string copy operation STRCOPY(str1,str2) that copies a string str1 to another
string str2 without using library function. This program supposed to be implemented using
functions
9.1.1 Program
/* program to copy string without using library function */
#include<stdio.h>
#include<conio.h>
// function to copy a string
void strcopy(chars1[50], char s2[50])
{
int i=0;
while(s[1i]!='\0')
{
s2[i]=s1[i];
i++;
}
s2[i]='\0';
}
int main()
{
char str1[50],str2[50];
clrscr();
printf("Enter the source string\n");
gets(str1);
strcopy(str1,str2);
printf("Destination string is\n");
puts(str2);
return 0;
}
Vijay Kumar HosaGoudar
45
Department of CSE& ISE, SLNCE raichur
9.1.2 Test Cases
Test
No
Input
Parameters Expected output Obtained output Remarks
1 Str1=RNSIT Str2=RNSIT Destination string
Str2=hello PASS
2 Str1=CSE & ISE
Dept Str2=CSE & ISE Dept
Destination string Str2=CSE & ISE Dept
PASS
Test for the following cases & record your observations.
3 Str1 =
ello#%good
4 Str1 = 12345
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. Program to reverse a string without using built-in function. 2. Program to copy a string with using library function. 3. Program to check the given string is palindrome or not. 4. Program to string concatenation without using strcat()
Vijay Kumar HosaGoudar
46
Department of CSE& ISE, SLNCE raichur
9.2 Vowels and Consonants Count
ii. Reads a sentence and prints frequency of each of the vowels and total count
ofconsonants.
9.2.1 Program
/* program to prints frequency of vowels and total count of consonants */
#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
1 Str = hello apple umbrella Vowels=7
Consonants=11 Vowels=7
Consonants=11 PASS
2 Str=FIRE FOX Vowels=3
Consonants=4 Vowels=3
Consonants=4 PASS
3 Str= bitty butter 123 Vowels=3
Consonants=8 Vowels=3
Consonants=8 PASS
Test for the following cases & record your observations.
4 Str = qwerty@#$
5 Str = DER$ gthy
Vijay Kumar HosaGoudar
47
Department of CSE& ISE, SLNCE raichur
Viva Questions:
1. Mention some built-in functions of string.h header file
2. What is isalpha function?
3. What is tolower function?
4. What is strlen function?
5. What is strcpy function?
6. What is strcat function?
7. How the of strcmp( ) function works?
Exercise Problems:
1. Write a c program to delete the all consonants from given string.
2. Write a c program to sort the characters of a string.
3. Program to convert uppercase to lowercase and vice versa
4. Program to print the ASCII value of a given character
5. Program to find the string length without using built-in function.
6. Write a program to find a substring in a given string.
Vijay Kumar HosaGoudar
48
Department of CSE& ISE, SLNCE raichur
10. Right Rotate and isprime or not
10. i)Design and develop a C function RightShift(x ,n) that takes two integers x and n
as input and returns value of the integer x rotated to the right by n positions. Assume the
integers are unsigned. Write a C program that invokes this function with different values
for x and n and tabulate the results with suitable headings.
ii) Design and develop a C function isprime(num) that accepts an integer argument and
returns 1 if the argument isprime, a 0 otherwise. Write a C program that invokes this
function to generate prime numbers between the given ranges
10.1 Right Rotate by n Positions
Design and develop a C function RightShift(x ,n) that takes two integers x and n as input and
returns value of the integer x rotated to the right by n positions.
10.1.1 Program
/* program to rotate right */
#include<stdio.h>
#include<conio.h> #include<math.h>
//function to right rotate unsignedint RightShift(unsignedint x,unsignedint n) { int i; for(i=0;i<n;i++) { if(x%2==0) x=x>>1; else { x=x>>1; x=x+32768; } } return(x); }
void main()
{ unsignedint x,y,n,i,value; char input; clrscr(); do {
printf("\nEnter the number and the no of bits to be” “rotated\n"); scanf("%u %u",&x,&n); y=x; value=RightShift(x,n); printf("\nCALULATED VALUE rightrot of %u,%u=%u",y,n,value); printf("\nTocontinue press 'y' else press 'n'\n"); input=getche(); }while(input!='n'); }
Vijay Kumar HosaGoudar
49
Department of CSE& ISE, SLNCE raichur
10.1.2 TestCases
Test
No Input Parameters Expected output
Obtained
output Remarks
1 X=4 & N=1
(hint: binary for 4: 0000 0000 0000 0100)
Result=2 (hint : after rotation :
0000 0000 0000 0010)
Result=2 PASS
2 X=5 & N=2
(hint: binary for : 0000 0000 0000 0101)
Result=16385 (hint : after rotation :
0100 0000 0000 0001) Result=16385
PASS
Test for the following cases and Record the observation
3 X=8 & N=4
4 X=15 & N=3
Viva Question
1. Explain bitwise operators in C? 2. What is difference between integer and unsigned integer? 3. Explain the function without return type and return value with example? 4. What is difference between getch() and getche()? 5. What are library functions?
Exercise Problems
1. Write a c program to convert decimal number to binary number. 2. Write a c program to convert decimal number to octal number. 3. Write a program to find the 1’s complement of a number? 4. Write a program to find the 2’s complement of a number? 5. Write a program for an unsigned integer to left rotate by n position. 6. Write a program to shift right an integer by n positions.
Vijay Kumar HosaGoudar
50
Department of CSE& ISE, SLNCE raichur
10.2 To Check Prime or Not
10 ii). Design and develop a function isprime (x) that accepts an integer argument
and returns 1 if the argument is prime and 0 otherwise. The function must use plain
division checking approach to determine if a given number isprime. Invoke this function
from the main with different values obtained from the user and print appropriate messages
10.2.1 Program
#include<stdio.h> #include<conio.h> int isprime(int num) { int i; if(num==0 || num==1) { return 0; } for(i=2;i<= sqrt(num);i++) { if(num%i==0) return(0); } return(1); } int main() { int x,y,i,flag=0; clrscr(); printf("Enter a range\n"); scanf("%d%d",&x,&y); printf("The prime numbers are\n"); for(i=x;i<=y;i++) { if(isprime(i)) { printf("%d\t",i); flag=1; } } if(flag==0) { printf("There are no prime numbers between this range\n") } return 0; }
Vijay Kumar HosaGoudar
51
Department of CSE& ISE, SLNCE raichur
10.2.2 Test Cases
Test No Input Parameters Expected output Obtained output Remarks
1 Range
X=0 & Y=10 Prime numbers are
2 3 5 7 Prime numbers are
2 3 5 7 PASS
2 Range
X=5 & Y=15 Prime numbers are
5 7 11 13 Prime numbers are
5 7 11 13 PASS
3 Range
X=8 & Y=10 There are no prime
numbers There are no prime
numbers PASS
Test for the following cases and Record the observations
4 Range
X=10 & Y=30
5 Range
X=15 & Y=25
Viva Question
1. Why is the return type used? 2. What is function prototype? 3. What is the default value returned by a function? 4. Which is the even prime number?
Exercise Problem:
1. Write a program to generate a prime number between range 1 to 100.
Vijay Kumar HosaGoudar
52
Department of CSE& ISE, SLNCE raichur
11. Factorial of number using Recursive function
11. Draw the flow chart and write a Recursive C function to find the factorial of
number n! defined by fact(n)=1, if n=0, otherwise fact(n)=n*fact(n-1),using this function
write a c program to compute the binomial co-efficient nCr. Tabulate the results for
different values of n and r using suitable messages.
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); }
11.2 Test Cases:
Test No Input Parameters Expected output Obtained output Remarks
1 N=4 & R=2 4C2 = 6 4C2 = 6 PASS
2 N=5 & R=5 5C5 = 1 5C5 = 1 PASS
Test for the following cases and Records
3 N=6 & R=0
4 N=7 & R=3
5 N = 3 & R = 1
Hint: Enter N>=R.
Viva Questions
1. Define the term recursion. 2. Explain how recursive function works. 3. What are the advantages and disadvantages of recursive function. 4. Give the general syntax of a recursive function.
Vijay Kumar HosaGoudar
53
Department of CSE& ISE, SLNCE raichur
Exercise Problems
1. Write a program to find of GCD of two numbers using recursion. 2. Write a program using recursive to generate the Fibonacci series. 3. Write a program to find the sum of all numbers from 1 to N using recursive 4. Recursive solutions for Linear and Binary Search 5. Recursive solution for Binomial Coefficient
Vijay Kumar HosaGoudar
54
Department of CSE& ISE, SLNCE raichur
12. Copy the Contents Of File
12. Given two university information files "studentname.txt" and "usn.txt" that contains
students names and USN respectively. Write a C program to 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 content of output file "output.txt" on to the screen.
Student Name USN
Name1 USN1
Name2 USN2
…. …. …. ….
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);
Heading
Vijay Kumar HosaGoudar
55
Department of CSE& ISE, SLNCE raichur
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); }
12.2 Test Cases Test No Input Parameters Expected output Obtained output Remarks
1 Don’t create the studentn.txt file
Cannot open file Cannot open file and exits
PASS
2 Create a file student.txt
contains names Manoj Suresh Kiran Don’t create usn.txt
Cannot open file Cannot open file and exits
PASS
3 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. What is file? 2. File is type of ___________? Ans: Struct type 3. What is file mode ? Mention the different types of file mode ? 4. What is pointer and NULL pointer? 5. Write the syntax of fopen( ) and fclose ( )? 6. How the fgetc( ) and fputc( ) works ? 7. If there is any error while opening a file, fopen will return__________? Ans : NULL 8. EOF indicate________? Ans : End – of – file (EOF) is used to report end of file.
9. 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.
Vijay Kumar HosaGoudar
56
Department of CSE& ISE, SLNCE raichur
13. Student Recordusing Array of Structures
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"); }
Vijay Kumar HosaGoudar
57
Department of CSE& ISE, SLNCE raichur
13.2 TestCases
Test
No
Input Parameters Expected
output
Obtained
output
Rem
arks
1 N=3, Enter the student details of 3 student
Roll no Name Marks Grade
S[0]. 100 Divya 90 A
S[1]. 200 Pavithra 80 B
S[2] 300 Tanisha 60 C
Enter name = Divya to print the marks
Divya Marks=
90
Divya Marks= 90
PASS
2 N=2, Enter the student details of 3 student
Roll no Name Marks Grade
S[0]. 100 Krish 75 A
S[1]. 200 Krish 80 B
Enter name = krish to print the marks
Krish Marks=
75
80
Krish Marks=
75
80
PASS
3 N=3, Enter the student details of 3 student
Roll no Name Marks Grade
S[0]. 100 Divya 90 A
S[1]. 200 Pavithra 80 B
S[2] 300 Tanisha 60 C
Enter name = pallavi to print the marks
Given student
name not found
Given student
name not found
PASS
Test the following cases and records 4
N=0,
5 N=5
Viva Questions:
1. What is a structure?
2. Give the difference between an array and a structure?
3. Does the definition of a structure create memory space?
4. How are individual elements of a structure accessed?
5. What is an enumerated data?
6. What is union?
7. What are the difference between structure and union?
8. What is the use of fflush( ).
9. 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).
Vijay Kumar HosaGoudar
58
Department of CSE& ISE, SLNCE raichur
14. Use of Pointers
14. Write a C program using pointers to compute the sum, mean and standard
deviation of all elements stored in an array of n real numbers.
Mean :is the average of the numbers. i.ethe sum of a collection of numbers divided by the
number of numbers in the collection
Standard deviation(SD) : measures the amount of variation ordispersionfrom the
average. For a finite set of numbers, the standard deviation is found by taking thesquare
rootof theaverageof the squared differences of the values from their average value.
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); }
Vijay Kumar HosaGoudar
59
Department of CSE& ISE, SLNCE raichur
14.2 Test Cases
Test
No Input Parameters Expected output Obtained output Remarks
1 N=8
Array elements 2 4 4 4 5 5 7 9
Sum=40 Mean=5 Standard
deviation=2
Sum=40 Mean=5 Standard
deviation=2
PASS
2 N=4
Array elements 1 2 3 4
Sum=10 Mean=2.5 Standard
deviation=0.790569
Sum=10 Mean=2.5 Standard
deviation=0.790569
PASS
Test for the following cases and Records
3 N=5
Array elements 2 3 4 8 10
4 N=6
Array elements 1 3 5 7 9 11
Viva Question :
1. Define pointer?
2. What does * and & operator indicate with respect to pointer.
3. What are the advantages of using pointer.
4. How is a pointer variable declared?
5. 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
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.
Vijay Kumar HosaGoudar
60
Department of CSE& ISE, SLNCE raichur
APPENDIX - A
General Viva & Exercise Problems
Viva and Exercise problems on Basic concepts of C program
1. Define preprocessor directives.
2. What is the syntax for preprocessor directive?
3. What are header files?
4. What does include stands for?
5. Give some examples of built-in functions stored in math.h ,conoi.h ,stdio.h,string.h.
6. What type of a function is main()?
7. What are variables?
8. Name the basic data type available in C.
9. 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?
Vijay Kumar HosaGoudar
61
Department of CSE& ISE, SLNCE raichur
35. How characters are stored in memory?
36. How many bits is equal to 1 byte?
37. Half byte is known as _______.
38. What is a compiler?
39. What is an assembler?
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.
Viva and Exercise problems on Operators
1. What is an operator?
2. Name the different types of operators in C.
3. What is associativity?
4. Arithmetic operators are left to right associative.(True / false)
5. How multiple assignments are done? Is it left to right or right to left associative?
6. Name relational operators? It is also known as ______.
7. What are unary operators?
8. Give some examples for unary operators.
9. What is an address operator?
10. Give the syntax for ternary operator.
11. What type of operator is increment operator?
12. Which operator is used to know the size of all data type?
13. Name logical operator. Why is it used?
14. Which operator has highest precedence among logical operators?
15. What type of operators are >> and <<?
16. Is there any rotate operator in C?
17. = is an example of -------------------------- operator.
18. A=b. Explain this?
19. What is declaration?
20. Give an example of initialization of variable. How it works?
21. What are local variables?
22. What are global variables?
23. What is the significance of giving semicolon at the end of every statement?
24. What are backslash constants?
25. What does this indicates \a and \t?
Vijay Kumar HosaGoudar
62
Department of CSE& ISE, SLNCE raichur
26. Differentiate implicit and explicit type conversion.
27. Explicit type conversion is known as___________.
28. Both the variables should be of same data type in implicit type
conversion(True/false)?
29. Explain explicit conversion with syntax.
30. What is the output of following code?
void main ()
{
int a=6, c;
float b=9.0;
c=a/b;
printf(“%d”,c);
}
31. What is the output of the following code?
void main ()
{
int a=10,b=5;
float c;
c = (float) a/b;
printf(“%f”,c);
}
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.
Vijay Kumar HosaGoudar
63
Department of CSE& ISE, SLNCE raichur
Viva and Exercise problems on Branching and Looping
1. Name conditional branching statements.
2. Write the syntax for if.
3. Name two way decision statement.
4. What is meant by dangling if?
5. Give examples for multiway decision statements.
6. Write the syntax for switch case and else if ladder.
7. Name the different instance where switch case and else if ladder is used.
8. What is the difference between multiple if and else if ladder?
9. What is default? What is the significance of using it in switch case?
10. Can we use continue in switch case?
11. Can the case value be float in switch case?
12. Explain unconditional branching statement.
13. What is the output of the above code? for(i=0;i<5;i++) for(i=0;i<5;i++) { { if(i==3) continue; if(i==3)break; printf(“%d”,i); printf(“%d”,i); } }
14. What is break?
15. Explain the syntax for goto? Why it is not recommended in C?
16. How many times conditional branching statements will work?
17. What are loops?
18. Differentiate event controlled and counter controlled loop.
19. Explain the syntax of while and do-while loop.
20. The minimum times do-while loop will work-------------.
21. While loop is also known as _________.
22. Why do-while loop is also known as exit-controlled loop? Justify.
23. How many times the loop will work?
24. Explain the syntax of for loop.
25. Explain nested for loop.
26. Write the code to print the following code.
*
* *
* * *
27. Write for loop in terms of while loop.
28. What type of loop is this.
for (; ;)
29. Give a real time example where nested for loop is used.
30. pow() is defined in which header file?
31. Which is the preferable loop to find gcd of a number?
32. What is the advantage of using Horner’s method over simple method?
33. Name the different instances where break statement is used.
Vijay Kumar HosaGoudar
64
Department of CSE& ISE, SLNCE raichur
Exercise
1. Write a program to check whether a person is eligible to vote using if construct.
2. Write a program to check whether a number is even using if construct.
3. Write a program to check whether a student has secured distinction using if construct.
4. 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
Vijay Kumar HosaGoudar
65
Department of CSE& ISE, SLNCE raichur
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 of unconditional branching
statements(break,continue and goto).
Viva and Exercise problems on Arrays and Strings
1. What is an array?
2. Name the different types of arrays.
3. Can we store name usn and marks of a student in the single array?
4. The name of an array holds what?
5. Give the syntax for declaring 1D array.
6. What are the different ways of 1D array initialization?
7. The integer value associated with the array names indicates what?
8. What does the subscript of the array indicates?
9. How do we access the value stored in array?
10. Can we declare a 2D array without size? Justify.
11. Explain the working of linear search.
12. Name the different sorting techniques.
13. How binary search is more efficient than linear search?
14. What is a string?
15. In which header file all the string built-in function are stored?
16. Why address operator is not used while reading a string?
17. Generally gets() is used to read a string instead of scanf(). Why?
18. Give the syntax and explain the following built-in functions.
a. strlen() b. strrev( ) c. strcpy( ) d. strcat( ) e. strstr( ) f. strcmp()
19. On which basis string comparison is done using the function strcmp( )?
20. How many arguments does the function strcat( ) takes?
21. What does ‘\0’ represents?
22. What is the size of 0 and \0?
23. What is a null character?
24. Differentiate character constant and string constant?
25. How do you represent string constant?
Exercise
1. Write a program to read and display the elements of 1D array.
2. Write a program to find the sum and average of all elements of 1D array
3. Write a program to find the largest of array element.
4. Write a program to perform two 1D array addition.
5. Write a program to perform binary search on array elements.
6. Write a program to read and display the elements of 2D array.
7. Write a program to find the sum and average of all elements of 2D array.
8. Write a program to perform two 2D array addition.
Vijay Kumar HosaGoudar
66
Department of CSE& ISE, SLNCE raichur
9. Write a program to find transpose of a matrix.
10. Write a program to fill upper triangular and lower triangular matrix with 0 and
diagonal elements with 1.
11. Write a program to find norm of a matrix.
12. Write a program to perform linear search.
13. Write a program to print Fibonacci series up to N.
14. Write a program to read a string and display it.
15. Write a program to find the length of a string using and without using built-in
function.
16. Write a program to concatenate the string using and without using built-in function.
17. Write a program to reverse a string using and without using built-in function.
18. Write a program to compare the string using and without using built-in function.
19. Write a program to find the occurrence of a character in a string using and without
using built-in function.
20. Write a program to reverse a string and check whether it is palindrome or not.
Viva and Exercise problems on Functions
1. Define function.
2. What is user defined function and what is the need of it?
3. Name the three elements of user defined function.
4. Write the syntax for function declaration and function call.
5. What does return type in function declaration indicate?
6. What are actual and formal parameters?
7. How do we declare formal parameters?
8. Is it necessary to mention the name of variable in the function declaration(True /
False)?
9. What is a function call?
10. What type of a function is main()?
11. Write the syntax for actual parameters.
12. What are three aspects actual parameters and formal parameters should match?
13. Explain function definition.
14. How many return statements can be coded in a program?
15. What is the syntax of return statement?
16. What are the two ways of parameter passing technique?
Exercise
1. Write a program to perform addition of two numbers using function.
2. Write a program to find factorial of a number using function.
3. Write a program to swap two integers using function.
4. Write a program to find area of a circle using function.
5. Write a program to find Fibonacci of a number using function.
6. Write a program to check whether any character from string 2 is present in string 1
without using built-in function.
Viva and Exercise problems on Pointers and Recursion
Vijay Kumar HosaGoudar
67
Department of CSE& ISE, SLNCE raichur
1. What is a pointer?
2. How to declare a pointer?
3. What does a pointer hold?
4. What is a null pointer?
5. In pass by address, the formal parameters should be declared as ____________.
6. * is also known as__________ operator.
7. Can we have pointer to pointer?
8. Differentiate a normal variable and a pointer.
9. 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.
Exercise
1. Write a program to find factorial of a number using recursion.
2. Write a program to demonstrate tower of Hanoi using recursion.
3. Write a program to declare and initialize the pointers.
4. Write a program to illustrate pointer to pointer concept.
5. Write a program to illustrate array of pointers.
Viva and Exercise problems on Data Structures
1. What are the two operations implemented on stack?
2. What is data structure?
3. What type of data structure a stack is?
4. What is queue?
5. List the operations on queue.
6. What is importance of the top in the stack?
7. How many ends queue consist of?
8. Give an example of first in first out data structure.
9. What is a queue?
Vijay Kumar HosaGoudar
68
Department of CSE& ISE, SLNCE raichur
Exercise
1. Write a program to create stack using arrays.
2. Write a program to create queue using arrays.
Viva and Exercise problems on structures and unions
1. What is a structure?
2. Name the derived data types.
3. Can we store more than one data type in structure?
4. What is advantage of using structure over an array?
5. Give the syntax of structure.
6. How the structure elements are accessed?
7. When the memory is allocated to structure?
8. What is union?
9. What is the total memory allocated for union?
10. Can we copy two structures of same type?
11. Are logical operations allowed on structures?
Exercise
1. Write a program to create structures.
2. Write a program to implement array of structures.
3. Write a program to implement pointer to array of structures.
Vijay Kumar HosaGoudar
69
Department of CSE& ISE, SLNCE raichur
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.
Turbo C Editor to type the program:
Vijay Kumar HosaGoudar
70
Department of CSE& ISE, SLNCE raichur
Type the C program
Click File-> Save as to save the C program or Press F2
Save with appropriate File name with .c extension and press ok
Click Compile -> Compile (This is option within compile menu) to compile C program or
press alt+F9:
Vijay Kumar HosaGoudar
71
Department of CSE& ISE, SLNCE raichur
Compilation process:
Click Run -> Run (This the option within the run menu) or Press ctrl+F9to execute the C
program:
Vijay Kumar HosaGoudar
72
Department of CSE& ISE, SLNCE raichur
Press Alt+F5to see the output screen
Vijay Kumar HosaGoudar
73
Department of CSE& ISE, SLNCE raichur
Screenshots of C Program Execution’ in Linux Operating System:
Click Applications -> System Tools -> Terminal on desktop to open terminal shown
below:
Enter vi command in following format: vi Hello.c where Hello is file name and it is
programmer’s choice.
Now, editor is opened. Press ’i’ key or ’insert’ key to change editor to insert mode, where
we can type the program.
Vijay Kumar HosaGoudar
74
Department of CSE& ISE, SLNCE raichur
Now, press ESC : wq in editor to come back to terminal.
:w is to save the program. q is to quit the editor.
Type cc command following program name to compile the program.
Ex: cc Hello.c
After compilation, run the program using ./a.out command to see the output.
Vijay Kumar HosaGoudar
Top Related