Professional Documents
Culture Documents
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.
8. Develop, implement and execute a C program to search a Name in a list of names using
Binary searching Technique.
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.
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
2) it stores data,
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.
All data and instructions are stored here before and after processing.
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
2) control 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.
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.
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.
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.
Heat sink
Inductor
Capacitor
CPU Socket
Northbridge
Screw hole
Memory slot
Super I/O
Floppy connection
RAID
FWH
Southbridge
USB headers
Jumpers
Integrated circuit
1394 headers
SPDIF
CD-IN
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.
AT
ATX
Baby AT
BTX
DTX
LPX
Full AT
Full ATX
microATX
NLX
How
many
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
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
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.
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
nodes (computers)
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.
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.
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.
Broadcast - In a broadcast, a node sends out a packet that is intended for transmission to
all other nodes on the network.
Network Topologies
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:
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).
Although other network technologies exist, IEEE 802 networks including the Ethernet variants
have achieved near-ubiquity since the mid-1990s.
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.
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
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.\
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) 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.
Type of DRAM on the module can greatly affect performance and cause the most confusion
when designing or configuring a system.
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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
One of the most common DVD's is the single-sided, single-layer disc, capable of holding
4.7 GB.
Although rare, the double-sided, double-layer disc is capable of holding up to 17.08 GB.
Mitsubishi, Pioneer, Toshiba, and several others) and develop a single video disc format.
Together, the two groups developed the DVD format.
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.
IBM/PC keyboards
AT Keyboard - 84 keys
Apple keyboards
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.
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.
Note: The above count includes the Windows key and Menu key (3 keys) and does not count the
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
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.
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.
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.
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.
Cordless (Wireless)
Footmouse
J mouse
Joystick
Mechanical
Optical
Touchpad (Glidepoint)
Trackball
TrackPoint
Bluetooth
Infrared
PS/2 Port
Serial Port
USB
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.
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
Inkjet printer
Laser printer
LED printer
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
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
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
Flowchart
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.
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.
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.
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.
Can be proven.
Computers use algorithms to convert data (e.g. converting decimal into binary).
Encryption to encrypt and decrypt information and keep data safe is an algorithm.
There are dozens of sort algorithms that are used to sort data.
Data compression for getting information faster (e.g. YouTube video) use algorithms.
Pseudocode
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.
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,
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:
Print "passed"
else
Print "failed"
C Programming constructs
if statement
Syntax of if
if (testExpression)
{
// statements
}
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.
while loop
while (testExpression)
{
//code
}
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.
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.
The code block (loop body) inside the braces is executed once.
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 for loop is commonly used when the number of iterations is known.
It is sometimes desirable to skip some statements inside the loop or terminate the loop
immediately without checking the test expression.
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.
continue Statement
The continue statement skips some statements inside the loop. The continue statement is used
with decision making statement such as if...else.
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)
{
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.
C 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.
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.
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.
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.
7. Compute x1 = x2 = -b / (2*a), the two real and equal 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
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:
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.
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
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
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)
{
temp = sqroot;
sqroot = (number/sqroot + sqroot) / 2;
}
printf("Square root of %f is %f \n", number, sqroot);
}
Tracing Example
Start
The square root of 30 is 5.477225575
sqroot = number / 2
temp = 0
Flowchart for 3a
no
temp = sqroot
sqroot = (number/sqroot + sqroot) / 2
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.
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;
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
Viva questions:
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.
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--)
{
Output
Outcome:
The different methods for evaluating the polynomial are taught.
The usage of looping statement such as for loop is used.
Viva questions:
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.
Objective: To understand the logic proposed by Taylor for the evaluation of polynomial and
compare the result with standard library functions.
#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));
}
int fact(int n)
{ Start
if(n==0) return 1;
return n*fact(n-1);
} Read the values for x and n
my_sine(x, n)
Print the values of res and the result obtained from std. library function sine
is i<=n? no
return sum
yes
is (i-1) mod 4=0?
no
yes
i=i+2
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
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?
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;
}
}
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:
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.
1. Matrix-Multiply(A, B)
4. else
7. C[i, j] =0
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");
}
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];
}
}
}
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
The Matrix A is :
1 2
3 4
The Matrix B is :
1 3 5
2 4 6
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
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.
Output
2. Develop, implement and execute a C program to search a Name in a list of names using
Binary searching Technique.
#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)
{
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
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.
#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);
}
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
/* 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':
Start rightrotation(x,n)r
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
i=i+1
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.
#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);
no no
return 1 j = j +1
#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;
for(i=2;i<=sqrt(m);i++)
{
if(m%i==0) return 0;
}
return 1;
}
fact = 1
no
fact = n * fact(n-1)
return fact
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
Output
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.
#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);
}
Prerequisites
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
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");
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);
}
Output
STUDENTNAME USN
abc 1001
xyz 1002
pqr 1003
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)
{
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];
};
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
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);
VIVA QUESTIONS: