You are on page 1of 92

COMPUTER PROGRAMMING LABORATORY

SYLLABUS : Laboratory Experiments

Implement the following programs with WINDOWS / LINUX platform using appropriate
C compiler.

1. Design and develop a flowchart or an algorithm that takes three coefficients (a, b, and c) of a
Quadratic equation (ax2+bx+c=0) as input and compute all possible roots. Implement a C
program for the developed flowchart/algorithm and execute the same to output the possible
roots for a given set of coefficients with appropriate messages.

2. Design and develop an algorithm to find the reverse of an integer number NUM and check
whether it is PALINDROME or NOT. Implement a C program for the developed algorithm
that takes an integer number as input and output the reverse of the same with suitable
messages. Ex: Num: 2014, Reverse: 4102, Not a Palindrome

3. a) Design and develop a flowchart to find the square root of a given number N. Implement a
C program for the same and execute for all possible inputs with appropriate messages. Note:
Dont use library function sqrt(n).

b) 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 to evaluate polynomial f(x) = a4x4 + a3x3 + a2x2 + a1x + a0,
for a given value of x and its coefficients using Horners method. Implement a C program for
the same and execute the program with different set of values of coefficients and x.

5. Draw the flowchart and Write a C Program to compute Sin(x) using Taylor series
approximation given by Sin(x) = x - (x3/3!) + (x5/5!)- (x7/7!) + . Compare your result
with the built- in Library function. Print both the results with appropriate messages.

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 product of matrices A and B. Read matrix A and matrix B in row major order
and in column major order respectively. Print both the input matrices and resultant matrix
with suitable headings and output should be in matrix format only. Program must check the
compatibility of orders of the matrices for multiplication. Report appropriate message in case
of incompatibility.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 1


COMPUTER PROGRAMMING LABORATORY

8. Develop, implement and execute a C program to search a Name in a list of names 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. Read a sentence and print frequency of vowels and total count of consonants.

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

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

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 nCr. 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 contains students
Name 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
shown below. Display the contents of output file output.txt on to the screen.
Student Name USN
Name 1 USN1
Name 2 USN2
. .
. .

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). Assume appropriate data type for each
field. Print the marks of the student, given the student name as input.

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.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 2


COMPUTER PROGRAMMING LABORATORY

Functional Block Diagram of a Computer


A block diagram is a visual representation of how parts of an object relate to each other and
work together. It is named as such because blocks are used to represent each piece of the design,
with lines between them to show their respective relationships.

Used in the design of hardware and software, a block diagram helps to provide someone with a
high-level idea of how it can work. Being a high-level diagram, minimal details are included and
only the primary and most important components of the hardware or software are illustrated;
much like an outline.

A computer can process data, pictures, sound and graphics. They can solve highly complicated
problems quickly and accurately. A computer as shown in Fig. performs basically five major
computer operations or functions irrespective of their size and make. These are

1) it accepts data or instructions by way of input,

2) it stores data,

3) it can process data as required by the user,

4) it gives results in the form of output, and

5) it controls all operations inside a computer.

We discuss below each of these Computer operations

1. Input: This is the process of entering data and programs in to the computer system. You
should know that computer is an electronic machine like any other machine which takes as
inputs raw data and performs some processing giving out processed data. Therefore, the input
unit takes data from us to the computer in an organized manner for processing.

2. Storage: The process of saving data and instructions permanently is known as storage. Data
has to be fed into the system before the actual processing starts. It is because the processing
speed of Central Processing Unit (CPU) is so fast that the data has to be provided to CPU
with the same speed. Therefore the data is first stored in the storage unit for faster access and
processing. This storage unit or the primary storage of the computer system is designed to do
the above functionality. It provides space for storing data and instructions.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 3


COMPUTER PROGRAMMING LABORATORY

The storage unit performs the following major functions:

All data and instructions are stored here before and after processing.

Intermediate results of processing are also stored here.

3. Processing: The task of performing operations like arithmetic and logical operations is called
processing. The Central Processing Unit (CPU) takes data and instructions from the storage
unit and makes all sorts of calculations based on the instructions given and the type of data
provided. It is then sent back to the storage unit.

4. Output: This is the process of producing results from the data for getting useful information.
Similarly the output produced by the computer after processing must also be kept somewhere
inside the computer before being given to you in human readable form. Again the output is
also stored inside the computer for further processing.

5. Control: The manner how instructions are executed and the above operations are performed.
Controlling of all operations like input, processing and output are performed by control unit.
It takes care of step by step processing of all operations inside the computer.

Functional Units
In order to carry out the operations mentioned in the previous section the computer allocates the
task between its various functional units. The computer system is divided into three separate
units for its operation. They are

1) arithmetic logical unit

2) control unit.

3) central processing unit.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 4


COMPUTER PROGRAMMING LABORATORY

Arithmetic Logical Unit (ALU) Logical Unit

Logical Unit :After you enter data through the input device it is stored in the primary storage
unit. The actual processing of the data and instruction are performed by Arithmetic Logical Unit.
The major operations performed by the ALU are addition, subtraction, multiplication, division,
logic and comparison. Data is transferred to ALU from storage unit when required. After
processing the output is returned back to storage unit for further processing or getting stored.

Control Unit (CU)


The next component of computer is the Control Unit, which acts like the supervisor seeing that
things are done in proper fashion. Control Unit is responsible for co ordinating various
operations using time signal. The control unit determines the sequence in which computer
programs and instructions are executed. Things like processing of programs stored in the main
memory, interpretation of the instructions and issuing of signals for other units of the computer
to execute them. It also acts as a switch board operator when several users access the computer
simultaneously. Thereby it coordinates the activities of computers peripheral equipment as they
perform the input and output.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 5


COMPUTER PROGRAMMING LABORATORY

Central Processing Unit (CPU)


The ALU and the CU of a computer system are jointly known as the central processing unit. You
may call CPU as the brain of any computer system. It is just like brain that takes all major
decisions, makes all sorts of calculations and directs different parts of the computer functions by
activating and controlling the operations.

Bus
When referring to a computer,
the bus also known as the
address bus, data bus, or
local bus is a data connection
between two or more devices
connected to the computer. For
example, a bus enables a
computer processor to
communicate with the
memory or a video card to
communicate with the
memory.

The bus contains multiple wires (signal lines) that contain addressing information that describes
the memory location of where the data is being sent or where it is being retrieved. Each wire in
the bus carries a single bit of information, which means the more wires a bus has the more
information it can address. For example, a computer with a 32-bit address bus can address 4GB
of memory, and a computer with a 36-bit bus can address 64GB of memory.

A bus is capable of being a parallel or serial bus and today all computers utilize two bus types, an
internal bus or local bus and an external bus, also called the expansion bus. An internal bus
enables communication between internal components such as a video card and memory. An
external bus is capable of communicating with external components such as a USB or SCSI
device.

A computer or device's bus speed is listed as a MHz, e.g. 100MHz FSB. The throughput of a bus
is measured in bits per second or megabytes per second.

Most popular computer bus

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 6


COMPUTER PROGRAMMING LABORATORY

Today, many of the buses listed above are no longer used or are not as common. Below is a
listing of the most buses and how they are used with a computer.

eSATA and SATA - Computer hard drives and disc drives.

PCIe - Computer expansion cards and video cards.

USB - Computer peripherals.

Motherboard
Alternatively referred to as the mb, mainboard, mboard, mobo, mobd, backplane board, base
board, main circuit board, planar board, system board, or a logic board on Apple computers.
The motherboard is a printed circuit board that is the foundation of a computer, located on the
back side or at the bottom of the computer chassis. It allocates power and allows communication
to the CPU, RAM, and all other computer hardware components.

Motherboard overview
Below is a picture of the ASUS P5AD2-E motherboard with names of each major component of
the motherboard. Clicking on the image below gives you a larger more detailed version of the
picture below.

Motherboard components
Below mentioned are the motherboard components.

Expansion slots (PCI Express, PCI, and AGP)

3-pin case fan connectors

Back pane connectors

Heat sink

4-Pin (P4) power connector

Inductor

Capacitor

CPU Socket

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 7


COMPUTER PROGRAMMING LABORATORY

Northbridge

Screw hole

Memory slot

Super I/O

Floppy connection

ATA (IDE) disk drive primary connection

24-pin ATX power Supply connector

Serial ATA connections

Coin cell battery (CMOS backup battery)

RAID

System panel connectors

FWH

Southbridge

Serial port connector

USB headers

Jumpers

Integrated circuit

1394 headers

SPDIF

CD-IN

Motherboard form factors

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 8


COMPUTER PROGRAMMING LABORATORY

When referring to computer hardware, a form factor is a specification of its layout and physical
dimensions. Form factors help prevent incompatibilities between multiple hardware
manufacturers.

As computers advanced, so have motherboards. Below is a listing of the various motherboard


form factors and additional information about each of these form factors including ATX, the
most commonly used motherboard form factor today.

AT
ATX
Baby AT
BTX
DTX
LPX
Full AT
Full ATX
microATX
NLX

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 9


COMPUTER PROGRAMMING LABORATORY

How
many

connections, ports, or slots are on a motherboard?


There is no set standard to how many connections, ports, or expansion slots are on a
motherboard. The best method of determining how many connections, ports, or slots are
available for your computer or motherboard is to look up the specifications for your motherboard
in its documentation.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 10


COMPUTER PROGRAMMING LABORATORY

How does a motherboard connect to a computer case?


A computer motherboard connects to a desktop computer case using standouts and once attached
to the case all other devices connect to it or an inserted expansion card.

What was the first motherboard?


The first motherboard is considered to be one used in the IBM Personal Computer, released in
1981. At the time, IBM referred to it as a "planar" instead of a motherboard. The IBM Personal
Computer and the motherboard inside it would set the standard for IBM-compatible computer
hardware going forward.

Since there is a motherboard, is there a fatherboard?


No, there is no such thing as a fatherboard when talking about a computer. However, there is
such a thing as a daughterboard.

Daughterboard
Alternatively referred to as a piggyback board and daughter card, a daughterboard is an
expansion board that connects directly to the motherboard and gives added functionality (e.g.
modem). Today, these boards are not found or used in desktop computers and have been replaced
with ISA cards, PCI cards, and onboard. However, some laptops still use these boards.

Chipsets

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 11


COMPUTER PROGRAMMING LABORATORY

Chipset
A chipset is a group of microchips that are
designed to work with one or more related
functions that were first introduced in 1986
when Chips and Technologies introduced the
82C206. The original 82C206 chipset included
the 82284 Clock Generator functions, 82288 Bus
Controller, 8254 System Timer, dual 8259
Interrupt Controllers, dual 8237 DMA
controllers, and the MC146818 Clock. Four of
the 82C206 chips were later replaced by CS8221
or NEAT (New Enhanced AT) chipset that
contained only three chips. This was then
replaced by the 82C836 SCAT (Single Chip AT)
chipset that combined all the chips in the set into a single chip.

Examples of chipset manufacturers include ALi, AMD, Intel, NVidia, SiS, and VIA. These
chipsets can include instructions that help control the CPU, PCI, ISA, or USB hardware. They
are often divided into a multitiered architecture referred to as North bridge and South bridge, as
well as a Super I/O chip. An example of a recent Intel chipset is the i820 or the Intel 820 chipset.

Chipset drivers
After reinstalling Microsoft Windows or another operating system, it may be necessary to install
your motherboard chipset drivers for all components to work properly. These drivers are
included on your motherboard driver CD or can also be downloaded from the motherboard or
computer manufacturer.

Operating systems
Operating system

An operating system (OS) is system software that manages computer hardware and software
resources and provides common services for computer programs. All computer programs,
excluding firmware, require an operating system to function.

Time-sharing operating systems schedule tasks for efficient use of the system and may also
include accounting software for cost allocation of processor time, mass storage, printing, and
other resources.

For hardware functions such as input and output and memory allocation, the operating system
acts as an intermediary between programs and the computer hardware, although the application

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 12


COMPUTER PROGRAMMING LABORATORY

code is usually executed directly by the hardware and frequently makes system calls to an OS
function or is interrupted by it. Operating systems are
found on many devices that contain a computer
from cellular phones and video game consoles to web
servers and supercomputers.

The dominant desktop operating system is Microsoft


Windows with a market share of around 82%. OS X
by Apple Inc. is in second place (9.8%), and Linux is
in third position (1.5%). In the mobile (smartphone
and tablet combined) sector Android by Google is
dominant with 65% and iOS by Apple is placed
second with around 25%. Linux is dominant in the
server and supercomputing sectors. Other specialized
classes of operating systems, such as embedded and
real-time systems, exist for many applications.

Types of operating systems


Single and multi-tasking
A single-tasking system can only run one program at a time, while a multi-tasking operating
system allows more than one program to be running in concurrency. This is achieved by time-
sharing, dividing the available processor time between multiple processes that are each
interrupted repeatedly in time slices by a task-scheduling subsystem of the operating system.
Multi-tasking may be characterized in preemptive and co-operative types. In preemptive
multitasking, the operating system slices the CPU time and dedicates a slot to each of the
programs. Unix-like operating systems, e.g., Solaris, Linux, as well as AmigaOS support
preemptive multitasking. Cooperative multitasking is achieved by relying on each process to
provide time to the other processes in a defined manner. 16-bit versions of Microsoft Windows
used cooperative multi-tasking. 32-bit versions of both Windows NT and Win9x, used
preemptive multi-tasking.

Single and multi-user


Single-user operating systems have no facilities to distinguish users, but may allow multiple
programs to run in tandem. A multi-user operating system extends the basic concept of multi-
tasking with facilities that identify processes and resources, such as disk space, belonging to
multiple users, and the system permits multiple users to interact with the system at the same
time. Time-sharing operating systems schedule tasks for efficient use of the system and may also
include accounting software for cost allocation of processor time, mass storage, printing, and
other resources to multiple users.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 13


COMPUTER PROGRAMMING LABORATORY

Distributed
A distributed operating system manages a group of distinct computers and makes them appear to
be a single computer. The development of networked computers that could be linked and
communicate with each other gave rise to distributed computing. Distributed computations are
carried out on more than one machine. When computers in a group work in cooperation, they
form a distributed system.

Templated
In an OS, distributed and cloud computing context, templating refers to creating a single virtual
machine image as a guest operating system, then saving it as a tool for multiple running virtual
machines. The technique is used both in virtualization and cloud computing management, and is
common in large server warehouses.

Embedded
Embedded operating systems are designed to be used in embedded computer systems. They are
designed to operate on small machines like PDAs with less autonomy. They are able to operate
with a limited number of resources. They are very compact and extremely efficient by design.
Windows CE and Minix 3 are some examples of embedded operating systems.

Real-time
A real-time operating system is an operating system that guarantees to process events or data by
a specific moment in time. A real-time operating system may be single- or multi-tasking, but
when multitasking, it uses specialized scheduling algorithms so that a deterministic nature of
behavior is achieved. An event-driven system switches between tasks based on their priorities or
external events while time-sharing operating systems switch tasks based on clock interrupts

Library
A library operating system is one in which the services that a typical operating system provides,
such as networking, are provided in the form of libraries. These libraries are composed with the
application and configuration code to construct unikernels which are specialized, single
address space, machine images that can be deployed to cloud or embedded environments.

Networking Basics

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 14


COMPUTER PROGRAMMING LABORATORY

A typical network consists of:

nodes (computers)

a connecting medium (wired or wireless)

specialized network equipment like routers or hubs.

In the case of the Internet, all of these pieces work together to allow your computer to send
information to another computer that could be on the other side of the world!

Switches are another fundamental part of many networks because they speed things up. Switches
allow different nodes (a network connection point, typically a computer) of a network to
communicate directly with one another in a smooth and efficient manner.

There are many different types of switches and networks. Switches that provide a separate
connection for each node in a company's internal network are called LAN switches. Essentially,
a LAN switch creates a series of instant networks that contain only the two devices
communicating with each other at that particular moment. In this article, we will focus on
Ethernet networks that use LAN switches. You will learn what a LAN switch is and how
transparent bridging works, as well as about VLANs, trunking and spanning trees.

Here are some of the fundamental parts of a network:

Network - A network is a group of computers connected together in a way that allows


information to be exchanged between the computers.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 15


COMPUTER PROGRAMMING LABORATORY

Node - A node is anything that is connected to the network. While a node is typically a
computer, it can also be something like a printer or CD-ROM tower.

Segment - A segment is any portion of a network that is separated, by a switch, bridge or


router, from other parts of the network.

Backbone - The backbone is the main cabling of a network that all of the segments
connect to. Typically, the backbone is capable of carrying more information than the
individual segments. For example, each segment may have a transfer rate of 10 Mbps
(megabits per second), while the backbone may operate at 100 Mbps.

Topology - Topology is the way that each node is physically connected to the network
(more on this in the next section).

Local Area Network (LAN) - A LAN is a network of computers that are in the same
general physical location, usually within a building or a campus. If the computers are far
apart (such as across town or in different cities), then a Wide Area Network (WAN) is
typically used.

Network Interface Card (NIC) - Every computer (and most other devices) is connected
to a network through an NIC. In most desktop computers, this is an Ethernet card
(normally 10 or 100 Mbps) that is plugged into a slot on the computer's motherboard.

Media Access Control (MAC) address - This is the physical address of any device --
such as the NIC in a computer -- on the network. The MAC address, which is made up of
two equal parts, is 6 bytes long. The first 3 bytes identify the company that made the
NIC. The second 3 bytes are the serial number of the NIC itself.

Unicast - A unicast is a transmission from one node addressed specifically to another


node.

Multicast - In a multicast, a node sends a packet addressed to a special group address.


Devices that are interested in this group register to receive packets addressed to the
group. An example might be a Cisco router sending out an update to all of the other Cisco
routers.

Broadcast - In a broadcast, a node sends out a packet that is intended for transmission to
all other nodes on the network.

Network Topologies

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 16


COMPUTER PROGRAMMING LABORATORY

Bus network topology

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 17


COMPUTER PROGRAMMING LABORATORY

Star network topology A typical star bus network

Some of the most common topologies in use today include:

Bus - Each node is daisy-chained (connected one right after the other) along the same
backbone, similar to Christmas lights. Information sent from a node travels along the
backbone until it reaches its destination node. Each end of a bus network must be terminated
with a resistor to keep the signal that is sent by a node across the network from bouncing
back when it reaches the end of the cable.

Ring - Like a bus network, rings have the nodes daisy-chained. The difference is that the end
of the network comes back around to the first node, creating a complete circuit. In a ring
network, each node takes a turn sending and receiving information through the use of a
token. The token, along with any data, is sent from the first node to the second node, which
extracts the data addressed to it and adds any data it wishes to send. Then, the second node
passes the token and data to the third node, and so on until it comes back around to the first
node again. Only the node with the token is allowed to send data. All other nodes must wait
for the token to come to them.

Star - In a star network, each node is connected to a central device called a hub. The hub
takes a signal that comes from any node and passes it along to all the other nodes in the
network. A hub does not perform any type of filtering or routing of the data. It is simply a
junction that joins all the different nodes together.

Star bus - Probably the most common network topology in use today, star bus combines
elements of the star and bus topologies to create a versatile network environment. Nodes in
particular areas are connected to hubs (creating stars), and the hubs are connected together
along the network backbone (like a bus network). Quite often, stars are nested within stars, as
seen in the example below:

Network interface controller (NIC)

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 18


COMPUTER PROGRAMMING LABORATORY

A network interface controller (NIC, also


known as a network interface card, network
adapter, LAN adapter or physical network
interface, and by similar terms) is a computer
hardware component that connects a computer
to a computer network.

Early network interface controllers were


commonly implemented on expansion cards
that plugged into a computer bus. The low
cost and ubiquity of the Ethernet standard
means that most newer computers have a
network interface built into the motherboard.

Modern network interface controllers offer


advanced features such as interrupt and DMA
interfaces to the host processors, support for
multiple receive and transmit queues,
partitioning into multiple logical interfaces,
and on-controller network traffic processing such as the TCP offload engine.

The network controller implements the electronic circuitry required to communicate using a
specific physical layer and data link layer standard such as Ethernet, Fibre Channel, Wi-Fi or
Token Ring. This provides a base for a full network protocol stack, allowing communication
among small groups of computers on the same local area network (LAN) and large-scale
network communications through routable protocols, such as Internet Protocol (IP).

The NIC allows computers to communicate


over a computer network, either by using
cables or wirelessly. The NIC is both a
physical layer and data link layer device, as it
provides physical access to a networking
medium and, for IEEE 802 and similar
networks, provides a low-level addressing
system through the use of MAC addresses that
are uniquely assigned to network interfaces.

Although other network technologies exist, IEEE 802 networks including the Ethernet variants
have achieved near-ubiquity since the mid-1990s.

RAM (random access memory)

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 19


COMPUTER PROGRAMMING LABORATORY

RAM (random access memory) is the place in a computing device where the operating system
(OS), application programs and data in current use are kept so they can be quickly reached by the
device's processor. RAM is much faster to read from and write to than other kinds of storage in a
computer, such as a hard disk drive (HDD), solid-state drive (SSD) or optical drive. Data
remains in RAM as long as the computer is running. When the computer is turned off, RAM
loses its data. When the computer is turned on again, the OS and other files are once again
loaded into RAM, usually from an HDD or SSD.

You can compare RAM to a person's short-term memory and a hard disk to long-term memory.
Short-term memory focuses on the work at hand, but can only keep so many facts in view at one
time. If short-term memory fills up, your brain is sometimes able to refresh it from facts stored in
long-term memory. A computer also works this way. If RAM fills up, the processor needs to
continually go to the hard disk to overlay old data in RAM with new, slowing the computer's
operation. Unlike a hard disk, which can become completely full of data and unable to accept
any more, RAM never runs out of memory, but the combination of RAM and storage memory
can be completely used up.

DRAM vs. SRAM


RAM comes in two primary forms:

Dynamic random access memory. DRAM is what makes up the typical computing device
RAM and, as noted above, requires constant power to hold on to stored data.

Static random access memory. SRAM doesn't need constant power to hold on to data, but the
way the memory chips are made means they are much larger and thousands of times more
expensive than an equivalent amount of DRAM. However, SRAM is significantly faster than
DRAM. The price and speed differences mean SRAM is mainly used in small amounts as cache
memory inside a device's processor.

History of RAM
RAM is called random access because any storage location -- also known as a memory address -
can be accessed directly. Originally, the term distinguished regular core memory from offline
memory, usually on magnetic tape in which an item of data could only be accessed by starting
from the beginning of the tape and finding an address sequentially. RAM is organized and
controlled in a way that enables data to be stored and retrieved directly to specific locations.
Note that other forms of storage -- such as the hard disk and CD-ROM -- are also accessed
directly or randomly, but the term random access is not applied to these forms of storage.

RAM started out as asynchronous, or having a different clock speed for the microchips in the
RAM than the processor. This was a problem as processors became more powerful and RAM
couldn't keep up with requests for data from the processor. In the early 1990s, clock speeds were

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 20


COMPUTER PROGRAMMING LABORATORY

synchronized with the introduction of synchronous dynamic random access memory. SDRAM
reached its limit quickly, since it transferred data in a single data rate. Around the year 2000,
double data rate random access memory (DDR RAM) was developed. This moved data twice in
a single clock cycle -- at the start and end. The introduction of DDR RAM also seems to have
changed the definition of SDRAM, as many sources now define it as single data rate RAM.

DDR RAM has evolved three times, through DDR2, DDR3 and DDR4. Each iteration improved
data throughput speeds and reduced power use. However, each version is not compatible with the
previous ones, as data is handled in larger batches in each innovation.\

How big is RAM?


RAM is small, both in physical size - it's stored in microchips -- and in the amount of data it can
hold. A typical laptop computer may come with 4 gigabytes of RAM, while a hard disk can hold
10 terabytes.

RAM comes in the form of discrete or separate microchips, and in modules that plug into slots in
the computer's motherboard. These slots connect through a bus or set of electrical paths to the
processor. The HDD, on the other hand, stores data on a magnetized surface that looks like a
phonograph record, while the SSD stores data in memory chips that, unlike RAM, are not
dependent on having power all the time and won't lose data once the power is turned off.

Most PCs allow users to increase the number of RAM modules to a certain limit. Having more
RAM in your computer reduces the number of times the processor has to read data from the hard
disk, an operation that takes much longer than reading data from RAM. RAM access time is in
nanoseconds, while storage memory access time is in milliseconds.

SDRAM (synchronous DRAM)

SDRAM (synchronous DRAM) is a generic name for various kinds of dynamic random access
memory (DRAM) that are synchronized with the clock speed that the microprocessor is
optimized for. This tends to increase the number of instructions that the processor can perform in
a given time. The speed of SDRAM is rated in MHz rather than in nanoseconds (ns). This makes
it easier to compare the bus speed and the RAM chip speed. You can convert the RAM clock
speed to nanoseconds by dividing the chip speed into 1 billion ns (which is one second). For
example, an 83 MHz RAM would be equivalent to 12 ns.

Computer memory: DRAM types

Type of DRAM on the module can greatly affect performance and cause the most confusion
when designing or configuring a system.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 21


COMPUTER PROGRAMMING LABORATORY

FPM (fast page mode DRAM). Introduced in 1987, this is an early form of DRAM that
was once very common because it was slightly faster than DRAM. This computer
memory type was frequently mounted on a SIMM in 486 and early Pentium computers.

EDO (extended data output). EDO offers a slight performance boost over FPM DRAM
by cutting a few steps when addressing memory. Introduced in 1995, EDO requires a
specific chip set and is limited to bus speeds of 66 MHz. Once again, these chips are
mounted on SIMM modules.

BEDO (burst EDO RAM). This is a slightly faster variant of the EDO RAM chip in
which read and write operations send bursts of data in batches of four. This type of
computer memory is not widely used.

SDRAM (synchronous DRAM). SDRAM synchronizes itself with the microprocessor


clock speed allowing faster access to memory. These chips are mounted on DIMM
memory modules and are classified according to the CPU speed they are designed to
support. For example, a PC133 SDRAM DIMM is designed for a Pentium 133 CPU.

ESDRAM (enhanced SDRAM). This version of SDRAM includes a small SRAM cache
in order to reduce latency and speed up operations. This standard is not widely used.

SLDRAM (synchronous link dynamic RAM). Another version of SDRAM, which was
designed as a royalty-free, open-industry standard design alternative to RDRAM. It is not
widely used.

DDR (double data rate SDRAM). DDR allows data transfers on both the rising and
falling edges of the clock cycle, which doubles the data throughput. DDR SDRAM chips
are mounted on 184-pin DIMM modules and are typically available in 128 Mb to 1 GB
capacity. They operate at bus speeds up to 400 MHz. DDR memory is very common, but
the technology behind it is at its limits, and it is being replaced by DDR2.

DDR2. These chips are the next generation of DDR SDRAM memory. They are mounted
on 240-pin DIMM modules, can operate at higher bus speeds and have a capacity to hold
256 Mb to 2 GB of memory. DDR2 has twice the latency of DDR but delivers data at
twice the speed of DDR, theoretically performing at the same level.

RDRAM (Rambus DRAM). A proprietary protocol-based, high-speed memory


technology developed by Rambus Inc., RDRAM has current frequencies of 800 MHz to
1200 MHz, and planned chip sets can expect to reach 1600 MHz. RDRAM RIMMs can
only be used on motherboards or systems specifically designed for them. There are 184
pins for 16-bit RDRAM RIMMs; 32-bit RDRAM RIMMs have 232 pins.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 22


COMPUTER PROGRAMMING LABORATORY

FLASH memory
Flash memory is a memory storage
device for computers and electronics. It is
most often used in devices like digital
cameras, USB flash drives, and video
games. It is quite similar to EEPROM.

Flash memory is different from RAM


because RAM is volatile (not
permanent). When power is turned off,
RAM loses all its data. Flash can keep its
data intact with no power at all. A hard
drive also is permanent (non-volatile)
storage, but it is bulky and fragile. Flash
memory is slower than RAM, but faster
than hard drives. It is much used in small
electronics because it is small and has no
moving parts.

The main weakness of flash memory is that it is more expensive than hard drives for the same
amount of storage. Another weakness of flash memory is the number of times that data can be
written to it. Data can be read from flash as many times as desired, but after a certain number of
"write" operations, it will stop working. Most flash devices are designed for about 100,000 -
1,000,000 write operations (or "write cycles").

EEPROM has the same limitation that flash does: it can only survive about 100,000 write cycles.
But it is more expensive than flash, so it is rarely used for storage greater than 128kB. The main
difference between EEPROM and flash memory is that EEPROM can "write" to any byte of
memory, at any time. Flash memory can only write to an entire chunk, or "sector", of memory at
a time. That means that if the user wants to change only one byte, flash must also re-write all the
bytes in that sector. This means that flash memory can wear out faster than EEPROM. Flash
Memory can store as many as hundreds of GBs. Many are in the form of a pen drive.

Flash memory is used in USB Drives, SSD Drives, computer RAM (occasionally), hybrid drives
(small SSD + Hard Drive), graphics cards, and memory cards.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 23


COMPUTER PROGRAMMING LABORATORY

Hard disks
A hard disk drive (sometimes abbreviated as Hard drive, HD, or HDD) is a non-volatile
memory hardware device that permanently stores and retrieves data on a computer. A hard drive
consists of one or more platters to which data is written using a magnetic head, all inside of an
air-sealed casing. Internal hard disks reside in a drive bay, connect to the motherboard using an
ATA, SCSI, or SATA cable, and are powered by a connection to the PSU (power supply unit).

Hard drive components

As can be seen in the picture above, the desktop hard drive consists of the following
components: the head actuator, read/write actuator arm, read/write head, spindle, and platter. On
the back of a hard drive is a circuit board called the disk controller or interface board and is what
allows the hard drive to communicate with the computer.

What is stored on a hard drive?

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 24


COMPUTER PROGRAMMING LABORATORY

A hard drive can be used to store any data, including pictures, music, videos, text documents, and
any files created or downloaded. Also, hard drives store files for the operating system and
software programs that run on the computer.

What is stored on a hard drive?


A hard drive can be used to store any data, including pictures, music, videos, text documents, and
any files created or downloaded. Also, hard drives store files for the operating system and
software programs that run on the computer.

Where is the hard drive found in a computer?


All primary computer hard drives are found inside a computer case and are attached to the
computer motherboard using an ATA, SCSI, or SATA cable, and are powered by a connection to
the PSU (power supply unit).

What are the sizes of hard drives?


The hard drive is typically capable of storing more data than any other drive, but its size can vary
depending on the type of drive and its age. Older hard drives had a storage size of several
hundred megabytes (MB) to several gigabytes (GB). Newer hard drives have a storage size of
several hundred gigabytes to several terabytes (TB). Each year, new and improved technology
allows for increasing hard drive storage sizes.

Optical media

Optical media - such as the compact disk (CD) - are storage media that hold content in digital
form and that are written and read by a laser; these media include all the various CD and DVD
variations, as well as optical jukeboxes and autochangers. Optical media have a number of
advantages over magnetic media such as the floppy disk. Optical disk capacity ranges up to 6
gigabytes; that's 6 billion bytes compared to the 1.44 megabytes (MB) - 1,440,000 bytes - of the
floppy. One optical disk holds about the equivalent of 500 floppies worth of data. Durability is
another feature of optical media; they last up to seven times as long as traditional storage media.

The Optical Storage Technology Association (OSTA) is an international trade organization


dedicated to the promotion of standardized writable optical technologies and related products.
Incorporated in 1992, OSTA is made up of members and associates from the leading optical

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 25


COMPUTER PROGRAMMING LABORATORY

media manufacturers and resellers of North America, Europe, and Asia. OSTA members include
Adaptec, Hewlett-Packard, Philips, and Sony.

CD-R
Alternatively referred to as a cd writer, CD-WO (Write once), WORM (Write Once Read Many)
drive. CD-R is short for CD-Recordable and is a writable disc and drive that is capable of having
information written to the disc once and then having that disc read many times after that. Data
cannot be deleted from a CD-R disc and a CD-R disc cannot be formatted. If the data is not
written to the disc properly, it cannot be corrected and is often jokingly referred to as a coaster.

The first recordable specification (CD-WO) was published


in 1989 by Philips and Sony in the Orange Book. However,
the drives were not popularized until Hewlett Packard
released the HP 4020i in September 1995.

CD-Rs are a low-cost solution for backing up software and


only costs a few cents (as of 2010 around 17-cents a disc)
and can hold up to 650 MB (74 minutes of music) or
700MB (80 minutes of music). Although these are still a
very popular solution for backing up data, more users are
turning to DVD-R and USB thumb drives to backup and
transfer their data today.

How does the CD-R work?

A CD-R disc is coated with a photosensitive organic dye that allows a user to record information.
Once the CD-R disc is placed within the computer, the recording process begins. The laser inside
the drive heats the dye to reveal areas that diffuse the light like a traditional CD pit. The CD-R
drive does not create pits on the CD; instead the burner creates reflective sections on the CD
causing the computer's CD-ROM laser to interpret it as a pit. Once a CD-R disc is finished
recording, the CD can be used in any standard CD-ROM, CD-R, CD-RW, or DVD drive.
Although, there were issues with the first revision DVD drives reading CD-R disc, today's drives
no longer suffer from any reading problems.

CD R/W
Short for Read/Write, R/W is a file attribute or permission that can be given to files and
directories that allows them to be read or written. These attributes can also be taken away to
prevent that file from being read or modified.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 26


COMPUTER PROGRAMMING LABORATORY

Short for Read/Write, R/W is a drive and CD


media that was first introduced in 1997 that is
capable of being written to and read. Unlike a
traditional CD-R disc that can only be written to
once, these discs allow data to be erased and re-
written multiple times.

The CD-R technology uses a photosensitive


dye, CD-RW discs use an active layer of Ag-In-
Sb-Te (silver-indium-antimony-tellurium) alloy
that, in its original state, has a polycrystalline
structure that makes it reflective. When the CD-
RW drive writes to the disc, the laser uses its
highest power setting known as Pwrite. At this
temperature, which is usually between 500 and 700 degrees Celsius, the chemical structure will
liquefy. In its liquid state, the molecules of the active material flow freely, losing their
polycrystalline structure and taking on an amorphous state. When the material solidifies in this
amorphous state, it loses its reflectivity. By selectively firing the laser, the drive leaves parts of
the disc in its polycrystalline state, forming the lands, and parts in the amorphous state forming
the pits.

To reverse the phase of a specific area on a disc, the laser operates at a lower power setting and
heats the active material to approximately 200 degrees Celsius. By heating the disc it reverts
back from its amorphous to its polycrystalline state and then becomes reflective again.

The drawback with CD-RW discs is with the lower reflectivity of the disc itself can limit the
readability. In the 1980s, the CD standards specified that on a compact disc the lands should have
a minimum of 70% and the pits should have a reflectance of 28%. However, on a CD-RW disc,
the reflectance of a land is approximately 15% to 25%. The low reflectance can cause certain
CD-RWs discs to be unreadable in some older CD-ROM drives and CD players.

DVDs
Short for Digital Versatile Disc or Digital Video Disc, a DVD or
DVD-ROM is a disc capable of storing large amounts of data on
one disc the size of a standard Compact Disc. CD/DVD drives
were first sold in 1997. Today they are widely used for storing
and viewing movies and other data. To play DVDs on a
computer, you must have a DVD drive and a software DVD
player. The picture to the right is an example of what a DVD
movie may look like, which in this example is a picture of the
Matrix DVD movie.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 27


COMPUTER PROGRAMMING LABORATORY

How much data can a DVD hold?


There are several capacities a single DVD disc is capable of holding. Below is a listing of the
different types of DVD's and each of their total capacity.

One of the most common DVD's is the single-sided, single-layer disc, capable of holding
4.7 GB.

The single-sided, double-layer disc is capable of holding between 8.5-8.7 GB.

The double-sided, single-layer disc is capable of holding 9.4 GB.

Although rare, the double-sided, double-layer disc is capable of holding up to 17.08 GB.

What is the difference between a DVD and a CD?


Physically, a DVD and CD look the same. Both discs are the same size and typically have one
side with a label and the other side that the laser reads, unless it is a double-sided DVD.
However, the technology that makes up a DVD allows for the same size disc to hold a lot more
data than a CD.

What types of information can be stored in a DVD?


A DVD is capable of holding any data and are most often used to store movie data, games, and
install data for programs.

What DVD player should I get to play DVD movies?


We recommend VLC, it's free and an open-source media player that works on Windows, Mac,
and Linux. However, you can also use Windows Media Player on Windows computers to play
most DVDs.

Can DVD drives read CDs?


Yes, all DVD drives are capable of reading both CDs and DVDs. If you have a DVD burner, it
will be capable of reading CDs and DVDs, as well as writing CD-Rs, CD-RWs, and writable
DVDs.

The history of DVD


In 1993, there were two video disc formats being developed: the Multimedia Compact Disc
(MMCD) and the Super Density (SD) disc. To avoid a video format war, Philips and Sony, the
backers of the MMCD, decided to combine forces with the backers of the SD disc (Hitachi, JVC,

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 28


COMPUTER PROGRAMMING LABORATORY

Mitsubishi, Pioneer, Toshiba, and several others) and develop a single video disc format.
Together, the two groups developed the DVD format.

What was the first DVD?


The movie Twister became the first feature film put on DVD on March 25, 1996.

The future of DVD


DVD's are still very popular and widely used. However, due to more recent technologies like
Blu-ray discs and streaming services like Netflix and other cloud services, DVD sales and usage
have been on a steep decline.

Keyboard
A computer keyboard is one of the primary input devices used with a computer that looks similar
to those found on electric typewriters, but with some additional keys. The modern keyboard is
based on the typewriter, a typing device that was first developed and patented in 1868 by
Christopher Sholes.

Keyboards allow you to input letters, numbers, and other symbols into a computer that often
function as commands. The following image shows a 104-key Saitek keyboard with indicators
pointing to each of the major key sections of a keyboard including the control keys, function
keys, LED indicators, wrist pad, arrow keys, and keypad.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 29


COMPUTER PROGRAMMING LABORATORY

How many keys are on a computer keyboard?


Although there is not a single set of rules dictating the number of keys on a keyboard, most
companies use the PC keyboard with 104 keys as a de facto standard. There have been many
different manufacturers over the years, so the number of keys varies from model to model. This
document contains the counts for many of the more common types of keyboards in their
respective classes.

IBM/PC keyboards

Original IBM PC Keyboard (1981) - 83 keys

Updated IBM PC Keyboard (1984) - 84 keys

AT Keyboard - 84 keys

AT Enhanced Keyboard - 101 keys

US Traditional Keyboard - 101 keys

Enhanced European Keyboard - 102 keys

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 30


COMPUTER PROGRAMMING LABORATORY

Windows Keyboard - 104 keys

Windows-based Laptop Keyboard - 86 keys

Apple keyboards

Apple Keyboard with Numeric Keypad - 109 keys

Apple Wireless Keyboard - 78 keys

Apple MacBook Air laptop - 78 keys

Miscellaneous keyboards
Other keyboard configurations may include more than 104 keys, mainly being the Korean,
Japanese, and Brazilian keyboards. Also, keyboards with keys to control a CD drive and Media
Center functionality using special keys may have several dozen additional keys. Other keyboards
provide programmable keys and may fall into the category of a programmable or gaming
keyboard.

How many function keys are on a keyboard?


Today's traditional PC keyboards have 12 function keys, F1 through F12. Many Apple desktop
computer keyboards with a number pad have 19 function keys, F1 through F19. See our function
keys page for further information about function keys and their functions.

How many keys are on the numeric keypad


All keyboards only have one numeric keypad, and if you count all of the numbers and symbols
on it, there are 17 keys on the PC numeric keypad and 18 keys on most Apple keyboards.

Note: Some computers may also have an external USB numeric keypad attached to the computer.
An external USB numeric keypad can have any number of keys. For example, the one shown on
our numeric keypad page has 31 keys.

How many number keys are on a keyboard?


If you only count the number keys above the keyboard 1 through 0, there are ten number keys on
the keyboard. If you count the number keys above the keyboard as well as the number keys on
the numeric keypad (1 through 0), there are twenty number keys on the keyboard.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 31


COMPUTER PROGRAMMING LABORATORY

How many alphabetic keys are on a keyboard?


On an English computer keyboard, there are the same numbers of letters as there are in the
language, 26 letters.

How many symbols are on a keyboard?


On an English QWERTY keyboard there are 40 symbols (e.g. !, @, #, $, and % that are not
letters or numbers) on 28 keys. There is a difference in numbers because some of the keys have
two symbols.

Note: The above count includes the Windows key and Menu key (3 keys) and does not count the
arrow keys.

How many arrow keys are on a keyboard?


There are four arrow keys on a keyboard. If you also count the arrow keys on most PC keyboards
the number pad, there are eight arrow keys.

Keyboard overview
Below is a closer up image of a QWERTY computer keyboard with each of the keys selectable.
Hover over any of the keys below to see a description of the key and click any of the keys to
open a new page with full details about the key.

Keyboard interfaces

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 32


COMPUTER PROGRAMMING LABORATORY

Today, most desktop computer keyboards connect to


the computer using either USB or Bluetooth for
wireless communication. Before USB, a computer may
have used PS/2 or AT (Din5) as a keyboard interface.

Types of keyboards
Today, most keyboards are similar to each other, but may be missing one or more of the sections
mentioned earlier (e.g. the keypad). Where keyboards begin to differ the most is with the
keyboard layout. While most keyboards use the QWERTY layout, there are still people who use
the DVORAK layout.

Laptop keyboards
A laptop keyboard is different from a desktop keyboard to help reduce the size and the overall
weight of the laptop. Most laptop keyboards are made smaller by placing the keys closer to each
other and not always including control keys or a keypad. For a laptop to have all the same
functions of a desktop keyboard, laptop keyboards use a Fn key that is used in conjunction with
other keys to perform special functions. For example, pressing the Fn key and the up or down
arrow on the keyboard shown below, increases and decreases the brightness of the screen.

Another difference with a laptop keyboard is the type of switch beneath each key or how the
keys feel when pressed down. Some users may even experience more typing errors when typing
on a laptop because of how easy it can be to press another key next to the key you intended to
press.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 33


COMPUTER PROGRAMMING LABORATORY

Smartphone and tablet keyboards


Today's smartphones and tablets do not come with a physical keyboard although it is an optional
add-on. These devices utilize a thumb keyboard or on-screen keyboard to type messages and
other text. In the picture to the right is an example of the Apple iPhone on-screen keyboard.

Mouse
When and who invented the first computer mouse?
The computer mouse as we know it today was invented and
developed by Douglas Engelbart, with the assistance of Bill
English, during the 1960's and was patented on November 17,
1970.

While creating the mouse, Douglas was working at the Stanford


Research Institute, a think tank sponsored by Stanford
University. The mouse was originally referred to as an "X-Y
Position Indicator for a Display System" and was first used
with the Xerox Alto computer system in 1973. Using the
mouse, Douglas was able to demonstrate moving a mouse
cursor on the Alto computer in The Mother of All Demos.
However, because of its lack of success, the first widely used mouse is the mouse found on the
Apple Lisa computer.

The picture to the right was taken by Maracin Wichary at the New Mexico Museum of Natural
History and Science and is an example of what the first computer mouse. As you can see in the
picture, the mouse was made of wood, was much larger than today's mouse, rectangular in size,
and had a small button in the top right corner.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 34


COMPUTER PROGRAMMING LABORATORY

Today, the mouse is still used on every desktop computer and


has influenced other input devices such as the touchpad on a
laptop computer and touch screens on smartphones and tablets.

Why is the computer mouse called a


mouse?
With the cord coming out of the back of the mouse Douglas
said the device reminded him of the rodent mouse and the name
stuck. It's a lot easier to remember than a X-Y Position Indicator for a Display System.

Originally referred to as an X-Y Position Indicator for a Display System, a mouse is a hardware
input device that was invented by Douglas Engelbart in 1963 while working at Xerox PARC. The
mouse allows an individual to control a pointer in a graphical user interface (GUI) and
manipulate on-screen objects such as icons, files, and folders.

By using a mouse, the user doesn't have to memorize commands, such as those utilized in a text-
based command line environment like MS-DOS. For example, in MS-DOS a user would have to
know the cd command and dir command to navigate to a folder and view the files inside.
Whereas a Windows user only has to double-click a file to view its contents.

After its inception at the Stanford Research Institute (a think tank sponsored by Stanford
University), Xerox applied the mouse to its revolutionary Alto computer system in 1973.
However, due to Alto's lack of success, the first widely used application was with the Apple Lisa
computer. Today, this pointing device is found on virtually every computer.

Types of computer mice

Cordless (Wireless)

Footmouse

IntelliMouse (Wheel mouse)

J mouse

Joystick

Mechanical

Optical

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 35


COMPUTER PROGRAMMING LABORATORY

Touchpad (Glidepoint)

Trackball

TrackPoint

Computer mouse ports


Today, most computer mice connect to a computer using a USB port. Below is a listing of all of
the type of ports and wireless connections that a mouse has used.

Bluetooth

Infrared

PS/2 Port

Serial Port

USB

Mouse vs. mice or mouses


When talking about one (singular) you refer to a computer mouse as a "mouse." When talking
about two or more (plural) you refer to them as "mice" or "mouses" although "mice" is more
common.

Note: To help prevent confusion, some companies and writers avoid using either plural form of
mouse by referring to multiple mice as "mouse devices."

Is "mouse" an acronym?
No. Some believe that mouse is short for "manually-operated user-select equipment," but when
Douglas Engelbart helped invent the mouse he called it a mouse because the device resembled
the rodent.

What are the functions of a mouse?

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 36


COMPUTER PROGRAMMING LABORATORY

A computer mouse has many functions that help a user use their computer. Below are the most
common functions of a mouse.

Move the mouse cursor - The primary use of a computer mouse is to move the mouse
cursor on the screen.

Open or execute a program - Once you've moved the mouse to an icon, folder, or other
object clicking or double clicking that object opens the document or executes the
program.

Select - A mouse also allows you to select a file or highlight and select multiple files at
once.

Scroll - When working with a long document or viewing a long web page you may need
to scroll up or down on that page. Using a mouse wheel or clicking and dragging the
scroll bar is another function of the mouse.

Printer
A printer is an external hardware output device responsible for taking
electronic data stored on a computer or computing device and
generating a hard copy of that data. Printers are one of the most
commonly used peripherals on computers and are commonly used to
print text and photos. The picture to the right is an example of a
computer printer, the Lexmark Z605 Inkjet printer.

Types of printers
Below is a list of all the different types of computer printers.
Today, the most common printers used with a computer are Inkjet
and Laser printers.

3D printer

Dot Matrix printer

Inkjet printer

Laser printer

LED printer

Multifunction printer (MFP)

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 37


COMPUTER PROGRAMMING LABORATORY

Plotter

Thermal printer

Printer interfaces

There are different interfaces or ways a printer can connect to the computer. Today, the most
common cable and ways a printer connects to a computer is
by using a USB or Wi-Fi connection. Below is a full list of
cables and interfaces used to connect a computer to a printer.

Cat5

Firewire

MPP-1150

Parallel port

SCSI

Serial port

USB

Wi-Fi

History of the printer


The first mechanical printer was invented by Charles Babbage, for use with the Difference
Engine, which Babbage developed in 1822. Babbage's printer utilized metal rods with printed
characters on each rod to print text on rolls of paper that were fed through the device.

While inkjet printers started being developed in the late 1950s, it wasn't until the late 1970s that
inkjet printers were able to reproduce good quality digital images. These better quality inkjet
printers were developed by multiple companies, including Canon, Epson, and Hewlett-Packard.

In the early 1970s, Gary Starkweather invented the laser printer while working at Xerox. He
modified a Xerox 7000 copier to essentially be a laser printer, by having a laser output electronic
data onto paper. However, it wasn't until 1984 that laser printers became more widely and
economically available when Hewlett-Packard introduced the first low-cost laser printer, the HP

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 38


COMPUTER PROGRAMMING LABORATORY

LaserJet. The following year, Apple introduced the Apple LaserWriter laser printer, adding the
PostScript technology to the printer market.

Plotter
A plotter is a computer hardware device much like a
printer that is used for printing vector graphics. Instead of
toner, plotters use a pen, pencil, marker, or another writing
tool to draw multiple, continuous lines onto paper rather
than a series of dots like a traditional printer. Though once
widely used for computer-aided design, these devices have
more or less been phased out by wide-format printers.
Plotters are used to produce a hard copy of schematics and
other similar applications.

Advantages of plotters

Plotters can work on very large sheets of paper while maintaining high resolution.

They can print on a wide variety of flat materials including plywood, aluminum, sheet
steel, cardboard, and plastic.

Plotters allow the same pattern to be drawn thousands of time without any image
degradation.

Disadvantages

Plotters are quite large when compared to a traditional printer.

Plotters are also much more expensive than a traditional printer.

Flowchart

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 39


COMPUTER PROGRAMMING LABORATORY

A flowchart is a graphical representation of


decisions and their results mapped out in
individual shapes that were first developed by
Herman Goldstine and John von Neumann in
the 1940's. Flowcharts can provide a step-by-
step diagram for mapping out complex
situations, such as programming code or
troubleshooting problems with a computer. The
picture to the right shows an image from
Microsoft Visio, a popular program used to
design and create flowcharts and diagrams.

Below is an example of a basic flowchart created in Visio that gives a good representation of
their layout. As can be seen, you have several steps that may be followed systematically to help
determine the cause of computer problem. Of course, this is just an example and not the full set
of steps required to troubleshoot computer issues.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 40


COMPUTER PROGRAMMING LABORATORY

Other examples of how flow charts are used


Flowcharts can also be created for any of the situations below.

Algorithm - List the steps of how an algorithm works.

Audit - Give the steps required to test a system or process with steps on handle any
problems.

Procedure - List the steps for completing any procedure to help verify everything is done
right the first time and every time.

Program - Steps on how to create or use a program.

Projects - Give an overview of the steps required for creating a new project or the steps
on how to complete the project.

Troubleshooting - List the steps involved for troubleshooting a problem, like the
example listed earlier.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 41


COMPUTER PROGRAMMING LABORATORY

Algorithm
Derived from the name of the mathematician Muhammed ibn-Musa Al-Khowarizmi, an
algorithm is a solution to a problem that meets the following criteria.

A list of instructions, procedures, or formula that solves a problem.

Can be proven.

Something that always finishes and works.

Examples of how are algorithms used today


Today, algorithms are used billions of times every day for a variety of tasks. Below are just a
very few of the different ways algorithms are used today.

Computers use algorithms to convert data (e.g. converting decimal into binary).

Google search uses the PageRank algorithm to sort search results.

Encryption to encrypt and decrypt information and keep data safe is an algorithm.

GPS uses algorithms to find the best route to a destination.

There are dozens of sort algorithms that are used to sort data.

Smartphones, Wi-Fi, and wireless communication use algorithms to communicate.

E-mail spam detection uses algorithms to filter out bad e-mails.

Data compression for getting information faster (e.g. YouTube video) use algorithms.

When was the first algorithm?


Because a cooking recipe could be considered an algorithm the first algorithm could go back as
far as when writing. However, many find Euclid's Euclidean algorithm for finding the greatest
common divisor to be the first algorithm that was first described in 300 B.C. Ada Lovelace is
credited as being the first person to develop an algorithm for a machine.

Pseudocode

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 42


COMPUTER PROGRAMMING LABORATORY

Pseudocode (rarely known as Program Design Language) is an informal high-level description of


the operating principle of a computer program or other algorithm.

It uses the structural conventions of a normal programming language, but is intended for human
reading rather than machine reading. Pseudocode typically omits details that are essential for
machine understanding of the algorithm, such as variable declarations, system-specific code and
some subroutines. The programming language is augmented with natural language description
details, where convenient, or with compact mathematical notation. The purpose of using
pseudocode is that it is easier for people to understand than conventional programming language
code, and that it is an efficient and environment-independent description of the key principles of
an algorithm. It is commonly used in textbooks and scientific publications that are documenting
various algorithms, and also in planning of computer program development, for sketching out the
structure of the program before the actual coding takes place.

No standard for pseudocode syntax exists, as a program in pseudocode is not an executable


program. Pseudocode resembles, but should not be confused with skeleton programs which can
be compiled without errors. Flowcharts, drakon-charts and Unified Modeling Language (UML)
charts can be thought of as a graphical alternative to pseudocode, but are more spacious on
paper.

Application
Textbooks and scientific publications related to computer science and numerical computation
often use pseudocode in description of algorithms, so that all programmers can understand them,
even if they do not all know the same programming languages. In textbooks, there is usually an
accompanying introduction explaining the particular conventions in use. The level of detail of
the pseudo-code may in some cases approach that of formalized general-purpose languages.

A programmer who needs to implement a specific algorithm, especially an unfamiliar one, will
often start with a pseudocode description, and then "translate" that description into the target
programming language and modify it to interact correctly with the rest of the program.
Programmers may also start a project by sketching out the code in pseudocode on paper before
writing it in its actual language, as a top-down structuring approach, with a process of steps to be
followed as a refinement.

Syntax
As the name suggests, pseudocode generally does not actually obey the syntax rules of any
particular language; there is no systematic standard form, although any particular writer will
generally borrow style and syntax; for example, control structures from some conventional
programming language. Popular syntax sources include Fortran, Pascal, BASIC, C, C++, Java,

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 43


COMPUTER PROGRAMMING LABORATORY

Lisp, and ALGOL. Variable declarations are typically omitted. Function calls and blocks of code,
such as code contained within a loop, are often replaced by a one-line natural language sentence.

Depending on the writer, pseudocode may therefore vary widely in style, from a near-exact
imitation of a real programming language at one extreme, to a description approaching formatted
prose at the other.

Pseudocode is an artificial and informal language that helps programmers develop algorithms.
Pseudocode is a "text-based" detail (algorithmic) design tool.

The rules of Pseudocode are reasonably straightforward. All statements showing "dependency"
are to be indented. These include while, do, for, if, switch. Examples below will illustrate this
notion.

Examples:

1. If student's grade is greater than or equal to 60

Print "passed"
else
Print "failed"

2. Set total to zero

Set grade counter to one

While grade counter is less than or equal to ten


Input the next grade
Add the grade into the total

Set the class average to the total divided by ten

Print the class average.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 44


COMPUTER PROGRAMMING LABORATORY

C Programming constructs
if statement

Syntax of if
if (testExpression)
{
// statements
}

The if statement evaluates the test expression inside parenthesis.

If test expression is evaluated to true (nonzero), statements


inside the body of if is executed.

If test expression is evaluated to false (0), statements inside the


body of if is skipped.

To learn more on when test expression is evaluated to nonzero


(true) and 0 (false), check out relational and logical operators.

if...else statement

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 45


COMPUTER PROGRAMMING LABORATORY

The if...else statement executes some code if the test


expression is true (nonzero) and some other code if the test
expression is false (0).
Syntax of if...else
if (testExpression)
{
// code inside the body of if
}
else
{
// code inside the body of else
}

Nested if...else statement (if...else if....else Statement)

The if...else statement executes two different codes depending upon whether the test expression
is true or false. Sometimes, a choice has to be made from more than 2 possibilities.

The nested if...else statement allows you to check for multiple test expressions and execute
different codes for more than two conditions.

Syntax of nested if...else statement


if (testExpression1)
{
// statements to be executed if testExpression1 is true
}
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is true
}
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false and testExpression3 is true
}
.
.
else
{
// statements to be executed if all test expressions are false
}

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 46


COMPUTER PROGRAMMING LABORATORY

while loop

The syntax of a while loop is:

while (testExpression)
{
//code
}

How while loop works?

The while loop evaluates the test expression.

If the test expression is true (nonzero), code inside the body of while loop is evaluated. The test
expression is evaluated again. The process goes on until the test expression is false.

When the test expression is false, the while loop is terminated.

do...while loop
The do..while loop is similar to the while loop with one
important difference. The body of do...while loop is executed
once, before checking the test expression. Hence, the
do...while loop is executed at least once.

do...while loop Syntax


do
{
// code
}
while (testExpression);

How do...while loop works?

The code block (loop body) inside the braces is executed once.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 47


COMPUTER PROGRAMMING LABORATORY

Then, the test expression is evaluated. If the test expression is true, the loop body is executed
again. This process goes on until the test expression is evaluated to 0 (false).

When the test expression is false (nonzero), the do...while loop is terminated.

for Loop

The syntax of a for loop is:

for (initializationStatement; testExpression;


updateStatement)
{
// code

How for loop works?

The initialization statement is executed only once.

Then, the test expression is evaluated. If the test


expression is false (0), for loop is terminated. But if the test expression is true (nonzero), code
inside the body of for loop is executed and the update expression is updated.

This process repeats until the test expression becomes false.

The for loop is commonly used when the number of iterations is known.

break and continue statements

It is sometimes desirable to skip some statements inside the loop or terminate the loop
immediately without checking the test expression.

In such cases, break and continue statements are used.

break Statement
The break statement terminates the loop (for, while and do...while loop) immediately when it is
encountered. The break statement is used with decision making statement such as if...else.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 48


COMPUTER PROGRAMMING LABORATORY

Syntax of break statement


break;

Flowchart of break statement How break statement works?

In C programming, break statement is also used with switch...case statement.

continue Statement
The continue statement skips some statements inside the loop. The continue statement is used
with decision making statement such as if...else.

Syntax of continue Statement


continue;

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 49


COMPUTER PROGRAMMING LABORATORY

Flowchart of continue statement How continue statement works?

switch...case Statement

The nested if...else statement allows you to execute a block code among many alternatives. If
you are checking on the value of a single variable in nested if...else statement, it is better to use
switch statement.

The switch statement is often faster than nested if...else (not always). Also, the syntax of switch
statement is cleaner and easy to understand.

Syntax of switch...case

switch (n)
{

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 50


COMPUTER PROGRAMMING LABORATORY

case constant1:
// code to be executed if n is equal to constant1;
break;

case constant2:
// code to be executed if n is equal to constant2;
break;
.
.
.
default:
// code to be executed if n doesn't match any constant
}
When a case constant is found that matches the switch expression, control of the program passes
to the block of code associated with that case.

In the above pseudocode, suppose the value of n is equal to constant2. The compiler will execute
the block of code associate with the case statement until the end of switch block, or until the
break statement is encountered.

The break statement is used to prevent the code running into the next case.

If break statement is not used, all cases after the correct case is executed.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 51


COMPUTER PROGRAMMING LABORATORY

switch Statement Flowchart

C goto Statement

The goto statement is used to alter the normal sequence of a C program.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 52


COMPUTER PROGRAMMING LABORATORY

Syntax of goto statement

goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
The label is an identifier. When goto statement is
encountered, control of the program jumps to label:
and starts executing the code.

Reasons to avoid goto statement


The use of goto statement may lead to code that is buggy and hard to follow. For example:

one:
for (i = 0; i < number; ++i)
{
test += i;
goto two;
}
two:
if (test > 5) {
goto three;
}
... .. ...
Also, goto statement allows you to do bad stuff such as jump out of scope.

That being said, goto statement can be useful sometimes. For example: to break from nested
loops.

Should I or shouldn't I use goto statement?


If you think the use of goto statement simplifies your program. By all means use it. The goal here
is to create code that your fellow programmers can understand easily.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 53


COMPUTER PROGRAMMING LABORATORY

1.

Design and develop a flowchart or an algorithm that takes three coefficients (a, b, and c) of
a Quadratic equation (ax2+bx+c=0) as input and compute all possible roots. Implement
a C program for the developed flowchart/algorithm and execute the same to output the
possible roots for a given set of coefficients with appropriate messages.

/* Lab 1 - Quadratic Equation */

Objective: To develop the logic to find roots of quadratic equation and also to find the
nature of the roots.

Algorithm

1. Start

2. Read the values for a, b & c, the coefficients of quadratic equation, such that a <>0.

3. Compute disc = b*b 4*a*c

4. If disc = 0 then goto step 7 else goto step 5

5. If disc > 0 then goto step 8 else goto step 6

6. If disc < 0 then goto step 9

7. Compute x1 = x2 = -b / (2*a), the two real and equal roots, display x1 and x2, goto step 10

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 54


COMPUTER PROGRAMMING LABORATORY

8. Compute x1 = (- b + sqrt(disc))/(2*a) and x2 = (- b - sqrt(disc))/(2*a), the two real and


distinct roots, display x1 and x2, goto step 10

9. Compute x1=-b/(2*a), the real part of the complex roots and x2=sqrt(abs(disc)) /(2*a), the
imaginary part of the complex roots. Display the first root as x1 i x2 and second root as x1
+ i x2

10. Stop

#include<stdio.h>
#include<math.h>
void main()
{
float a, b, c;
float x1, x2, desc, img;
printf("\nEnter the value of a, b and c : ");
scanf("%f%f%f", &a, &b, &c);
desc = (b * b) - (4 * a * c);
if(desc==0)
{
printf("Roots are real and equal\n");
x1 = (-b)/(2.0 * a);
printf("Roots are :\nx1 = %f \nx2 = %f", x1, x1);
}
else if(desc>0)
{
printf("Roots are real and not equal\n");
x1 = ( - b + sqrt(desc)) / (2.0 * a);
x2 = ( - b - sqrt(desc)) / (2.0 * a);
printf("Roots are :\nx1 = %f \nx2 = %f", x1, x2);
}
else if(desc<0)
{
printf("Roots are complex and not equal\n");
x1 = (-b)/(2.0 * a);
img = sqrt(-desc) / (2.0 * a);
printf("Roots are : \nx1 = %f + i %f \nx2 = %f - i %f", x1, img, x1, img);
}
}

Output

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 55


COMPUTER PROGRAMMING LABORATORY

Enter the value of a, b and c : 1 2 3


Roots are complex and not equal
Roots are :
x1 = -1.000000 + i 1.414214
x2 = -1.000000 - i 1.414214

Enter the value of a, b and c : 4 4 1


Roots are real and equal
Roots are :
x1 = -0.500000
x2 = -0.500000

Enter the value of a, b and c : 3 6 2


Roots are real and not equal
Roots are :
x1 = -0.422650
x2 = -1.577350

Outcome:
The students get to know the evaluation to find the roots of a quadratic equation.
The standard mathematical functions like fabs(),sqrt() are use here which are available
under math.h header file.

Viva question:

What is the header file required to use standard i/o functions?


What is the header file required to use mathematical library functions?
Explain the functionality of fabs() function.

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.

/* Lab 2 - Reverse of an integer and check for palindrome */

Objective: To find reversal of any integer number and to understand the concept of
palindrome.

Algorithm
(1) Start
(2) Read num
(3) Store it in temp for future use.
(4) Initialize rev_num = 0

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 56


COMPUTER PROGRAMMING LABORATORY

(5) Loop while num > 0


(a) Multiply rev_num by 10 and add remainder of num
divide by 10 to rev_num
rev_num = rev_num*10 + num%10;
(b) Divide num by 10 and store it in num
(6) rev_num contains the reverse of the number
(7) If temp = rev_num, the given number is a palindrome, otherwise it is not.
(8) Stop

Tracing Example:
num = 4562 rev_num = 0
rev_num = rev_num *10 + num%10 = 2 num = num/10 = 456
rev_num = rev_num *10 + num%10 = 20 + 6 = 26 num = num/10 = 45
rev_num = rev_num *10 + num%10 = 260 + 5 = 265 num = num/10 = 4
rev_num = rev_num *10 + num%10 = 265 + 4 = 2654 num = num/10 = 0

#include<stdio.h>
void main()
{
int n, num, rev;
printf("\nEnter a number : ");
scanf("%d", &num);
rev = 0;
n = num;
while(n>0)
{
rev = (rev * 10) + (n % 10);
n = n / 10;
}
printf("Reverse of the number %d is %d", num, rev);
if(num==rev)
{
printf("\nThe number %d is a Palindrome", num);
}
else
{
printf("\nThe number %d is not a Palindrome", num);
}
}

Output

Enter a number : 12321


Reverse of the number 12321 is 12321
The number 12321 is a Palindrome

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 57


COMPUTER PROGRAMMING LABORATORY

Enter a number : 2345


Reverse of the number 2345 is 5432
The number 2345 is not a Palindrome

Outcome:
Students understand the usage of while loop.
Students understand the concept of palindrome.

Viva questions:
What is palindrome?
Explain the syntax of while loop.
Explain the syntax of printf() and scanf().

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 with
appropriate messages. Note: Dont use library function sqrt(n).
/* Lab 3a - Square root of a number without using library function sqrt */

Objective: To find square root of any number without using standard library function
sqrt().

#include<stdio.h>
int main()
{
float number, sqroot, temp;
printf("Enter a Number : ");
scanf("%f", &number);
sqroot = number / 2;
temp = 0;
while(sqroot != temp)

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 58


COMPUTER PROGRAMMING LABORATORY

{
temp = sqroot;
sqroot = (number/sqroot + sqroot) / 2;
}
printf("Square root of %f is %f \n", number, sqroot);
}

Tracing Example

number sqroot temp is sqroot


<> temp?
Initial 30 15 0 Yes
iteration 1 30 8.5 15 Yes
30 6.0147058 8.5 Yes
iteration 2 82
30 5.5012404 6.0147058 Yes
iteration 3 72 82
30 5.4772779 5.5012404 Yes
iteration 4 92 72
30 5.4772255 5.4772779 Yes
iteration 5 75 92
30 5.4772255 5.4772255 No
iteration 6 75 75

Start
The square root of 30 is 5.477225575

Read the value for number

sqroot = number / 2
temp = 0
Flowchart for 3a

no

is sqroot <> temp?


yes

temp = sqroot
sqroot = (number/sqroot + sqroot) / 2

Print the value of sqroot


VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 59
Stop
COMPUTER PROGRAMMING LABORATORY

Output for 3a

Enter a Number : 10
Square root of 10.000000 is 3.162278

Enter a Number : 30
Square root of 30.000000 is 5.477226

3b. 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.

/* Lab 3b - Leap year */

Objective: To understand the logic of leap and to write c program for the same using
conditional branching statements.

#include<stdio.h>
void main()
{
int year;

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 60


COMPUTER PROGRAMMING LABORATORY

printf("\nPlease enter the year in yyyy format : ");


scanf("%d", &year);
if(((year % 4 == 0) && (year % 100 !=0)) || (year % 400 == 0))
{
printf("Given year is a leap year");
}
else
{
printf("Given year is not a leap year");
}
}

Algorithm for 3b

Step 1: Start
Step 2: Read year
Step 3: if (year%4=0 and year%100!=0) or if (year%400=0) then go to step 4 else go to step 5
Step 4: print a leap year, go to step 6
Step 5: print not a leap year
Step 6: Stop

Output for 3b

Please enter the year in yyyy format : 1976


Given year is a leap year

Please enter the year in yyyy format : 1900


Given year is not a leap year

Please enter the year in yyyy format : 2000


Given year is a leap year
Outcome:
Students understand the logic behind sqrt() function.
Students understand concept of looping and usage of while loop.
The usage of arithmetic and relational operators are understood.
The working of conditional branching statements is taught.

Viva questions:

Explain the syntax of while loop.


What is looping?
What are conditional branching statements?

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 61


COMPUTER PROGRAMMING LABORATORY

Explain the logic of occurrence of leap year.

Design and develop an algorithm to evaluate polynomial f(x) = a 4x4 + a3x3 + a2x2 +
a1x +a0, for a given value of x and its coefficients using Horners method. Implement
a C program for the same and execute the program with different set of values of
coefficients and x.

/* Lab 4 - Evaluating Polynomial using Horners Method */

Objective: To develop a program for the evaluation of a polynomial by using the method
proposed by Horner.

Algorithm

1. Start
2. Read number of terms n, the value for x
3. Read the coefficients of the polynomial a[0], a[1],, a[n-1]
4. Set result = 0
5. Set i = n-1
6. Calculate result = (result + a[i]) * x
7. Set i = i 1
8. As long as i>0 repeat steps 6 and 7, otherwise go to step 9
9. Set result = result + a[0]
10. Print the value of result, the value of the polynomial
11. Stop

#include<stdio.h>
#include<math.h>
void main()
{
int a[20], x, n, result;
printf("\nEnter number of terms : ");
scanf("%d",&n);
for(int i=0; i<n; i++)
{
printf("Enter Co-efficient a%d : ", i);
scanf("%d", &a[i]);
}
printf("Enter the value for x = ");
scanf("%d",&x);
result = 0;
for(i=n-1; i>0; i--)
{

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 62


COMPUTER PROGRAMMING LABORATORY

result = (result + a[i]) * x;


}
result += a[0];
printf("f(%d) = %d", x, result);
}

Output

Enter number of terms : 5


Enter Co-efficient a0 : 5
Enter Co-efficient a1 : 3
Enter Co-efficient a2 : 2
Enter Co-efficient a3 : 4
Enter Co-efficient a4 : 1
Enter the value for x = 2
f(2) = 67

Enter number of terms : 4


Enter Co-efficient a0 : -1
Enter Co-efficient a1 : 2
Enter Co-efficient a2 : -6
Enter Co-efficient a3 : 2
Enter the value for x = 3
f(3) = 5

Outcome:
The different methods for evaluating the polynomial are taught.
The usage of looping statement such as for loop is used.

Viva questions:

Explain the syntax of for loop


Explain the concept of evaluating a polynomial using Horners method.
How Horners method is different from substitution method.

Draw the flowchart and Write a C Program to compute Sin(x) using Taylor series
approximation given by Sin(x) = x - (x3/3!) + (x5/5!) - (x7/7!) + . Compare your result
with the built- in Library function. Print both the results with appropriate messages.

/* Lab 5 - Sin(x) using Taylor Series */

Objective: To understand the logic proposed by Taylor for the evaluation of polynomial and
compare the result with standard library functions.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 63


COMPUTER PROGRAMMING LABORATORY

#include<stdio.h>
#include<math.h>
float my_sine(float x, int n);
int fact(int n);
void main()
{
int x, n;
float rad, res;
printf("Enter the Degree : ");
scanf("%d", &x);
printf("Enter the number of terms : ");
scanf("%d", &n);
rad=x*(3.142/180);
res=my_sine(rad, n);
printf(" My_sine(%d)=%f\n", x , res);
printf(" Library sine(%d)=%f", x , sin(rad));
}

float my_sine(float x, int n)


{
int i;
float sum=0;
for(i=1; i<=n; i+=2)
{
if((i-1)%4==0)
sum=sum+pow(x , i)/fact(i);
else
sum=sum-pow(x , i)/fact(i);
}
return sum;
}

int fact(int n)
{ Start
if(n==0) return 1;
return n*fact(n-1);
} Read the values for x and n

Flowchart for driver program Flowchart


rad for Calculating
= x*(3.142/180) Sine using Taylor Series
res = my_sine(rad, n)

my_sine(x, n)
Print the values of res and the result obtained from std. library function sine

sum = 0 and i=1

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 64


Stop
COMPUTER PROGRAMMING LABORATORY

is i<=n? no
return sum

yes
is (i-1) mod 4=0?
no

yes

sum = sum + pow(x, i) / fact(i)

sum = sum - pow(x, i) / fact(i)

i=i+2

Flowchart for factorial function

Output
fact(n)
Enter the Degree : 90
Enter the number of terms : 10
My_sine(90)=0.997921 is n=1 ? yes
Library sine(90)=1.000000

Enter the Degree : 30 no fact = 1


Enter the number of terms : 10
My_sine(90)=0.500059 fact = n * fact(n-1)
Library sine(90)=0.500059 return fact

Outcome:
Comparison of results of Taylors method and the results of sin() is taught.
Brief discussion on functions of math library functions.

Viva questions:

What is function?
Explain the working of keyword return.
What is the difference between actual and formal parameters?

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 65


COMPUTER PROGRAMMING LABORATORY

6. Develop an algorithm, implement and execute a C program that reads N integer


numbers and arrange them in ascending order using Bubble Sort.

/* Lab 6 - Bubble Sort */

Objective:To write a c code to sort array of integer numbers in ascending order using bubble
sort.

Algorithm
We assume list is an array of n elements. We further assume that swap function swaps the values
of the given array elements.
begin BubbleSort(list)
1. for all elements of list
2. if list[i] > list[i+1]
3 swap(list[i], list[i+1])
end if
end for
return list
end BubbleSort

#include<stdio.h>
#include<stdlib.h>
void main()
{
int a[20],n,i,j,temp;
bool swapped = false;
printf("Enter the number of elements (>0 and <=20) : ");
scanf("%d",&n);
printf("Enter the array elements : \n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(j=1;j<n; j++)
{
for(i=0;i<n-j;i++)
{
if(a[i]>=a[i+1])
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
swapped = true;
}
}

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 66


COMPUTER PROGRAMMING LABORATORY

if (swapped == false) break;


}
printf("The sorted array is : \n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}

Output
Enter the number of elements (>0 and <=20) : 8
Enter the array elements :
7 8 10 12 18 23 34 56
The sorted array is :
7 8 10 12 18 23 34 56

Outcome:

To make students understand the sorting techniques.


Usage of arrays is taught.
Concepts of nested looping are taught.

Viva questions:
What is an array?
Explain the best case and worst case of bubble sort.
What do you mean by nested looping?

7. Develop, implement and execute a C program that reads two matrices A (m x n ) and B
(p x q ) and Compute product of matrices A and B.

Objective:To write c program to perform multiplication of two matrices using multi-dimensional


arrays.
/* Lab 7 - Matrix Multiplication */

Algorithm for Matrix Multiplication

1. Matrix-Multiply(A, B)

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 67


COMPUTER PROGRAMMING LABORATORY

2. if columns [A] rows [B]

3. then error "incompatible dimensions"

4. else

5. for i =1 to rows [A]

6. for j = 1 to columns [B]

7. C[i, j] =0

8. for k = 1 to columns [A]

9. C[i, j]=C[i, j]+A[i, k]*B[k, j]

10. return C

#include<stdio.h>
#include<stdlib.h>
void main()
{
int i, j, a[10][10], b[10][10], c[10][10], k, p, q, m, n;
printf("Enter the Order of Matrix A : ");
scanf("%d%d",&m,&n);
printf("Enter %d elements of Matrix A in Row Major Order : ", m*n );
for(i=0;i<m;i++)
for(j=0;j<n;j++) scanf("%d",&a[i][j]);
printf("Enter the Order of Matrix B : ");
scanf("%d%d",&p,&q);
printf("Enter %d elements of Matrix B in Column Major Order : ", p*q);
for(j=0;j<q;j++)
for(i=0;i<p;i++) scanf("%d",&b[i][j]);
printf("The Matrix A is : \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++) printf("%d\t",a[i][j]);
printf("\n");
}
printf("The Matrix B is : \n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++) printf("%d\t",b[i][j]);
printf("\n");
}

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 68


COMPUTER PROGRAMMING LABORATORY

if(n!=p)
{
printf("Matrix multiplication is not possible");
exit(0);
}
else
{
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 resultant matrix is : \n");


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

Output
Enter the Order of Matrix A : 2 2
Enter 4 elements of Matrix A in Row Major Order : 1 2 3 4
Enter the Order of Matrix B : 3 2
Enter 6 elements of Matrix B in Column Major Order : 1 3 4 2 5 6
The Matrix A is :
1 2
3 4
The Matrix B is :
1 2
3 5
4 6
Matrix multiplication is not possible

Enter the Order of Matrix A : 2 2


Enter 4 elements of Matrix A in Row Major Order : 1 2 3 4
Enter the Order of Matrix B : 2 3
Enter 6 elements of Matrix B in Column Major Order : 1 2 3 4 5 6

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 69


COMPUTER PROGRAMMING LABORATORY

The Matrix A is :
1 2
3 4

The Matrix B is :
1 3 5
2 4 6

The resultant matrix is :


5 11 17
11 25 39

Outcome:
Concept of multi-dimensional array is taught.
Students understand the declaration and initialization of two dimensional arrays.

Viva questions:
How can we read and write two dimensional arrays.
What is necessary condition to perform matrix multiplication.

Binary Search

Binary search works on sorted arrays. A binary


search begins by comparing the middle element of
the array with the target value. If the target value
matches the middle element, its position in the array
is returned. If the target value is less than or greater
than the middle element, the search continues in the
lower or upper half of the array, respectively,
eliminating the other half from consideration.

Algorithm

Given an array A of n elements with values or records A0 ... An1, sorted such that A0 ... An1,
and target value T, the following subroutine uses binary search to find the index of T in A.
1. Set L to 0 and R to n 1.
2. If L > R, the search terminates as unsuccessful.
3. Set m (the position of the middle element) to the floor of (L + R)/2.
4. If Am < T, set L to m + 1 and go to step 2.
5. If Am > T, set R to m 1 and go to step 2.
6. Now Am = T, the search is done; return m.
This iterative procedure keeps track of the search boundaries via two variables L & R.

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 70


COMPUTER PROGRAMMING LABORATORY

Output

How many Names ? 5


Please enter the names in Alphabetical Order :
arjun
bheema
budda
mahaveer
rama
Please Enter the name you want to search in the above list : mahaveer
Search Successful... mahaveer is present in position 4

How many Names ? 5


Please enter the names in Alphabetical Order :
arjun
bheema
budda
mahaveer
rama
Please Enter the name you want to search in the above list : gandhi
Search Unsuccessful...

2. Develop, implement and execute a C program to search a Name in a list of names using
Binary searching Technique.

/* Lab 8 - Binary Search on list of names */

#include<stdio.h>
#include<string.h>
void main()
{
char name[30][20];
char key[20];
int n,i,mid,low,high,found=0;
printf("\nHow many Names ? ");
scanf("%d",&n);
printf("Please enter the names in Alphabetical Order : \n");
for(i=0;i<n;i++)
{
scanf("%s",name[i]);
}
printf("Please Enter the name you want to search in the above list : ");
scanf("%s",key);
low=0;
high=n-1;
while(low<=high && ! found)
{

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 71


COMPUTER PROGRAMMING LABORATORY

mid=(low+high)/2;
if(strcmp(name[mid],key)==0)
found=1;
else if(strcmp(name[mid],key)<0)
low=mid+1;
else
high=mid-1;
}
if(found==1)
{
printf("\nSearch Successful... %s is present in position %d", key, mid+1);
}
else
{
printf("\nSearch Unsuccessful...");
}
}

Algorithm for 9a
1. Scan Entered String From Left to Right, Character by Character.
2. In Each Iteration Copy One Character to New String Variable.

3. As soon as Source or Original String Ends, Process of Copying Character Stops but we still
havent Copied NULL Character into new String, So Append Null Character to New String.

Output for 9a

Please Enter a String : ATME College of Engineering


Copied String is : ATME College of Engineering

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 72


COMPUTER PROGRAMMING LABORATORY

3. Write and execute a C program that

9a. Implements string copy operation STRCOPY(str1,str2) that copies a string str1 to
another string str2 without using library function.

9b. Read a sentence and print frequency of vowels and total count of consonants.

/* 9a - string copy operation without using strcpy */

#include<stdio.h>
void STRCOPY(char *str1, char *str2);
void main()
{
char str1[200], str2[100];
printf("Please Enter a String : ");
gets(str1);
STRCOPY(str1, str2);
printf("Copied String is : %s", str2);
}

void STRCOPY(char *str1, char *str2)


{
int i=0;
while(str1[i]!='\0')
{

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 73


COMPUTER PROGRAMMING LABORATORY

str2[i] = str1[i];
i++;
}
str2[i] = '\0';
}

Algorithm for 9b

1. Given a sentence, we have to count the number of vowels, consonants in it and print the
counts on screen.
2. English has five proper vowel letters (A, E, I, O, U) and all alphabets except these characters
are consonants.
3. Using a for loop we traverse input string from index 0 to length of string.
4. We keep separate counter for counting the occurrence of each of vowels.
5. Whenever a vowel is found the corresponding counter is incremented.
6. We use separate counter for consonant.
7. Whenever a consonant is encountered in the string the value of the consonant counter is
incremented.
8. At last we print the values of all the five vowel counters and the value of consonant counter.

Output for 9b

Please enter a sentence : A brown cunning fox quickly jumps over the lazy dog
Frequency of a = 2
Frequency of e = 2
Frequency of i = 2
Frequency of o = 4
Frequency of u = 3
Frequency of Consonants = 29

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 74


COMPUTER PROGRAMMING LABORATORY

/* Lab 9b - Program that reads a sentence and prints frequency of each of the vowels and
total count of consonants.*/

#include<stdio.h>
#include<string.h>
#include<ctype.h>
void main()
{
int na=0, ne=0, ni=0, no=0, nu=0, nc=0, len, i;
char str[100];
printf("Please enter a sentence : ");
gets(str);
len=strlen(str);
for(i=0;i<len;i++)
{
if( isdigit(str[i]) || ispunct(str[i]) || str[i]==' ')
{
continue;
}
switch(str[i])
{
case 'a':
case 'A': na++;
break;
case 'e':

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 75


COMPUTER PROGRAMMING LABORATORY

case 'E': ne++;


break;
case 'i':
case 'I': ni++;
break;
case 'o':
case 'O': no++;
break;
case 'u':
case 'U': nu++;
break;
default: nc++;
break;
}
}
printf("Frequency of a = %d\n",na);
printf("Frequency of e = %d\n",ne);
printf("Frequency of i = %d\n",ni);
printf("Frequency of o = %d\n",no);
printf("Frequency of u = %d\n",nu);
printf("Frequency of Consonants = %d\n",nc);
}
Flowchart for driver program Flowchart for function rightrotation(x, n)

Start rightrotation(x,n)r

Read the values for x and n i=1

no
res = rightrotation(x, n) return x
is i<=n?
yes
Print the value of res
no

is x mod 2=0?
Stop
yes

rightshift x by 1 bit
i.e., x = x >>1

rightshift x by 1 bit and


add 32768 to x
i.e., x = x >>1
x = x + 32768

i=i+1

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 76


COMPUTER PROGRAMMING LABORATORY

Output for 10a


Enter the number : 2
Enter the number of right rotations : 1
(2,1) = 1

Enter the number : 64


Enter the number of right rotations : 4
(64,4) = 4

Enter the number : 35


Enter the number of right rotations : 3
(35,3) = 24580

4.

10a. 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.

10b. 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 range.

/* LAB 10a - Right Rotation */

#include<stdio.h>
unsigned int rightrotation(unsigned int x,int n);
void main()
{
int n;
unsigned int x,res;
printf("Enter the number : ");
scanf("%u",&x);
printf("Enter the number of right rotations : ");
scanf("%d",&n);
res=rightrotation(x,n);
printf("(%u,%d)=%u",x,n,res);

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 77


COMPUTER PROGRAMMING LABORATORY

unsigned int rightrotation(unsigned int x, int n)


{
int i;
for(i=1;i<=n;i++)
{
if((x%2)==0)
{
x=x>>1;
}
else
{
x=x>>1;
x=x + 32768;
}
}
return x;
}

Flowchart for isprime(n) function

isprime(n) isprime function returns 0, if n is not a


prime number
It returns 1, if n is a prime number
j=2

is j<sqrt(n)? is n mod j =0? yes


yes
return 0

no no

return 1 j = j +1

Algorithm to print the prime number series from n1 to n2


1. Start
2. Read the values n1, n2
3. Initialize i=n1
4. Using isprime function check whether i is prime number, if it is a prime number print it.
5. Increment i by 1, i = i + 1

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 78


COMPUTER PROGRAMMING LABORATORY

6. If i <= n2 then goto step 4


7. Stop

Output for 10b

Enter a range of numbers n1 & n2 : 10 50

Prime numbers within the range 10 and 50 are


11 13 17 19 23 29 31 37 41 43 47

There are total of 11 prime numbers within the range 10 and 50

/* Lab 10b - Prime numbers in the given Range */

#include<stdio.h>
#include<math.h>
int isprime(int m);
void main()
{
int i, n1, n2, count=0;
printf("Enter a range of numbers n1 & n2 : ");
scanf("%d%d",&n1,&n2);
printf("Prime numbers within the range %d and %d are \n", n1, n2);
for(i=n1;i<=n2;i++)
{
if(isprime(i))
{
count=count+1;
printf("%d\t",i);
}
}
printf("\nThere are total of %d prime numbers within the range %d and
%d\n",count,n1,n2);
}

int isprime(int m)
{
int i;

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 79


COMPUTER PROGRAMMING LABORATORY

for(i=2;i<=sqrt(m);i++)
{
if(m%i==0) return 0;
}
return 1;
}

Flowchart for recursive fact(n) function

fact(n) Algorithm for factorial function


1. if n=1 then fact=1. Goto step 3
2. if n>1 then fact = n * fact(n-1)
is n=1 ? 3. Return the value of fact
yes

fact = 1
no

fact = n * fact(n-1)
return fact

Algorithm to calculate nCr, the binomial coefficient

1. Start
2. Read the values of n and r
3. Calculate ncr = fact(n) / (fact(n-r)*fact(r))
4. Print the value of ncr
5. Stop

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 80


COMPUTER PROGRAMMING LABORATORY

Output

Enter the value for n : 7


Enter the valur for r (<=7) : 5
The Binomial Coefficient is : 21

Enter the value for n : 5


Enter the valur for r (<=5) : 3
The Binomial Coefficient is : 10

5. 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 nCr. Tabulate the results for
different values of n and r with suitable messages.

/* Lab 11 - To compute the binomial coefficient nCr. */

#include <stdio.h>
int fact(int n);
void main()
{
int n, r, ncr;
printf("Enter the value for n : ");
scanf("%d",&n);
printf("Enter the value for r (<=%d) : ", n);
scanf("%d",&r);
ncr = fact(n) / (fact(n-r)*fact(r));
printf("The Binomial Coefficient is : %d", ncr);

}
int fact(int n)
{
if(n==0) return 1;
return n * fact(n-1);
}

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 81


COMPUTER PROGRAMMING LABORATORY

Prerequisites

1. Create a text file by name studentname.txt with the following contents


abc
xyz
pqr

2. Create another text file by name usn.txt with the following contents
1001
1002
1003

Algorithm

1. Start
2. Open the file studentname.txt in read mode
3. Open the file usn.txt in read mode.
4. Open the file output.txt in write mode.
5. Read a name from first file, corresponding usn from second file, write name and usn to
output.txt file.
6. Repeat step 5 until end of file is reached for either first file or for the second file.
7. Stop

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 82


COMPUTER PROGRAMMING LABORATORY

6. Given two university information files "studentname.txt" and "usn.txt" that contains
students Name 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 shown below. Display the contents of output file "output.txt" on to
the screen.
Student Name USN
Name 1 USN1
Name 2 USN2
. .
. .
/* Lab 12 - Reading File contents and Copying to another file */

#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp1, *fp2, *fp3;
char name[20];
int usn;

fp1=fopen("studentname.txt","r");
if(fp1==NULL)
{
printf("Error in opening the name file \n");
exit(0);
}

fp2=fopen("usn.txt","r");

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 83


COMPUTER PROGRAMMING LABORATORY

if(fp2==NULL)
{
printf("Error in opening the usn file \n");
exit(0);
}

fp3=fopen("output.txt","w");
if(fp3==NULL)
{
printf("Error in opening the output file \n");
exit(0);
}

/* Program continues on next page */

Output

Before executing this program

1. Create a file by name studentname.txt with the following contents


abc
xyz
pqr

2. Create another file by name usn.txt with the following contents


1001
1002
1003

3. Execute the program

4. A file by name output.txt will be created.

5. The contents of the output.txt are printed on the screen as follows:

STUDENTNAME USN
abc 1001
xyz 1002
pqr 1003

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 84


COMPUTER PROGRAMMING LABORATORY

/* Program continued from previous page */

for(;;)
{
if(fscanf(fp1,"%s",&name)>0)
{
if(fscanf(fp2,"%d",&usn)>0)
{
fprintf(fp3,"%s\t%d\n",name,usn);
}
else break;
}
else break;
}

fclose(fp1);
fclose(fp2);
fclose(fp3);

fp3=fopen("output.txt","r");
if(fp3==NULL)
{
printf("Error in opening the output file \n");
exit(0);
}

printf("STUDENTNAME\tUSN\n");
while(fscanf(fp3,"%s%d",&name,&usn)>0)

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 85


COMPUTER PROGRAMMING LABORATORY

{
printf("%s\t%d\n",name,usn);
}
fclose(fp3);
}

Algorithm
1. Start
2. Read n, the number of students
3. Read the details of n students as per the structure given below
4. Print the read details
5. Enter the student name to be searched in the list
6. Sequentially compare the student name with the students name in the array of structures.
7. If there is a match, print the marks scored by that student, else print student not found
8. Stop

struct student
{
int rollno;
char name[20]; Student record using
int marks; Structure
char grade[5];
};

struct student s[20]; Array of student


Structures
Output
How many students details has to be entered ? 3
Enter the roll no : 1234
Enter the name : abcde
Enter the marks : 85
Enter the grade : A

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 86


COMPUTER PROGRAMMING LABORATORY

Enter the roll no : 1235


Enter the name : xyz
Enter the marks : 90
Enter the grade : A

Enter the roll no : 1236


Enter the name : pqr
Enter the marks : 70
Enter the grade : B

Details of students are as follows :


ROLL NUMBER NAME MARKS GRADE
1234 abcde 85 A
1235 xyz 90 A
1236 pqr 70 B

Which student marks has to be displayed ? xyz


Marks of xyz is 90

7. 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). Assume
appropriate data type for each field. Print the marks of the student, given the student
name as input.
/* LAB 13 - Array of Structures, Reading, Searching and Printing student details */
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
struct student
{
int rollno;
char name[20];
int marks;
char grade[5];
};
struct student s[20];
char name2[20];
int i,j,n;
printf("How many students details has to be entered ? ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the roll no : ");
scanf("%d",&s[i].rollno);
printf("Enter the name : ");
scanf("%s",&s[i].name);
printf("Enter the marks : ");

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 87


COMPUTER PROGRAMMING LABORATORY

scanf("%d",&s[i].marks);
printf("Enter the grade :");
scanf("%s",&s[i].grade);
}
printf("Details of students are as follows : \n");
printf("ROLL NUMBER\tNAME\tMARKS\tGRADE\n\n");
for(i=0;i<n;i++)
printf("%d\t\t%s\t%d\t%s\t\n",s[i].rollno,s[i].name,s[i].marks,s[i].grade);
printf("Which student marks has to be displayed ? ");
scanf("%s",&name2);
for(i=0;i<n;i++)
{
if((strcmp(s[i].name,name2))==0)
{
printf("Marks of %s is %d\n\n", s[i].name,s[i].marks);
exit(0);
}
}
printf("Student not found\n");
}

Algorithm
1. Start
2. Read the value for n.
3. Read all the n values in an array a
4. sum = a[0] + a[1] + .. + a[n-1]
5. mean = sum / n
6. sum1 = (a[0] mean)2 + (a[1] mean)2 + + (a[n-1] mean)2
7. stddev = sqrt(sum1/n)
8. print the values of sum, mean, standard deviation
9. Stop
In the program instead of directly using the variables, we have to make use of pointers.

Output

Enter the number of elements : 10

Enter the 10 elements :


10 20 15 8 7 9 6 15 12 25

The Sum is = 127.000000


Mean = 12.700000
Variance = 33.610001

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 88


COMPUTER PROGRAMMING LABORATORY

Standard Deviation = 5.797413

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

/* Lab 14 - To find Sum, mean and standard deviation of all elements stored in an array of n real
numbers.*/

#include<stdio.h>
#include<math.h>
void main()
{
int n,i;
float x[20], sum, mean, variance, deviation;
printf("Enter the number of elements : ");
scanf("%d", &n);
printf("Enter the %d elements : \n", n);
for(i=0;i<n;i++) scanf("%f", &x[i]);
sum=0;
for(i=0;i<n;i++) sum = sum + *(x+i);
mean = sum/n;
printf("The Sum is = %f \n", sum);
sum=0;
for(i=0;i<n;i++) sum = sum + (*(x+i) - mean) * (*(x+i)-mean);
variance = sum/n;
deviation = sqrt(variance);
printf("Mean = %f\n", mean);
printf("Variance = %f\n", variance);
printf("Standard Deviation = %f\n", deviation);

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 89


COMPUTER PROGRAMMING LABORATORY

VIVA QUESTIONS:

1. What are the general characteristics of C?


2. Explain the Basic structure of C program.
3. What are pre-processor Directives?
4. List the rules to define the valid Identifiers.
5. What are Identifiers?
6. What are Keywords?
7. What are Constants? How they differ from Variables?
8. List the various types of Constants with an example.
9. Describe the String Constant.
10. Explain the various data types supported by C.
11. What is an Operator?
12. List the various types of operators supported by C.
13. Describe the Arithmetic operators in C.
14. Describe the Logical operators in C.
15. Describe the Assignment operators in C.
16. Describe the Relational operators in C.
17. Describe the Arithmetic operators in C.
18. Describe the Arithmetic operators in C.
19. Describe the Conditional operators in C.
20. Describe the Bitwise operators in C.
21. List the commonly used input/output functions in C.
22. What is a name of standard input/output header file?
23. What is the purpose of printf function?
24. What is the purpose of escape Sequences? Explain any two.
25. What is the purpose of putchar function?
26. What is the purpose of scanf function?

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 90


COMPUTER PROGRAMMING LABORATORY

27. What is the purpose of getchar function?


28. What is the purpose of gets function?
29. What do you mean by branching?
30. What is the purpose of control statements in C? List various control statements in C?
31. What is Variable? Describe the array variable.
32. How and where are the variables declared?
33. What is the purpose of if-else statement? Give its Syntax.
34. Describe the different forms of if-else statement.
35. What is nested-if statement?
36. What is the purpose of switch statement?
37. Explain the rules associated with the use of the Switch statement.
38. What is the purpose of Break statement?
39. Compare the switch statement with the nested if statements.
40. What is meant by looping? Describe two different forms of looping .
41. What is the purpose of for statement?
42. Explain the syntax of for statement.
43. What the purpose of nested for loops?
44. What the purpose of while statements?
45. What the purpose of do- while statements? How it differs from while statement?
46. What is the purpose of continue statement?
47. In what way does an array differ from an ordinary variable?
48. Draw and explain the general structure of an array?
49. What do you mean by array declaration?
50. What is array initialization? State various ways of array initialization.
51. What is string? How it is declared and initialized?
52. Explain the functions used to read strings.
53. Explain the functions used to display string on the screen.
54. List the most commonly used string handling functions and explain their usage.
55. What is function? What is its purpose?
56. What do you mean by modular programming? What are its advantages?
57. Explain the three elements of a function.
58. Write a note on scope of function.
59. What are arguments or passing parameters? What is their purpose?
60. What do you mean by actual parameters and formal parameters?
61. Explain the two methods of passing arguments to a function.
62. What is recursion? How is it possible to write recursive function?
63. Explain the process of passing an individual element of an array to a function with
example.
64. Explain the process of passing the entire array to a function with example.
65. What is a Structure? How does a structure differ from an array?
66. What is a structure member? What is a relationship between a structure member and a
structure?
67. Describe the syntax of defining a composition of structure.
68. How is structure variable being declared?
69. How is structure initialized?
70. How is array of structure initialized?

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 91


COMPUTER PROGRAMMING LABORATORY

71. How is structure member accessed and processed?


72. What is nested structure?
73. What is the purpose of typedef feature?
74. How can an entire structure be passed to a function?
75. How can structure members be passed to a function?
76. What is file pointer? What is its purpose?
77. Explain the file modes supported by C for text files.
78. Explain the syntax for opening and closing the file.
79. Explain how to read and write to character in the file.
80. Explain the fscanf and fprintf functions. Compare them with scanf and printf functions.
81. Write a note on error handling.
82. Write a short note on fseek().
83. What is a pointer?
84. What is pointer variable? What is its purpose?
85. How is pointer variable declared?
86. Explain the process of initialization of pointer variable.
87. How is pointer variable accessed?
88. Write a short note on operations on pointers.
89. What do you mean by pointer to pointer?
90. How can a pointer variable be passed to a function?
91. How can a function return a pointer to its calling routine?
92. What is meant by dynamic memory allocation? List the various library functions used for
the dynamic memory allocation.
93. Compare: static memory allocation Vs dynamic memory allocation.
94. What are the functions of C processor?
95. What is nested macro?
96. Define data structure.
97. What are primitive and non primitive data structures?
98. What are linear and non linear data structures?
99. What are static and dynamic data structures?
100 .What is an abstract data type?

VERSION 1.1/SEP-16 DEPT OF CSE, ATMECE Page 92

You might also like