Você está na página 1de 75

Computer Programming Lab Manual 2014-2015

ACHARYA INSTITUTE OF TECHNOLOGY


Soladevanahalli, Bangalore - 560107

(Affiliated to Visvesvaraya Technological University, Belgaum)

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

COMPUTER PROGRAMMING LABORATORY


MANUAL
14CPL16/14CPL26
As per VTU Syllabus 2014
For
I / II semester B E
Compiled By
Latharani T.R. and Manjunath G.S.
Assistant Professor
Dept. of Computer Science & Engineering
Acharya Institute of Technology
Bangalore-560107

Computer Programming Lab Manual 2014-2015

COMPUTER PROGRAMMING LABORATORY


.

Subject Code:14CPL16/14CPL26
Hours/Week:03
Total Hours:42

IA Marks:25
Exam. Hours:03
Exam. Marks:50

Sl
No.

Program Name

Write-up on Functional block diagram of Computer, CPU, Buses, Mother


Board, Chip sets, Operating System & types of OS, Basics of Networking &
Topology and NIC.

Page
No.

PART A : Demonstration of Personal Computer and its Accessories


Demonstration and Explanation on Disassembly and Assembly of a Personal Computer by
the faculty-in-charge. Students have to prepare a write-up on the same and include it in the
Lab record and evaluated.

1
2
3
4
5
6
7

Write-up onRAM, SDRAM, FLASH memory, Hard disks, Optical media, CDROM/R/RW, DVDs, Flash drives, Keyboard, Mouse, Printers and
Plotters.Introduction to flowchart, algorithm and pseudo code.
PART B: Problem Solving in C
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.
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.
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.
Design and develop an algorithm for evaluating the polynomial f(x) = a4x4+
a3x3 +a2x2+a1x+a0 for a given value of x and its coefficients using Horners
method. Implement a C program for the developed algorithm and execute for
different sets of values of coefficients and x.
Draw the flowchart and write C Program to compute Sin(x) using Taylor
series approximation given by Sin(x) = x - (x3/3!) + (x5/5!) - (x7/7!) + .
Compare the result with the built- in Library function and print both the
results with appropriate messages.
Develop an algorithm, implement and execute a C program that reads N
integer numbers and arrange them in ascending order using Bubble Sort.
Develop, implement and execute a C program that reads two matrices A (m x
n) and B (p x q) and Compute the product A and B. Read matrix A in row
major order and matrix B in column major order. Print both the input

Computer Programming Lab Manual 2014-2015

8
9

10

11

12

13
14

matrices and resultant matrix with suitable headings and in matrix format.
Program must check the compatibility of orders of the matrices for
multiplication. Report appropriate message in case of incompatibility.
Develop, implement and execute a C program to search a Name in a list of
names using Binary searching technique.
Write and execute a C program that
i. Implements string copy operation STRCOPY (str1, str2) that copies a
string str1 to another string str2 without using library function.
ii. Reads a sentence and prints frequency of each of the vowels and total
count of consonants.
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 ranges.
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 C.
Tabulate the results for different values of n and r with suitable messages.
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
.
.
.
.
.
.
Write a C program to maintain a record of n student details using an array
of structures with four fields (Roll number, Name, Marks, and Grade). Each
field is of an appropriate data type. Print the marks of the student given
student name as input.
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.
Viva-Voce Questions

Reference Book :
ReemaThareja, Computer Fundamentals and Programming in C ,Oxford Press, 2012.

Computer Programming Lab Manual 2014-2015


Practical Examination Procedure:
1. All laboratory experiments (Fourteen) are to be included for practical examination.
2. Students are allowed to pick one experiment from the lot.
3. Strictly follow the instructions as printed on the cover page of answer script for
breakup of marks.
4. Change of experiment is allowed only once and 15% Marks allotted to the procedure
part to be made zero.
Sl. No.
1
2
3
4
5

Activity
Writing the assigned program along with Algorithm and Flowchart
Execution of the program and displaying the output ina proper format
Viva-Voce
Total Maximum Marks
Minimum passing Marks (40% of Total Maximum Marks)

Max Marks
10
30
10
50
20

Computer Programming Lab Manual 2014-2015


A DIGITAL COMPUTER
Computer programs may be written in High level languages like Pascal, FORTRAN and
COBOL etc., some programmer also writes assembly language to carry out the desired task.
Hardware is the tangible parts of a computer like the keyboards, printers, disk drives and
the monitor among others. Software is the intangible part of the computer that provides
instructions for the hardware to perform and it includes the operating system, utilities,
word processor, database management systems and the spreadsheets.

Hardware of a computer system refers to any physical, electrical, electro-mechanical


components of the computer which we can touch and see. For example keyboard, mouse,
cabinet of computer is considered as hardware.
Software is a set of programs, which are designed to perform a well-defined function. A
program is a sequence of instructions written to solve a particular problem.
There are two types of system software:
System Software
Application Software
System Software
The system software is a collection of programs designed to operate, control and extend
the processing capabilities of the computer itself. System software is generally prepared by
computer manufacturers.
This software comprise of programs written in low level languages which interact with the
hardware at a very basic level. System software serves as the interface between hardware
and the end users.
Some examples of system software are Operating System, Compilers, Interpreter,
Assemblers, linkers, loaders etc.

Features of System Software are the following:


Close to system.
Fast in speed.
Difficult to design.
Difficult to understand.
Less interactive.
Smaller in size.
Difficult to manipulate.
Generally written in low-level language.

Computer Programming Lab Manual 2014-2015


Application Software
Application software is the software that is designed to satisfy a particular need of a
particular environment. All software prepared by us in the computer lab can come under
the category of Application Software.
Application software may consist of a single program, such as a Microsoft's notepad for
writing and editing simple text. It may also consist of a collection of programs, often called
a software package, which work together to accomplish a task, such as a spreadsheet
package.
Examples of Application software are the following:
Payroll Software
Income Tax Software
Student Record Software
Railways Reservation Software
Inventory Management Software
Microsoft Office

Features of Application Software


It is close to user.
It is easy to design.
More interactive.
Slow in speed.
Generally written in high-level language.
Easy to understand.
Easy to manipulate and use.
Bigger in size and requires large storage space.

Hardware represents the physical and tangible components of the computer, i.e., the
components that can be seen and touched.

Computer Programming Lab Manual 2014-2015


Examples of Hardware are following:
Input devices -- keyboard, mouse, etc.
Output devices -- printer, monitor, etc.
Secondary storage devices -- Hard disk, CD, DVD, etc.
Internal components -- CPU, motherboard, RAM, etc.

Relationship between Hardware and Software


Mutually dependent. Both of them must work together to make computer produce a
useful output.
Software cannot be utilized without supporting hardware.
Hardware without set of programs to operate upon cannot be utilized and is useless.
To get a particular job done on the computer, relevant software should be loaded into
the hardware.
Hardware is a one-time expense.
Software development is very expensive and is a continuing expense.
Different software can be loaded on hardware to run different jobs.
Software acts as an interface between the user and the hardware.
If hardware is the 'heart' of a computer system, then software is its 'soul'. Both are
complimentary to each other.
Information Processing Life cycle
All types of computer follows a same basic logical structure and perform the following five
basic operations for converting raw input data into information useful to their users

Sl. No.

Operation

Description

Receive Input

The process of entering data and instructions into the computer


system through input devices like key board, mouse etc.

Output
Information

The process of producing useful information or results for the user,


such as a printed report or visual display on an output devices like
monitor, printer etc.

4
5

Processing
Data

Store Data

Performing arithmetic, logical operations on data in order to


convert them into useful information in the CPU.

Saving data and instructions in the memory so that they are


available for processing as and when required.

Control
the Direct the manner and sequence in which all of the above
workflow
operations are performed.

CPU
Consists of the following features:
CPU is considered as the brain of the computer.
CPU performs all types of data processing operations.
It stores data, intermediate results and instructions (program).

Computer Programming Lab Manual 2014-2015


It controls the operation of all parts of computer.
CPU itself has following three components.
Memory Or Storage Unit
Control Unit
ALU(Arithmetic Logic Unit)

ALU (Arithmetic Logic Unit)


This unit consists of two subsections namely
Arithmetic section
Logic Section

Arithmetic section
Function of Arithmetic section is to perform arithmetic operations like addition,
subtraction, multiplication and division. All complex operations are done by making
repetitive use of above operations.
Logic section
Function of logic section is to perform logic operations such as comparing, selecting,
matching and merging of data.

Basic units of a computer


Memory or Storage Unit
A memory is just like a human brain. It is used to store data and instruction. Computer
memory is the storage space in computer where data is to be processed and instructions
required for processing are stored. The memory is divided into large number of small parts.
Each part is called cell. Each location or cell has a unique address which varies from zero to
memory size minus one. For example if computer has 64k words, then this memory unit
has 64 * 1024=65536 memory location. The address of these locations varies from 0 to
65535. This unit can store instruction, data and intermediate results. This unit supplies
information to the other units of the computer when needed.
Function of Memory Unit is
It stores all the data to be processed and the instructions required for processing.

Computer Programming Lab Manual 2014-2015


It stores intermediate results of processing.
It stores final results of processing before these results are released to an output
device.
All inputs and outputs are transmitted through main memory.

Memory is primarily of three types


Cache Memory
Primary Memory/Main Memory
Secondary Memory

Cache Memory
Cache memory is a very high speed semiconductor memory which can speed up CPU. It acts
as a buffer between the CPU and main memory. It is used to hold those parts of data and
program which are most frequently used by CPU. The parts of data and programs are
transferred from disk to cache memory by operating system, from where CPU can access
them.
Advantage
Cache memory is faster than main memory.
It consumes less access time as compared to main memory.
It stores the program that can be executed within a short period of time.
It stores data for temporary use.
Disadvantage
Cache memory has limited capacity.
It is very expensive.

Primary Memory (Main Memory)


Primary memory holds only those data and instructions on which computer is currently
working. It has limited capacity and data get lost when power is switched off. It is generally
made up of semiconductor device. These memories are not as fast as registers. The data
and instruction required to be processed earlier reside in main memory. It is divided into
two subcategories RAM and ROM. Characteristic of Main Memory are
These are semiconductor memories.
It is known as main memory.
Usually volatile memory.
Data is lost in case power is switch off.
It is working memory of the computer.
Faster than secondary memories.
A computer cannot run without primary memory.

A RAM constitutes the internal memory of the CPU for storing data, program and program
result. It is read/write memory. It is called random access memory (RAM). Since access
time in RAM is independent of the address to the word that is, each storage location inside
the memory is as easy to reach as other location & takes the same amount of time. We can

Computer Programming Lab Manual 2014-2015


reach into the memory at random & extremely fast but can also be quite expensive. RAM is
volatile, i.e. data stored in it is lost when we switch off the computer or if there is a power
failure. Hence a backup uninterruptible power system (UPS) is often used with computers.
RAM is small, both in terms of its physical size and in the amount of data it can hold. RAM is
of two types
Static RAM (SRAM)
Dynamic RAM (DRAM)
Static RAM (SRAM)

SRAM Chip
The word static indicates that the memory retains its contents as long as power remains
applied. However, data is lost when the power gets down due to volatile nature. SRAM
chips use a matrix of 6-transistors and no capacitors. Transistors do not require power to
prevent leakage, so SRAM need not have to be refreshed on a regular basis. Because of the
extra space in the matrix, SRAM uses more chips than DRAM for the same amount of
storage space, thus making the manufacturing costs higher. Static RAM is used as cache
memory needs to be very fast and small. Characteristic of the Static RAM
It has long data lifetime
There is no need to refresh
Faster
Used as cache memory
Large size
Expensive
High power consumption

Dynamic RAM (DRAM)


DRAM, unlike SRAM, must be continually refreshed in order for it to maintain the data.
This is done by placing the memory on a refresh circuit that rewrites the data several
hundred times per second. DRAM is used for most system memory because it is cheap and
small. All DRAMs are made up of memory cells. These cells are composed of one capacitor
and one transistor. Characteristic of the Dynamic RAM
It has short data lifetime
Need to refresh continuously
Slower as compared to SRAM
Used as RAM

Computer Programming Lab Manual 2014-2015


lesser in size
Less expensive
Less power consumption

Read Only Memory (ROM)


ROM stands for Read Only Memory, the memory from which we can only read but cannot
write on it. This type of memory is non-volatile. The information is stored permanently in
such memories during manufacture. A ROM, stores such instruction as are required to start
computer when electricity is first turned on, this operation is referred to as bootstrap. ROM
chip are not only used in the computer but also in other electronic items like washing
machine and microwave oven.
Following are the various types of ROM

MROM (Masked ROM)


The very first ROMs were hard-wired devices that contained a pre-programmed set of data
or instructions. These kinds of ROMs are known as masked ROMs. It is inexpensive ROM.
PROM (Programmable Read only Memory)
PROM is read-only memory that can be modified only once by a user. The user buys a
blank PROM and enters the desired contents using a PROM programmer. Inside the PROM
chip there are small fuses which are burnt open during programming. It can be
programmed only once and is not erasable.

EPROM (Erasable and Programmable Read Only Memory)


The EPROM can be erased by exposing it to ultra-violet light for a duration of up to 40
minutes. Usually, a EPROM eraser achieves this function. During programming an electrical
charge is trapped in an insulated gate region. The charge is retained for more than ten
years because the charge has no leakage path. For erasing this charge, ultra-violet light is
passed through a quartz crystal window (lid). This exposure to ultra-violet light dissipates
the charge. During normal use the quartz lid is sealed with a sticker.
EEPROM (Electrically Erasable and Programmable Read Only Memory)
The EEPROM is programmed and erased electrically by burning some fusible links. It can
be erased and reprogrammed about ten thousand times. Both erasing and programming
take about 4 to 10 ms (milli second). In EEPROM, any location can be selectively erased and

Computer Programming Lab Manual 2014-2015


programmed. EEPROMs can be erased one byte at a time, rather than erasing the entire
chip. Hence, the process of re-programming is flexible but slow.
Advantages of ROM
Non-volatile in nature
These cannot be accidentally changed
Cheaper than RAMs
Easy to test
More Reliable than RAMs
These are static and do not require refreshing
Its contents are always known and can be verified

Secondary Memory
This type of memory is also known as external memory or non-volatile. It is slower than
main memory. These are used for storing Data/Information permanently. CPU directly
does not access these memories instead they are accessed via input-output routines.
Contents of secondary memories are first transferred to main memory, and then CPU can
access it. For example: disk, CD-ROM, DVD etc. Characteristic of Secondary Memory
These are magnetic and optical memories.
It is known as backup memory.
It is non-volatile memory.
Data is permanently stored even if power is switched off.
It is used for storage of the data in the computer.
Computer may run without secondary memory.
Slower than primary memories.
Control Unit
This unit controls the operations of all parts of computer. It does not carry out any actual
data processing operations. Functions of this unit are
It is responsible for controlling the transfer of data and instructions among other
units of a computer.
It manages and coordinates all the units of the computer.
It obtains the instructions from the memory, interprets them and directs the
operation of the computer.
It communicates with input/output devices for transfer of data or results from
storage.
It does not process or store data.
Input unit
The input device is used to enter data and information into a computer.
The devices like keyboard, mouse and scanner are commonly used as input devices.
A keyboard is used to enter alphanumeric characters and symbols.
The mouse is used to pick or select a command from the monitor screen.
A scanner is used to scan an image or read a barcode and so on.

Computer Programming Lab Manual 2014-2015


Central Processing Unit

The processing unit comprises a processor which interprets the program


instructions in memory, controls the flow of data and performs arithmetic and
logical operations.
The program instructions are processed one at a time along with the necessary data.
The results are sent to memory and the next instruction is processed.
This method is repeated until the program is executed.

Arithmetic and Logic unit:


The arithmetic-logic unit (ALU) is the unit of the computer that performs arithmetic
and logical operations on the data.
This section of the machine can be relatively small consisting of circuits and
registers which perform arithmetic (+, -, *, /) and logic (>,<,<=,>=,== and !=)
operations.
Arithmetic-logic units which can add and subtract and perform logical operations
form the backbone for the arithmetic and control operations in computers.
To perform scientific calculations the floating-point number system is used.
Control unit:
The control unit controls the overall activities of the components of the computer.
It is mainly used to coordinate the activities among other units.
It will send commands signals and controls the sequence of instructions to be
executed.
The control unit may be defined as the parts that effect the retrieval of instructions
in proper sequence and application of the proper signals to the arithmetic unit and
the other parts.

Output Unit
The output device is used to display or print result from a computer. Monitor, printer and
plotter are commonly used output devices. A monitor is used to display the result in the
form of text and graphics. The printer is used to print the result. A plotter is used to plot or
print graphical result from a computer. Note that a result displayed in a monitor is
temporary and it disappears when the next result is displayed, whereas the output printed
using a printer or a plotter is permanent and these printouts can be used for any business
correspondence or documentation. Normally soft copy is referred to information that is
stored on the storage device. A hard copy refers to a printout showing the information.
Microprocessor
A microprocessor is the heart of the computer. It is a semiconductor chip, which is
manufactured using the Large Scale integration (LSI) or Very Large Scale Integration
(VLSI), which comprises Arithmetic Logic Unit, Control unit and Central Processing Unit
(CPU) fabricated on a single chip. Intel 8088, Motorola 68000 are few microprocessors.

Computer Programming Lab Manual 2014-2015


Microprocessor has some key components which work closely with it. In case of any
damage, the component can be replaced. They are
Clock rate
Defines the rate at which a processor completes its operation.
Motherboard
It is the main circuit board of a computer in which a processor is inserted. It contains other
chipsets, controllers and expansion slots used to enhance the processor speed in computer
system.
System Bus
Placed between CPU and memory on the mother board to transfer address and data.
Cache memory
Portion of main memory that a microprocessor can access more quickly than RAM.
Improves overall system speed.
Instruction Pipelining
Method to increase the capability of a CPU. It is technique where the microprocessor begins
executing the second instruction before the first has already been executed.
Heat sink
Attached to microprocessor chip to bring down its temperature. It keeps away the
processor from overheating by absorbing its heat and dissipating it in air. There are two
types of heat sink.
Active Heat sink
Comes along with the fan and attached at the top of the plain metal surface of
microprocessor. It enables direct cooling of the processor.
Passive heat sink
Comes without fan. It consists of the metal plate attached to the surface of the processor
and consists of the fins, which streams the air to cool it.
Types of Microprocessors
Instruction Set: It is a group of instructions that can be given to the computer. These
instructions direct the computer in terms of data manipulation. A typical instruction
consists of two parts: Opcode and Operand.
Opcode or operational code is the instruction applied. It can be loading data, storing data
etc.
Operand is the memory register or data upon which instruction is applied.
CISC Approach
Single instructions can execute several low-level operations. The entire task of multiplying
two numbers can be completed with one instruction:
MULT 1A6F, 1A80
MULT is what is known as a "complex instruction." It operates directly on the computer's
memory banks and does not require the programmer to explicitly call any loading or
storing functions. It closely resembles a command in a higher level language. For instance,
if we let "a" represent the value of 6 and "b" represent the value of 8, then this command is
identical to the statement "a = a * b."
One of the primary advantages of this system is that the compiler has to do very little work
to translate a high-level language statement into assembly. Because the length of the code

Computer Programming Lab Manual 2014-2015


is relatively short, very little RAM is required to store instructions. The emphasis is put on
building complex instructions directly into the hardware.
The RISC Approach
RISC processors only use simple instructions that can be executed within one clock cycle.
Thus, the "MULT" command described above could be divided into three separate
commands: "LOAD," which moves data from the memory bank to a register, "PROD," which
finds the product of two operands located within the registers, and "STORE," which moves
data from a register to the memory banks. In order to perform the exact series of steps
described in the CISC approach, a programmer would need to code four lines of assembly:
LOAD 1A6F, 1A80
LOAD
B,
8
PROD A, B
STORE F000, A
Buses
These are collection of wires which transfer information between different parts of the
computer. There are two types of buses.
1. System Bus
2. I/O Bus

System Bus
The system bus is a cable which carries data communication between the major
components of the computer, including the microprocessor. Not all of the communication
that uses the bus involves the CPU, although naturally the examples used in this tutorial
will centre on such instances.
The system bus consists of three different groups of wiring, called the data bus, control bus
and address bus. These all have separate responsibilities and characteristics, which can be
outlined as follows:

Control Bus
The control bus carries the signals relating to the control and co-ordination of the various
activities across the computer, which can be sent from the control unit within the CPU.
Different architectures result in differing number of lines of wire within the control bus, as
each line is used to perform a specific task. For instance, different, specific lines are used
for each of read, write and reset requests.

Computer Programming Lab Manual 2014-2015


Data Bus
This is used for the exchange of data between the processor, memory and peripherals, and
is bi-directional so that it allows data flow in both directions along the wires. Again, the
number of wires used in the data bus (sometimes known as the 'width') can differ. Each
wire is used for the transfer of signals corresponding to a single bit of binary data. As such,
a greater width allows greater amounts of data to be transferred at the same time.
Address Bus
The address bus contains the connections between the microprocessor and memory that
carry the signals relating to the addresses which the CPU is processing at that time, such as
the locations that the CPU is reading from or writing to. The width of the address bus
corresponds to the maximum addressing capacity of the bus, or the largest address within
memory that the bus can work with. The addresses are transferred in binary format, with
each line of the address bus carrying a single binary digit. Therefore the maximum address
capacity is equal to two to the power of the number of lines present (2^lines).

I/O Bus
A personal computer may transfer data from disk to CPU, from CPU to memory, or from
memory to the display adapter. I/O buses connect all I/O devices with the CPU and RAM. In
modern Pentium driven PC, there are two or three different I/O Buses.
The ISA (Industry Standard Architecture) Bus - oldest, simplest and slowest bus.
ISA is a type of bus used in PCs for adding expansion cards. For example, an ISA slot
may be used to add a video card, a network card, or an extra serial port.
The PCI (Peripheral Component Interconnect) Bus Fastest and presently most
powerful bus. PCI is an interconnection system between a microprocessor and
attached devices in which expansion slots are spaced closely for high speed
operation. Using PCI, a computer can support both new PCI cards while continuing
to support Industry Standard Architecture (ISA) expansion cards, an older
standard.
The USB (Universal Serial Bus) newest bus. It is most used on Personal
computers. USB is also used on other devices such as the PlayStation 2, PlayStation
3 and the Xbox 360. USB connects different devices using a standard interface.
Most people use USB for computer mice, keyboards, scanners, printers, digital cameras,
and USB flash drives. The standard was made to improve plug and play devices. This means
that a device can simply be plugged into a free socket. The computer will then recognize it.
Operating systems and its functions:
An operating system is a program that acts as an interface between the software and
the computer hardware.
It is an integration set of specialized programs that are used to manage overall
resources and operations of the computer.
It is specialized software that controls and monitors the execution of all other
programs that reside in the computer, including application programs and other
system software.

Computer Programming Lab Manual 2014-2015

Objectives of Operating System


Making a computer system convenient to use in an efficient manner.
To hide the details of the hardware resources from the users.
To provide users a convenient interface to use the computer system.
To act as an intermediary between the hardware and its users and making it easier
for the users to access and use other resources.
Manage the resources of a computer system.
Keep track of who is using which resource, granting resource requests, according for
resource using and mediating conflicting requests from different programs and users.
The efficient and fair sharing of resources among users and programs.

Characteristics of Operating System


Memory Management -- It keeps track of primary memory, i.e., what parts of it are
in use by whom, what parts are not in use, etc. Allocates the memory when the
process or program requests it.
Processor Management -- Allocates the processor (CPU) to a process. Deallocate
processor when processor is no longer required.
Device Management -- Keeps tracks of all devices. This is also called I/O controller.
Decides which process gets the device when and for how much time.
File Management -- Allocates the resources. Deallocates the resource. Decides who
gets the resources.
Security -- By means of passwords & similar other techniques, preventing
unauthorized access to programs & data.
Job accounting -- Keeping track of time & resources used by various jobs and/or
users.

Computer Programming Lab Manual 2014-2015


Control over system performance -- Recording delays between requests for a
service & from the system.
Interaction with the operators -- The interaction may take place via the console of
the computer in the form of instructions. Operating System acknowledges the same,
do the corresponding action and inform the operation by a display screen.
Error-detecting aids -- Production of dumps, traces, error messages and other
debugging and error-detecting methods.
Coordination between other software and users -- Coordination and assignment
of compilers, interpreters, assemblers and other software to the various users of the
computer systems.

We know operating system is a collection of programs and it is the interface between user
and the computer. An operating system is a program which connects the user and the
electronic hardware in a computer. It is a set of programs which supervise the activities of
a computer and activate the operations of the hardware components such as CPU, main
memory, disk drives, keyboard, monitor and printer and so on. Some of the startup
programs initially loaded to RAM are stored in ROM, mainly the BIOS programs which are
recorded by the manufacturers of the computer system. Service programs available in
operating system for operating system for operations like copying a file, deleting a file,
formatting a disk, printing a file and so on are usually stored in the disk. Error messages are
displayed on the screen if there is any malfunctioning of hardware.
There are many operating system used in computers. Commonly used operating systems
are MS-DOS (Microsoft Disk operating System), Windows 95/98/2000, Windows NT, UNIX
and so on. Nowadays Windows 2000 operating system is widely used in personal
computers, and UNIX is used in Mainframes, Servers, Graphic Workstations and also
personal computers. Linux is one of the most popular free operating system.
Operating system will display instruction on the monitor screen and the user can
interact with the computer.
It loads the application programs such as MS Word, AutoCAD and so on from disk to
the computer memory.
It manages the information stored on disk and retrieves the same whenever required.
It supervises and coordinates the activities of the hardware and peripherals such as
CPU, keyboard, mouse, monitor, printer, RAM, disk drives and so on.
It utilizes the power of the CPU for multitasking and timesharing.
In general operating systems performs many task which include
Memory management
Process management
I/O management
Device management

Multitasking
It is the ability of the computer to handle several application programs concurrently.
Printing a document, executing a program and any other operation can be done
simultaneously to reduce the idle time of the processor. The multi task capability of the

Computer Programming Lab Manual 2014-2015


operating system will utilize the processor efficiently, the reducing the user time. Another
simple example is hearing audio songs and typing programs same time.

Timesharing
It is the ability of the CPU to serve many users connected to it through a network. The
operating system will assign each user a slice of processor time or time quantum in a
round-robin fashion. Since the CPU has high processing speed, it can process information of
many users.

Specific features of DOS and UNIX:


MS-DOS is a single user operating system developed by Microsoft Corporation. An
operating system has a collection of program. When the computer is switched on, the file
COMMAND.COM is loaded to the RAM and after the successful start of the computer, the
DOS prompt or command prompt will be displayed. The DOS prompt displays the letter
associated with the disk drive followed by a> symbol. For floppy disk drive, A> or A :> is
displayed and for hard disk drive C> or C:\> is displayed. It indicates the operating system
is ready to take commands from the user. MS-DOS is one of the popular operating system
for desktop computers. DOS operating system consists of three parts in it, namely resident
part, initialization and the transient part. Most of the command programs are located in
the resident part. While booting, the number of files and buffers to open are contained in
the initialization part and transient part is flexible part of the operating system. The
commands are not case sensitive.
File:
A file is a collection of related information. For example, like the contents of a file folder in a
desk drawer. Files on the disk can contain letters, memos and executable programs.
Program:
Programs are special types of files. These are series of instructions written in computer
languages. This program instructs the computer to perform the task.

Directory:
DOS uses a filing system to store its files. The filing system uses storage areas called
directories. A directory is nothing more than an expandable file folder that can hold other
expandable file folders. These file folders hold the data files. A directory is a table of
contents for a disk. It contains the names of files, their sizes, and the dates they were last
modified. All of the different directories are stored under one master directory. This
directory is called the root directory.
In addition to directories, it uses an area on a disk called the File Allocation Table (FAT).
The FAT is similar to our contents page in our book. It holds the information where the file
is stored in the disk.
Multilevel directories:
When there are two or more users who share a computer, when you are working on
several different projects, the number of files in the directory can become a large and

Computer Programming Lab Manual 2014-2015


unwieldy. Using directories is one way that we can divide our files into convenient groups.
Any one directory can contain many files. This directory may also contain other directories
or sub directories. This organized file structure is called a hierarchical directory system.
Specific features of UNIX:
The commands in UNIX are considered to case sensitive. It means, lower case a and
uppercase A are considered differently.

Multitasking:
It refers to performing a number of tasks simultaneously. For example when a document is
printed, you may run another program to sort large data and at the same time you may edit
a document in the foreground screen. UNIX switches between the tasks and executes them
one by one at small interval of time. This process of sharing the CPU to perform various
tasks simultaneously is called time-sharing. The more number of the tasks are submitted
then we end up with slower response from the computer.

Multi-user capability:
UNIX allows the computer to be used by several users through several terminal connected
to a powerful computer. A terminal will have a keyboard and a monitor. The computer to
which terminals are connected is called as the host computer or server. Any user on the
terminal can run various programs, read file information or print a document at the same
time. Multi user computer, are economical and efficient compared to stand-alone
computers.

Portability:
One of the outstanding features of UNIX is its ability to port itself to another installation.
For example, an application program developed in UNIX environment can be used in a
different platform.
Security
UNIX provides a good security for users. The users are required to authenticate before they
use the system. The password is encrypted.

File system
UNIX identifies three types of users, owner, group and others. For each group it provides
permission on the files like to read, write and execute operation.
We know, in information technology era, sharing of resources and easy communication are
acting as a backbone of any network. Popular example is our Internet. With the help of
internet we are able to exchange information and share resources. Hence in this chapter we
study different advantages of the network and different forms of the network and their
features.
Networking of computers and its advantages.
Computer network is defined as an interconnection of autonomous computer. Here
autonomous means, there is no master and slave relationship. All computers are equal.

Computer Programming Lab Manual 2014-2015


Computer network enables to share the resources. Computer networking also refers to
connecting computers to share data, application software and hardware devices. Networks
allow sharing of information among various computers and permit users to share files. For
example a students accesses compilers sitting at one place, where compiler may be stored
on the other machine. The students takes printout with the help of one printer connected
to the network. The printer can be shared among many students.

Network offers the opportunity to communicate more efficiently with others through
electronic mail. Networks allow companies to share software and peripherals such as
printers, plotters, scanners and so on. With networking all the computers in an office can
be connected to a single printer and scanner. It also helps in using storage devices
efficiently. Computer network acts as a very powerful communication medium. It means
people exchange their information. When compared to mainframe computers, network of
computers saves money.

Types of networks
Depending the nature of the distances, protocols (the set of rules used for communication)
the network can be classified into LAN (Local Area Network), MAN (Metropolitan Area
Network) and WAN (Wide Area Network).

Local Area Network (LAN)


A LAN (local area network) is a group of computers and network devices connected
together, usually within the same building. By definition, the connections must be highspeed and relatively inexpensive (e.g., token ring or Ethernet). They function to link
computers together and provide shared access to printers, file servers, and other services.
Any individual computer connected to a network is called workstation. A workstation may
not need a floppy disk or hard disk. A LAN or local area network connects computers and
peripherals in a limited area. LAN requires cables to connect workstations. For example
LAN is used in a hall or within a building. Figure 5.1 shows Local Area Network , where
various departments are connected.

Fig: Local Area Network

Metropolitan Area Network (MAN)


A MAN (Metropolitan Area Network) is used to connect computers to cover the city or
town. The range may be approximately 50 Kilometers. Normally cables and fiber optic
cables are used to connect computers. The routing of the messages is fast. Normally central
library in a city may be connected by a MAN, so users can access the information. Figure 5.2
shows a typical view of Metropolitan Area Network.

Computer Programming Lab Manual 2014-2015


Wide Area Network (WAN)
A WAN (Wide Area Network) covers large distance like state, country or continents.
The WAN uses the fiber optics, cables and even satellites also. Here communication circuits
are connected with the help of hardware device called routers. Routers forward small
pieces of information called packets from one to another. Internet is the popular one
comes under WAN. Some of the examples makes use of internet are reservation of airplane
tickets, railway tickets and even cinema tickets. Another facility called e-commerce, where
business is carried out through internet. Here people can buy books, articles and so on
through registering their wants through the internet. Figure 5.3 shows a typical view of
Wide Area Network.

Fig: Wide Area Network

Internet
The internet is a massive wide area network, connecting thousands of computer networks
around the world. The internet is a worldwide network of networks. It is a collection of
thousands of smaller networks in different countries around the world. It links thousands
of academic government, military and public computers, enabling millions of people to
share information and other resources.

Internet pathways are used to exchange digitized computer data. The basic services that
form the foundation of the internet are e-mail, telnet and FTP. With internet we can easily
exchange electronic mail with friends and family anywhere in the world.
Telnet allows you to connect to a remote computer. We can access any of the public
services or tools and library databases at the remote site. FTP (File Transfer Protocol)
provides for transferring files from one computer to another across the internet.

Internet has many uses. For individuals, the most important uses of internet are e-mail and
surfing the Web. One can read the topics of interest like sports, a hobby, a country or any
place of interest.
E-mail:
The e-mail stands for electronic mail. One of the major features of computer networking is
that messages can be sent electronically to various terminals on the network. The messages
are sent very quickly and accurately. E-mail uses the concept of Storing and forwarding
messages. It saves a lot of money for the users. Here user registers his/her account with
one of the providers. The e-mail account normally contains username and the provider

Computer Programming Lab Manual 2014-2015


name. For example abc @ yahoo.com, represents abc is the name of the user, who is
registered in yahoo provider.

Internet
Internet is a world-wide/global system of interconnected computer networks.
Internet uses the standard Internet Protocol (TCP/IP)
Every computer in internet is identified by a unique IP address.
IP Address is a unique set of numbers (such as 110.22.33.114) which identifies a
computer location.
A special computer DNS (Domain Name Server) is used to give name to the IP
Address so that user can locate a computer by a name.
For example, a DNS server will resolve a name http://www.tutorialspoint.com to a
particular IP address to uniquely identify the computer on which this website is
hosted.
Internet is accessible to every user all over the world.

Intranet
Intranet is system in which multiple PCs are networked to be connected to each other.
PCs in intranet are not available to the world outside of the intranet.
Usually each company or organization has their own Intranet network and
members/employees of that company can access the computers in their intranet.
Each computer in Intranet is also identified by a IP Address, which is unique among
the computers in that Intranet.

Computer Programming Lab Manual 2014-2015

Similarities in Internet & Intranet


Intranet uses the internet protocols such as TCP/IP and FTP.
Intranet sites are accessible via web browser in similar way as websites in internet.
But only members of Intranet network can access intranet hosted sites.
In Intranet, own instant messengers can be used as similar to yahoo messenger/gtalk
over the internet.
Differences in Internet & Intranet
Internet is general to PCs all over the world where Intranet is specific to few PCs.
Internet is wider access and provides a better access to websites to large population
whereas Intranet is restricted.
Internet is not as safe as Intranet as Intranet can be safely privatized as per the need.
Memory
RAM is considered as Computer Memory as performance of a computer is directly
proportional to its memory and processor.
Today's software and operating systems require high memory.
Today, commonly used RAM is DDR3, which operates at 1066Mhz
As per window 7, 1 GB is the minimum RAM required to function properly.
Recommended - 4 GB.

Hard Drive
Hard disk is used for storage purpose. Higher the capacity, more data you can save in
it.
Nowadays, computers are equipped with 500GB, which can be extended to 2TB.
Most hard drives in desktop operate at the standard performance speed of 7200RPM.

Computer Programming Lab Manual 2014-2015


Recommended - 500GB.

CPU
Frequency (GHz) - This determines speed of the processor. More the speed, better
the CPU.
Cores - Today's CPUs come with more than one core, which is like having more than
one CPU in the computer. Programs, which can take advantage of multi-core
environment, will run faster on such machines.
Brand - Intel or AMD. Both are equivalent. Intel is in lead.
Cache - Higher the L1, L2 cache, better the CPU performance.
Recommended - Intel Core i3 i3-3225 3.30 GHz Processor.

Input Devices
Following are few of the important input devices which are used in Computer Systems
Keyboard
Mouse

Joy Stick

Light pen

Track Ball
Scanner

Graphic Tablet

Microphone
Magnetic Ink Card
Reader (MICR)

Optical Character Reader (OCR)


Bar Code Reader

Optical Mark Reader

Keyboard
Most common and very popular input device is keyboard. The keyboard helps in inputting
the data to the computer. The layout of the keyboard is like that of traditional typewriter,
although there are some additional keys provided for performing some additional
functions.

Computer Programming Lab Manual 2014-2015


Keyboard is of two sizes 84 keys or 101/102 keys, but now 104 keys or 108 keys keyboard
is also available for Windows and Internet.
The keys are following
Keys Description
1. Typing Keys

These keys include the letter keys (A-Z) and digits keys (0-9)
which are generally give same layout as that of typewriters.

3. Function Keys

The twelve functions keys are present on the keyboard. These


are arranged in a row along the top of the keyboard. Each
function key has unique meaning and is used for some specific
purpose.

2. Numeric Keypad

4. Control keys
5. Special Purpose Keys

It is used to enter numeric data or cursor movement. Generally, it


consists of a set of 17 keys that are laid out in the same
configuration used by most adding machine and calculators.

These keys provides cursor and screen control. It includes four


directional arrow key. Control keys also include Home, End,
Insert, Delete, Page Up, Page Down, Control(Ctrl), Alternate(Alt),
Escape(Esc).
Keyboard also contains some special purpose keys such as Enter,
Shift, Caps Lock, Num Lock, Space bar, Tab, and Print Screen.

Summary:
Computer network is defined as a interconnection of autonomous computers.
Computer networking enables us to connect computers to share data, application
software and hardware devices.
Networks allow sharing of information among various computers and permit users to
share files.
A LAN or local area network connects computers and peripherals in a limited area.
A MAN covers the city or town.
A Wide Area Network covers a large area.
The internet is a massive wide area network, connecting thousands of computer networks
around the world.
E-mail is a cost effective communication

Computer Programming Lab Manual 2014-2015


Quiz questions
1. Computer network defined as a interconnection of ---------- computers
2. Computer network allows user to ----- the resources
3. -------- network confined to hall or building.
4. ------- is one example of WAN.
5. ------ business is carried out through internet.
6. Small piece of information called ---- are forwarded by router in Internet.
Answers
1. Autonomous
2. share
3. Local area
4. Internet
5. E-commerce
6. packets

Exercise
1. What is a computer network? What are the advantages of computer network?
2. Briefly explain the Local area network, Metropolitan area network and wide area
network.
3. What e-mail? How e-mail works?
4. What are the uses of Internet?

Summary:
A computer is an electronic device which takes information and process information
according to the program and produces the output.
A computer system has five basic functional units.
The Central Processing Unit is the brain of the computer.
The arithmetic-logic unit (ALU) is the unit of the computer that performs arithmetic
and logical operations on the data.
The control unit controls the overall activities of the components of the computer.
The memory unit is the unit where all the input data and results stored.
Stored program concept uses the memory unit to store both instruction or operation
code and data or operands.

NIC
Short for Network Interface Card, a NIC is also commonly referred to as an Ethernet
card and network adapter and is an expansion card that enables a computer to connect to
a network such as a home network or the Internet using an Ethernet cable. A Network
Interface Card (NIC) is a computer hardware component that allows a computer to connect
to a network. NICs may be used for both wired and wireless connections.
A NIC is also known as a Network Interface Controllers (NIC), Network Interface Controller
Card, expansion card, computer circuit board, network card or LAN card
Every computer on a network, both clients and servers, requires a network interface card
(or NIC) in order to access the network. A NIC is usually a separate adapter card that slides

Computer Programming Lab Manual 2014-2015


into one of the server's motherboard expansion slots. However, most new computers have
the NIC built into the motherboard, so a separate card isn't needed.
What is a Computer Network?
A computer network is a system in which multiple computers are connected to each other
to share information and resources.

Characteristics
Share Resources from one computer to another
Create files and store them in one computer, access those files from the other
computer(s) connected over the network
Connect a printer, scanner or a fax machine to one computer within the network and
let other computers of the network use the machines available over network.
Following is the list of hardwares required to set up a computer network:
Network Cables
Distributors
Router
Internal Network Cards
External Network Cards
Network Cables
Network cables are used to connect computers. The most commonly used cable are
Category 5 cable RJ-45.

Computer Programming Lab Manual 2014-2015

Distributors
Each and every computer can be connected to another one via a serial port, but if we
need to connect many computers to produce a network, this serial connection will not
work. The solution is to use a central body to which other computers, printers,
scanners, etc., can be connected and then this body will manage or distribute network
traffic.

Router
A router is a type of device, which acts as the central point among computers and
other devices that are part of a network.
A router is equipped with holes called ports.
Computers and other devices are connected to a router using network cables.
Nowadays, router comes in wireless modes using which computers can be connected
without any physical cable.

Computer Programming Lab Manual 2014-2015

Network Interface Card (NIC)


Network card is a necessary component of a computer without which a computer
cannot be connected over a network.
Also known as network adapter or Network Interface Card (NIC).
Most of branded computers have network card pre-installed.
Network cards are of two types: Internal and External Network Cards
Internal Network Cards
Motherboard has a slot for internal network card where it is to be inserted.
Internal network cards are of two types:
First type uses Peripheral Component Interconnect (PCI) connection.
Second type uses Industry Standard Architecture (ISA).
Network cables are required to provide network access.

External Network Cards


Comes in two flavors: Wireless and USB based.
Wireless network card needs to be inserted into the motherboard but no network
cable is required to connect to network.

Computer Programming Lab Manual 2014-2015

USB cards are easy to use and connect via USB port.
Computer automatically detects USB card and can install the drivers required to
support the USB network card automatically.

What is Flash Memory?


Overview and tutorial about the basics of what is semiconductor Flash memory, how it
works, its performance, variants, applications & types of flash memory.
Flash memory of a form of semiconductor memory is widely used for many electronics data
storage applications.
Although first developed in the 1980s, the use of flash memory has grown rapidly in recent
years as forms the basis of many memory products.
Flash memory can be seen in many forms today including flash memory USB memory
sticks digital camera memory cards in the form of compact flash or secure digital, SD
memory. In addition to this flash memory storage is used in many other items from MP3
players to mobile phones, and in many other applications
There are also different flash memory types and these different types are each suited to
their own applications.

What Is Flash memory?


Flash memory storage is a form of non-volatile memory that was born out of a combination
of the traditional EPROM and E2PROM.
In essence it uses the same method of programming as the standard EPROM and the
erasure method of the E2PROM.
One of the main advantages that flash memory has when compared to EPROM is its ability
to be erased electrically. However it is not possible to erase each cell in a flash memory

Computer Programming Lab Manual 2014-2015


individually unless a large amount of additional circuitry is added into the chip. This would
add significantly to the cost and accordingly most manufacturers dropped this approach in
favour of a system whereby the whole chip, or a large part of it is block or flash erased hence the name.

Today most flash memory chips have selective erasure, allowing parts or sectors of the
flash memory to be erased. However any erasure still means that a significant section of the
chip has to be erased.
Flash memory history
Flash memory dates back to around 1980 when the concept was developed at Toshiba by
Dr. FujioMasuoka. It was then later presented at the 1984 IEEE International Electron
Devices Meeting, IEDM held in San Francisco, California.
The basic laboratory concept took a few years to develop into a product that could be
launched commercially. Intel introduced the first commercial chips onto the market in
1988 - these neither were NOR based types.
The NOR flash memories had relatively long erase and write times. Toshiba again
developed their technology further and were able to announce NAND technology at the
1987 IEDM. This technology, though, still needed further development to take it through to
commercial launch.
The advantage of NAND flash was that it had reduced erase and write times and it had a
greater storage density.

Flash memory advantages & disadvantages


As with any technology there are various advantages and disadvantages. It is necessary to
consider all of these when determining the optimum type of memory to be used.
FLASH
ADVANTAGES

MEMORY FLASH
DISADVANTAGES

Non-volatile memory
Easily portable (e.g. USB memory
sticks)
Mechanically robust

MEMORY

Higher cost per bit than hard drives


Slower than other forms of memory
Limited number of write / erase cycles
Data must be erased before new data can
be written
Data typically erased and written in
blocks

Computer Programming Lab Manual 2014-2015


Flash memory types
There are two basic types of Flash memory. Although they use the same basic technology,
the way they are addressed for reading and writing is slightly different. They two flash
memory types are:
1. NAND Flash memory: NAND Flash memories have a different structure to NOR
memories. This type of flash memory is accessed much like block devices such as hard
disks. When NAND Flash memories are to be read, the contents must first be paged
into memory-mapped RAM. This makes the presence of a memory management unit
essential.
2. NOR Flash memory: NOR Flash memory is able to read individual flash memory cells,
and as such it behaves like a traditional ROM in this mode. For the erase and write
functions, commands are written to the first page of the mapped memory, as defined
in "common flash interface" created by Intel.

NAND / NOR tradeoff: NAND Flash memories and NOR Flash memories can be used for
different applications. However some systems will use a combination of both types of Flash
memory. The NOR memory type is used as ROM and the NAND memory is partitioned with
a file system and used as a random access storage area.
Flash memory is a particularly important form of semiconductor memory. It is now widely
used and is possibly one of the most important forms of medium term storage. As
mentioned earlier Flash memory can be seen in a variety of forms and uses ranging from
Flash memory USB sticks to Compact Flash cards used for cameras. In addition to this many
other items of electronics can be seen using Flash memory ranging from mobile phones to
MP3 players and many more. In view of its current importance, Flash memory will be seen
in widespread use for many years to come.
We store and transfer all kinds of files on our computers -- digital photographs, music files,
word processing documents, PDFs and countless other forms of media. But sometimes your
computer's hard drive isn't exactly where you want your information. Whether you want to
make backup copies of files that live off of your systems or if you worry about your
security, portable storage devices that use a type of electronic memory called flash
memory may be the right solution.
Electronic memory comes in a variety of forms to serve a variety of purposes. Flash
memory is used for easy and fast information storage in computers, digital cameras and
home video game consoles. It is used more like a hard drive than as RAM. In fact, flash
memory is known as a solid state storage device, meaning there are no moving parts -everything is electronic instead of mechanical.
Here are a few examples of flash memory:
Your computer's BIOS chip
Compact Flash (most often found in digital cameras)
Smart Media (most often found in digital cameras)
Memory Stick (most often found in digital cameras)
PCMCIA Type I and Type II memory cards (used as solid-state disks in laptops)
Memory cards for video game consoles

Computer Programming Lab Manual 2014-2015


Flash memory is a type of EEPROM chip, which stands for Electronically Erasable
Programmable Read Only Memory. It has a grid of columns and rows with a cell that has
two transistors at each intersection (see image below).

Flash Memory Operation & Technology


Flash memory is an effective form of semiconductor memory.
Flash memory operation is very similar to that of the older EPROM and EEPROM
technologies.
Flash memory operation is based around methods including Fowler-Nordheim tunnelling
and hot electron injection.

Flash memory operation basics


Flash memory is a high density form of semiconductor memory. This is brought about by
the fact that each Flash memory cell is made up from a single field effect transistor and it is
very similar in structure to the ordinary EPROM.
Each Flash memory cell consists of the basic channel with the source and drain electrodes
separated by the channel about 1 m long. Above the channel in the Flash memory cell
there is a floating gate which is separated from the channel by an exceedingly thin oxide
layer which is typically only 100 thick. It is the quality of this layer which is crucial to the
reliable operation of the memory.

Flash memory cell structure


Above the floating gate there is the control gate. This is used to charge up the gate
capacitance during the write cycle.
In the case of traditional EPROMs, these memory chips are erased by the application of UV
light. To accommodate these memory devices have a translucent window which can be
exposed to the UV light. However this process takes upwards of twenty minutes. It also
requires the memory chip to be removed from its circuit and placed in a special eraser
where the UV light can be contained.
The Flash memory cell functions by storing charge on the floating gate. The presence of
charge will then determine whether the channel will conduct or not. During the read cycle a
"1" at the output corresponds to the channel being in its low resistance or ON state.
Programming the Flash memory cell is a little more complicated, and involves a process
known as hot-electron injection. When programming the control gate is connected to a
"programming voltage". The drain will then see a voltage of around half this value while the
source is at ground. The voltage on the control gate is coupled to the floating gate through
the dielectric, raising the floating gate to the programming voltage and inverting the

Computer Programming Lab Manual 2014-2015


channel underneath. This results in the channel electrons having a higher drift velocity and
increased kinetic energy.
Collisions between the energetic electrons and the crystal lattice dissipate heat which
raises the temperature of the silicon. At the programming voltage it is found that the
electrons cannot transfer their kinetic energy to the surrounding atoms fast enough and
they become "hotter" and scatter further afield, many towards the oxide layer. These
electrons overcome the 3.1 eV (electron volts) needed to overcome the barrier and they
accumulate on the floating gate. As there is no way of escape they remain there until they
are removed by an erase cycle.
The erase cycle for Flash memory uses a process called Fowler-Nordheimtunnelling. The
process is initiated by routing the programming voltage to the source, grounding the
control gate and leaving the drain floating. In this condition electrons are attracted towards
the source and they tunnel off the floating gate, passing through the thin oxide layer. This
leaves the floating gate devoid of charge.
Generally the erase process is only made to last a few milliseconds. When complete each
Flash memory cell in the block is checked to ensure it has been completely erased. If not a
second erase cycle is initiated.

Programming Flash memory


In the early days of flash memories one of the limiting factors in their uptake was the topic
of programming Flash memory because they had a limited number of erase programme
cycles. This was caused by the destructive breakdown of the thin gate oxide layer. Some of
the early examples of flash memories only had a few hundred cycles. Now Flash memory
technology is vastly improved and manufacturers quote figures that mean the Flash
memory life is no longer a concern.
Most of this improvement in Flash memory has been brought about by improving the
quality of the oxide layer. When samples of flash memory chips are found to have a lower
lifetime it is usually caused by the manufacturing process not being optimized for the oxide
growth. Now programming Flash memory is not a problem and when using Flash memory
the chips are, within reason, not treated as items with a limited life.
Flash memory access
Flash memory is different to most other types of electronic memory in that while reading
data can be performed on individual addresses on certain types of flash memory, erase and
write activities may only be performed on a block of a Flash memory. A typical block size
will be 64, 128, or 256 kB. In order to accommodate this, the low level control software
used to drive Flash memories, needs to take account of this if the read and write operations
are to be performed correctly.
Flash Memory Wear, Reliability & Life
One of the issues with flash memory is that it has a finite lifetime and can only support a
finite number of programme / write cycles. This process is known as flash memory wear.
It is important to incorporate the flash memory wear and lifetime into any decisions about
the use of flash memory.
Also when using flash memory, it is necessary to be aware of the lifetime and wear
limitations so that data is not lost.

Computer Programming Lab Manual 2014-2015


Flash memory wear basics
Significant improvements have been made in terms of flash memory wear since the first
flash devices were introduced. Originally the flash memory lifetime was measured in terms
of a few thousand programme- erase cycles.
Today most commercially available flash memory is guaranteed to withstand 100 000 or
more programme-erase cycles with some manufacturers guaranteeing a life of over 1 000
000 cycles.
Flash memories wear out mechanism
The flash memory wear out mechanism results from the structure of the device.
A typical device structure is seen below, and from this it can be seen that there are various
layers and areas to the device.

Flash memory cell structure


The wear-out mechanism for flash devices occurs as a result of usage causing the tunnel
oxide layer to degrade. Although there are other mechanisms that can cause the device to
fail, it is the tunnel oxide layer degradation that causes the flash memory wear issue.
Flash memory uses a process called channel hot-electron injection for programming each
cell and Fowler-Nordheimtunnelling for the erase cycle. However it is found that electrons
can become trapped within the oxide layer, and this electron trapping in the tunnel oxide
reduces electric field during erase operations. In turn this gives rise to a in gradual
degradation of the erase characteristics and closure of memory cell threshold window.
As a result charge trapping / de-trapping technology is key to the improvement of the flash
memory wear characteristics.
Wear levelling
In order to gain the maximum use from a flash memory, a process called wear levelling is
used. The wear levelling technique is one that can be used in a variety of forms of memory,
e.g. hard drives, etc., but is also very applicable to flash memories where it is widely used.
The aim of the flash memory wear levelling functionality is to track which blocks have been
used, and to distribute the programme and erase cycles are distributed evenly across the
available memory. By using the wear levelling techniques, no block should be used greatly
more than any other and therefore no single block prematurely fails due to a higher
number of programme-erase cycles.
To achieve this, one block within the flash memory is designed to have an extended
lifetime, so that it can be used to track the usage and control the wear levelling.
There are three main types of wear levelling mechanism that are used:

Computer Programming Lab Manual 2014-2015


No wear leveling: The simplest option is not to use wear levelling. This approach
might be acceptable in circumstances where little use is expected and a reduction in
complexity is of paramount importance. Under these circumstances the Flash
memory controller permanently assigns the logical addresses from the operating
system to the physical addresses of the Flash memory. When a location is changed,
the contents of that block must be erased and then re-programmed without any
intelligence to reduce the number of programme-erase cycles. This is not only more
time consuming, but it also does nothing to reduce the flash memory wear.
Dynamic wear leveling: Dynamic wear levelling uses a map to link Logical Block
Addresses, LBAs generated by the operating system, OS, to the physical Flash memory
locations. Each time the operating system writes new data, the map is updated so the
original physical block is marked as invalid data. A new block is then linked to that
map entry. Each time a block of data is re-written to the Flash memory it is written to
a new location.

There is still a problem with this type of flash memory wear levelling with blocks of
data that never get replaced. They remain with no additional wear.

The name for this type of wear leveling comes from the fact that only the dynamic
data, i.e. data that is changed, is recycled. The memory may last longer than one with
no wear leveling, but there will still be blocks of data that remain operable as a result
of low usage, long after the memory as a whole is inoperable as some areas have
exceeded the number of programme-erase cycles.
Static wear leveling: This form of wear leveling is the most sophisticated and
effective. Static wear leveling also uses a map to link the Logical Block Addresses to
physical memory addresses.
Static wear leveling works the same as dynamic wear leveling but with the addition
that blocks of static data, i.e. data that does not change, are periodically moved so that
these low usage cells are used by other data. By moving even static data periodically it
levels the usage and hence levels the wear across the whole memory.
The various forms of wear leveling ensure that the maximum life is achieved for a flash
memory. The wear leveling algorithms combined with improved semiconductor lifetimes,
means that flash memory is an effective form of solid state memory.

Introduction:
Flash memory or a flash RAM is a type of nonvolatile semiconductor memory device where
stored data exists even when memory device is not electrically powered. It's an improved
version of electrically erasable programmable read-only memory (EEPROM). The
difference between Flash Memory and EEPROM are, EEPROM erases and rewrite its
content one byte at a time or in other words, at byte level. Whereas Flash memory erases or
writes its data in entire blocks, which makes it a very fast memory compared to EEPROM.
Flash memory can't replace DRAM and SRAM because the speed at which the DRAM/SRAM
can access data and also their ability to address at byte level can't be matched by Flash.
The flash memory is also termed as Solid-state Storage Device (SSD) due to the absence of
moving parts in comparison to traditional computer hard disk drive.

Computer Programming Lab Manual 2014-2015


Flash memory types:
The two main types of flash memory are the NOR Flash & NAND Flash. Intel is the first
company to introduce commercial (NOR type) flash chip in 1988 and Toshiba released
world's first NAND-flash in 1989.
NOR-flash is slower in erase-operation and write-operation compared to NAND-flash. That
means the NAND-flash has faster erase and write times. More over NAND has smaller erase
units. So fewer erases are needed. NOR-flash can read data slightly faster than NAND.
NOR offers complete address and data buses to randomly access any of its memory location
(addressable to every byte). This makes it a suitable replacement for older ROM
BIOS/firmware chips, which rarely needs to be updated. Its endurance is 10,000 to
1,000,000 erase cycles. NOR is highly suitable for storing code in embedded systems. Most
of the today's microcontrollers comes with built in flash memory.

NAND-flash occupies smaller chip area per cell. This maker NAND available in greater
storage densities and at lower costs per bit than NOR-flash. It also has up to ten times the
endurance of NOR-flash. NAND is more fit as storage media for large files including video
and audio. The USB thumb drives, SD cards and MMC cards are of NAND type.
NAND-flash does not provide a random-access external address bus so the data must be
read on a block-wise basis (also known as page access), where each block holds hundreds
to thousands of bits, resembling to a kind of sequential data access. This is one of the main
reasons why the NAND-flash is unsuitable to replace the ROM, because most of the
microprocessors and microcontrollers require byte-level random access.
A write operation in any type of flash device can only be performed on an empty or erased
unit. So in most cases write operation must be preceded by an erase operation. The erase
operation is fairly straightforward in the case of NAND-flash devices. But for a NOR-flash, it
is mandatory that all bytes in the target block should be written with zeros before they can
be erased.
The size of an erase-block in NOR-flash ranges from 64 to 128 Kbytes. Here a write/erase
operation can take up to 5 s. But the NAND-flash has erase blocks 8 to 32 Kbytes in size. So
it is obvious that the NAND performs the identical operation in a lesser time duration.
INOR-flash interface resembles closely to a SRAM memory interface, which has enough
address pins to map its entire media, allowing for easy access to every byte contained in it,
whereas the NAND-flash go for serially accessed complicated I/O mapped interface. Here
the same pins are used for control, address & data.
In traditional single-level cell flash devices, each cell stores only one bit of information.
Later, many developers have developed a new form of flash memory known as multi-level
cell flash that can store/hold more than one bits rather than a single bit in each memory
cell, thus doubling the capacity of memory.
QUIZ QUESTIONS
1) A Computer consists of --- units.
a) 3 b) 4 c) 5 d) 6
2) Keyboard is an example of ------ unit.
a) Memory b) Input c) Output d) ALU
3) ALU stands for -------

Computer Programming Lab Manual 2014-2015


a) Arithmetic Logic Unit b) Arithmetic Lower Unit c) Add Logical Unit
d) None of the above
4) RAM is considered as a ---------a) Volatile Memory b) Nonvolatile Memory c) Permanent
d) None of the above
5) ------ contains the program during the manufacturing itself.
a) RAM b) ROM c) Both a and b d) None of the above
6) ------- unit is used to store information.
a) Input b) Output c) Control d) Memory
7) In Stored program concept ---- and --- are stored in the same memory.
a) Data and Instruction b) Data and Operands c) Instruction and operation code
d) None of the above
8) Microprocessor is the heart of ------ computer.
a) Digital b) Analog c) Both a and b d) None of the above
Answers:
1c
2b
3a
4a
5b
6d
7a
8a
Exercises
1. Mention the basic functional units of a computer?
2. With a neat diagram explain the working organization of a computer?
3. What is stored program concept or John Von Neumann concept?
4. What is microprocessor?
5. What are the differences between RAM and ROM?

Computer Programming Lab Manual 2014-2015

PART B

Program 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.
Algorithm
Step 1. Start.
Step 2. Input co-efficient of equation a, b, c.
Step 3. IF any or all the coefficients are zero
Print Invalid input
ELSE
d b2- 4ac
r |d|
IF d > 0
r1 (-b +r)/ (2a)
r2 (-b -r)/ (2a)
Print Roots are REAL and
DISTINCT
Flowchart

Print r1, r2
ELSE IF d < 0
r1 -b/ (2a)
r2 r/ (2a)
Print Roots are COMPLEX
Print r1 +i r2, r1 - i r2
ELSE
r1 -b/ (2a)
Print Roots are EQUAL
Print r1, r1
END IF
END IF
END IF.
Step 4. Stop

Computer Programming Lab Manual 2014-2015


/* C Program Find the Roots of Quadratic Equation */
#include <stdio.h>
#include <math.h>
#include <conio.h>

void main ( )
{
int a, b, c;
float d, x1, x2, r;

clrscr ( );
printf("Enter the three co-efficients:\n"); / * Accept three co-efficients * /
scanf("%d%d%d", &a, &b, &c);
if (a* b* c == 0)
/ * Check for zero co-efficients * /
{
printf("\n Invalid Input ");
}
else
{
d = b * b - 4 * a * c;
r=sqrt(fabs(d));

",x1,x2,x1,x2);
}

if (d > 0)
{
x1 = (-b +r) / (2.0*a);
x2 = (-b -r) / (2.0*a);
printf("\n The roots are real and distinct\n");
printf("\n The roots are \n 1) x1=%f\t\t \n 2) x2=%f",x1,x2);
}
else if (d == 0)
{
x1 = x2 = -b/(2.0*a);
printf("\n The roots are real and equal\n");
printf("\n The roots are: \n 1) x1=x2=%f",x1);
}
else
{
x1 = -b / (2.0 * a);
x2 =r / (2.0*a);
printf("\n The roots are real and imaginary\n");
printf("\n The roots are:\n 1) %f +i %f \t\t\n 2) %f i %f
}

Computer Programming Lab Manual 2014-2015


}

getch( );

Sample Output
First Run
Enter the three co-efficients:
1 4
4
The roots are real and equal
The roots are:
X1=X2=2.0000

Second Run
Enter the three co-efficients:
1 -5
6
The roots are real and distinct
The roots are:
X1=3.0000
X2=2.0000

Third Run
Enter the three co-efficients:
2 3
4
The roots are real and imaginary
The roots are:
1) -0.750000 +i 1.198958
2) -0.750000 - i 1.198958
Fourth Run
Enter the three co-efficients:
1 0
5
Invalid Input

Computer Programming Lab Manual 2014-2015


Program 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.
Algorithm
Step 1. Start
Step 5. Print revs
Step 2. Input n
Step 6. Check IF num EQUAL TO rev
Step 3. Initialize num n, rev 0, rem 0.
Print Palindrome.
Step 4.Repeat until n NOT EQUAL TO 0
ELSE
Compute rem n % 10
Print Not a Palindrome.
Compute rev rev *10 + rem. Step 7. Stop.
Compute n n / 10.
END until
FLOW CHART

Computer Programming Lab Manual 2014-2015


/* C Program to reverse a given integer number and check whether it is a
palindrome or not. */
#include <stdio.h>

#include <conio.h>

void main( )
{
int n, rev=0, rem, num;

clrscr ( );
printf("Enter a number : ");
scanf("%d", &n);
num = n;
while(n != 0)
{
rem=n%10;
rev= rev*10+rem;
n = n / 10;
}
Printf(The reverse of %d is %d, num, rev);
if(num==rev)
printf("\n The given Number %d is Palindrome", num);
else
printf("\n The given Number %d is not Palindrome", num);
getch( );

Sample Output
First Run
Enter a number:
2018

The reverse of 2018 is 8102


The Number 2018 is not Palindrome
Second Run
Enter a number:
5665
The reverse of 5665 is 5665
The Number is Palindrome

Computer Programming Lab Manual 2014-2015


Program 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).
Algorithm
5) If i*i >num

1) Start
2) Read num
3) If num=0
print error
4) Otherwise for i=0 to num repeat step 5

i=i*j
break

end if
6) Print i as square root value
7) End if
8) Stop

//Program to find the square root of a number without using library function
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main( )
{
float n, temp=0.0, s;
clrscr ( );
printf("ENTER ANY NUMBER : ");
scanf("%f", &n);
s = n/2;
while (s != temp)
{
temp = s;
s = (n/s+s)/2;
}
printf("\nSQRT = %.3f, s");
printf(\nSQRT by built-in function = %.3f, sqrt(n));
getch ( );
return 0;
}
Sample Output
Run 1
ENTER ANY NUMBER: 4
SQRT = 2.000
SQRT by built-in function = 2.000

Run 2
ENTER ANY NUMBER: 2
SQRT = 1.414
SQRT by built-in function = 1.414

Computer Programming Lab Manual 2014-2015


Program 3: 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.
Algorithm
1) Start
Print Leap year
2) Read year
4) Otherwise
3) If year%4=0 and year % 100=0 or year
Print Not a Leap Year
%400=0
5) Stop
Flowchart

/* C program to check whether a year is leap year or not using if else statement.*/
#include <stdio.h>
int main( )
{
int year;
clrscr( );
printf("Enter a year: ");
scanf("%d",&year);
if(year%4 == 0 && year%100 != 0 || year % 400 = = 0)
{
printf("\n%d is a leap year.\n", year);
}
else
printf("\n%d is not a leap year.\n", year);
return 0;
}
Sample Output
Run1
Enter a year: 2000
2000 is a leap year

Run 2
Enter a year: 1900
1900 is not a leap year

Run 3
Enter a year: 2014
2014 is not a leap year

Computer Programming Lab Manual 2014-2015


Program 4: Design and develop an algorithm for evaluating the polynomial f(x) =
a4x4+ a3x3 +a2x2+a1x+a0 for a given value of x and its coefficients using Horners
method. Implement a C program for the developed algorithm and execute for
different sets of values of coefficients and x.
Method: Evaluating a polynomial means, finding the value of f(x), given the value of x and
the co-efficient a0, a1, a2, . . . . . , an
In general the polynomial can be of the form
(a0 + x ( a1+ X ( a2 + X (a3 +. . .+ X( an-1 + x. an)))))
In nested parenthesis expression, innermost parenthesis is evaluated first. So, sum (i.e
f(x)) is initialized to a[n]*x. then from (n-1)th term to I term, sum is repeatedly calculated by
the expression sum= sum + a[i])*x. at last, 0th term is added to sum.
Algorithm
Step 1. Start.
Step 5.Compute sum a[n] * x
Step 2. Read the value of number of coStep 6. FOR i n - 1 to 0 in steps of 1
efficients and store in n.
Computesum = (sum + a[ i] ) * x;
Step 3. FOR i 0 to n in steps of 1
Compute sum = sum + a[0];
Read the co-efficients and store in array a[ i]
END FOR.
END FOR
Step 7. Print the value of sum.
Step 4. Read the value of x.
Step 8. Stop.
FLOW CHART

Stop

Computer Programming Lab Manual 2014-2015


/ * C Program to evaluate the given polynomial using Horners method.* /
#include <stdio.h>
#include <conio.h>
void main( )
{
int n, i, x, a[10], sum=0;
clrscr ( );
printf("\n Enter the degree of the polynomial : ");
scanf("%d", &n);
printf("\n Enter the %d coefficients\n",n+1);
for(i = 0 ; i <= n ; i++)
{
scanf("%d", &a[i]);
}
printf("\n Enter the value of x :");
scanf("%d", &x);
/ * Evaluate the polynomial * /
sum=a[n]* x;
for(i = n - 1 ; i >0 ; i - -)
{
sum = (sum + a[i] ) * x;
sum = sum + a[0];
}
printf("\n The sum of polynomial = %d", sum);
getch( ) ;
}
Sample Output
Enter the degree of the polynomial: 4
Enter the 5 coefficients
12345
Enter the value of x:
2
The sum of polynomial = 129

Computer Programming Lab Manual 2014-2015


Program 5: Write C Program to compute Sin(x) using Taylor series approximation
given by Sin(x) = x - (x3/3!) + (x5/5!) - (x7/7!) + . Compare the result with the
built- in Library function and print both the results.
Algorithm
1) Start
6) For i=3 to n compute
2) Read n
term = -term*x*x/(i*(i-1))
3) Read degree
sum = sum+term
4) Convert degree to radians and store in x
i=i+2
x = degree * PI/180;
7) Print calculated sin value in sum
5) Set sum=term=x
8) Print sin value using library function
9) Stop
#include<stdio.h>
#include<math.h>
#define PI 3.1426

int main( )
{
int n, i;
float x, term, sum, degree;
clrscr( );
printf("\nEnter the value of limit\n");
scanf("%d", &n);
printf("Enter Degrees \n");
scanf("%f",&degree);
x = degree * PI/180;
sum = term = x;
for(i = 3; i<=n; i+=2)
{
term = -term*x*x/(i*(i-1));
sum = sum+term;
}
printf("sin(%f) = %f\n",degree, sum);
printf("Using Library Function \n");
printf("sin(%f) = %f\n", degree,sin(x));
getch( );
return 0;
}
Sample output
Enter the value of limit: 5
Enter degrees: 75
Sin (75) = 0.9766
Using Library Function
sin (75) = 0.9765

Computer Programming Lab Manual 2014-2015


Program 6: Develop, implement and execute a C program that reads N integer
numbers and arrange them in ascending order using Bubble Sort technique.
Algorithm
Algorithm

1. Start.
2. Read n.
3. FOR i0 to n-1 in steps of 1
Read integer numbers in array a [ ]
b[i]a[i]
END FOR.
4. FOR i0 to n-1 in steps of 1
FOR j0 to n-i in steps of 1
Check IF a[j] > a[j + 1]
temp= a[j]
a[j] = a[j + 1]
a[j+1] = temp

END IF
END FOR
END FOR
5. Print original array b[i]
FOR i0 to n-1 in steps of 1
Print b[i]
END FOR.
6. Print sorted array a[i]
FOR i0 to n-1 in steps of 1
Print a[i]
END FOR.

Flowchart

Computer Programming Lab Manual 2014-2015


/*Program to sort array elements in ascending order using bubble sort technique*/
#include <stdio.h>
void main( )
{
int n, i, j, a[10], b[10], temp;
printf("\n Enter the no. of elements : ");
scanf("%d", &n);
printf("\n Enter %d elements ",n);
for(i = 0 ; i < n ; i++)
{
scanf("%d",&a[i]);
b[i]=a[i];
}
for(i = 0 ; i < n-1 ; i++)
{
for(j = 0 ; j < n-i; j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf("\n The original elements are\n ");
for(i = 0 ; i < n ; i++)
printf("%d \n",b[i]);
printf("\n The Sorted elements are ");
for(i = 0 ; i < n ; i++)
printf("%d \n",a[i]);
}
Sample Output
Enter the no. of elements : 5
Enter 5 elements
91
15
2
31
4
The original elements are
91
15
2
31
4
The Sorted elements are
2
4
15
31
91

Computer Programming Lab Manual 2014-2015


Program 6: Develop, implement and execute a C program that reads two matrices A
(m x n) and B (p x q) and Compute the product A and B. Read matrix A in row major
order and matrix B in column major order. Print both the input matrices and
resultant matrix with suitable headings and in matrix format. Program must check
the compatibility of orders of the matrices for multiplication. Report appropriate
message in case of incompatibility.
Algorithm
1. Start.
7. Print matrix A
2. Read order m, n
FOR i 0 to m in steps of 1
3. Read order p, q
FOR j 0 to n in steps of 1
4. IF n==p THEN
Print a[i][j]
FOR i 0 to m in steps of 1
END FOR
FOR j 0 to n in steps of 1 END FOR
Read a[i][j]
8. Print matrix B
END FOR
FOR i 0 to p in steps of 1
END FOR
FOR j 0 to q in steps of 1
5. FOR i 0 to p in steps of 1
Print b[i][j]
FOR j 0 to q in steps of 1
END FOR
Read b[i][j]
END FOR
END FOR
9. Print matrix C
END FOR
FOR i 0 to m in steps of 1
6. Matrix multiplication
FOR j 0 to q in steps of 1
FOR i 0 to m in steps of 1
Print c[i][j]
FOR j 0 to q in steps of 1
END FOR
c[i][j] 0
END FOR
FOR k 0 to n in steps of 1
ELSE
c[i][j] c[i][j] + a[i][k] * b[k][j]
Print Multiplication not possible
END FOR
END IF
END FOR
10. Stop.
END FOR
End if

Computer Programming Lab Manual 2014-2015


Flowchart

Computer Programming Lab Manual 2014-2015


/* Program for matrix multiplication */
#include <stdio.h>
void main ( )
{

int a[10][10], b[10][10], c[10][10];


int m, n, p, q, i, j, k;
printf("\n Enter the order of the matrix A :");
scanf("%d%d", &m, &n);
printf("\n Enter the order of the matrix B :");
scanf("%d%d", &p, &q);
if(n==p)
{
printf("\n Enter the elements of matrix A \n");
for(i = 0 ; i < m ; i++)
{
for(j = 0 ; j < n ; j++)
scanf("%d", &a[i][j]); //read matrix a
}
printf("\n Enter the elements of matrix B \n");
for(i = 0 ; i < p ; i++)
{
for(j = 0 ; j < q ; j++)
scanf("%d", &b[i][j]); //read matrix b
}
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] += a[i][k] * b[k][j];
}
}
printf("\n MATRIX A \n");
for(i = 0 ; i < m ; i++)
{
for(j = 0 ; j < n ; j++)
{
printf(" %d \t", a[i][j]); // print matrix a
}
printf("\n");
}
printf("\n MATRIX B \n");
for(i = 0 ; i < p ; i++)
{
for(j = 0 ; j < q ; j++)
{

Computer Programming Lab Manual 2014-2015


printf(" %d \t", b[i][j]); // print matrix b

}
printf("\n");

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

}
else
printf("Matrix A & B is not multipliable");
getch ( );

Sample Output
Run1
Enter the order of the matrix A :2 2
Enter the order of the matrix B :2 2
Enter the elements of matrix A
12
34
Enter the elements of matrix B
23
45
MATRIX A
12
34
MATRIX B
23
45
MATRIX C
10 13
22 29
Run 2
Enter the order of the matrix A: 2 3
Enter the order of the matrix B: 2 3
Matrix A & B is not multipliable

Computer Programming Lab Manual 2014-2015


Program 8: Develop, implement and execute a C program to search a Name in a list of
names using Binary searching Technique.
Algorithm
1. Start
9. IF key = a[mid]
2. Initialize found 0.
Print Successful Search.
3. Read n
Quit searching
4. Read names in ascending order
10. ELSE IF key >a[mid]
5. FOR i 0 to m in steps of 1
lowmid + 1
FOR j 0 to n in steps of 1
ELSE
Read name[i][j]
highmid 1
END FOR
END IF
END FOR
END Until
6. Read key.
11. Print Unsuccessful Search.
7. Initialize low0, highn - 1.
END IF
8. Until low <= high
12. Stop.
mid (low + high)/ 2.
Flow Chart

Computer Programming Lab Manual 2014-2015


/* C program to search a Name in a list of names using Binary searching Technique*/
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main ( )
{
char name[10][20], key[20];
int n, i, low, high, mid, found=0;
clrscr( );
printf("Enter the number of names to read");
scanf("%d",&n);
printf("Enter the names in ascending order\n");
for(i=0;i<n;i++)
scanf("%s",name[i]);
printf("Enter the name to be searched:");
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("Name found in position:%d",mid+1);
else
printf("Name not found");
getch();
return 0;
}
Sample Output
Run 1
Enter the number of names to read: 5
Enter the names in ascending order
Ajay
Biju
Chaya
Dhruv
Firoz
Enter the name to be searched: Dhruv
Name found in position: 4

Run 2
Enter the number of names to read: 5
Enter the names in ascending order
Ajay
Biju
Chaya
Dhruv
Firoz
Enter the name to be searched: Sinchana
Name not found

Computer Programming Lab Manual 2014-2015


Program 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.
Algorithm
1) Start
Function strcopy ( )
2) Read source string S1
1) Start
3) Call strcopy ( ) function with source and 2) Set i=0
destination strings (S1 and S2) as 3) While S1 character not equal to null
parameters
character
4) Print destination string
S2[i]=S1[i]
5) Stop
i=i+1
4) S2[i] = \0
5) stop
#include<stdio.h>
#include<conio.h>
void strcopy(char s1[ ],char s2[ ])
{
int i=0;
while(s1[i]!='\0')
{
s2[i]=s1[i];
i++;
}
s2[i]='\0';
}

int main ( )
{
char str1[50],str2[50];
clrscr( );
printf("Enter the source string: \n");
gets(str1);
strcopy(str1,str2);
printf("Destination string str2: \n");
puts(str2);
getch( );
return 0;
}
Output
Enter the source string:
Acharya Institute
Destination string str2:
Acharya Institute

Computer Programming Lab Manual 2014-2015


ii. Read a sentence and print frequency of vowels and total count of consonants.
1) Start
2) Input str
3) while (str[i] != \0)
4) if (isalpha (str[i]))
5) switch (tolower(srt[i]))
case a: Ca++;
case e: Ce++;
case i: Ci++;
case o: Co++;
case u: Cu++;

Algorithm

break;
break;
break;
break;
break;

default: Cc++;
[end switch]
[end if statement]
6) i++;
[end step 3 while loop]
7) Output Vowels and Consonents
8) Stop

Flowchart

Computer Programming Lab Manual 2014-2015


/*Program to read a sentence and print frequency of vowels and total count of
consonants.*/
#include<stdio.h>
void main( )
{
char str[40];
int i, j, ca=0, ce=0, ci=0, cu=0, co=0, cc=0;
clrscr( );
printf("Enter a string\n");
gets(str);
for(i=0; str[i]!='\0'; i++)
{
if(isalpha(str[i]))
{
switch(toupper(str[i]))
{
case 'A': ca++; break;
case 'E': ce++; break;
case 'I': ci++; break;
case 'O': co++; break;
case 'U': cu++; break;
default : cc++;
}
}
}
printf("The Frequency of the vowel is );
printf("Frequency of A : %d\n",ca);
printf("Frequency of E : %d\n",ce);
printf("Frequency of I : %d\n",ci);
printf("Frequency of O : %d\n",co);
printf("Frequency of U : %d\n",cu);
printf("Number of consonants : %d\n",cc);
getch( );
}
Sample Output
Enter a string
Acharya Institute of Technology
The Frequency of the vowel is
Frequency of A : 3
Frequency of E : 2
Frequency of I : 2
Frequency of O : 3
Frequency of U : 1
Number of consonants :17

Computer Programming Lab Manual 2014-2015


Program 10: a. Design and develop a C function Right Shift (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.
1. Start
2. Read x and n
3. Call function rightshift (x, n)
4. Print the result
5. Stop

Algorithm
Algorithm to rotate value by n bits
1. IF x%2=0
right shift x by 1
ELSE
right shift x by 1 and add 32768 to it
2. Return

/*Program to right shift the bits */


#include<stdio.h>
void main ( )
{
unsigned intans,x,n;
printf("enter x and n values\n");
scanf("%d%d",&x,&n);
ans=rightshift(x,n);
printf("\nThe value after rotating %d bit is : ",n);
printf("%d",ans);
}
unsignedintRightShift(unsigned int x, unsigned int n)
{
int i;
for(i=0; i<n; i++)
{
if(x%2==0)
x=x>>1;
else
{
x=x>>1;
x=x+32768;
}
}
return (x);
}
Sample Output
Enter x and n values
83
The value after rotating 3 bit is: 1

Computer Programming Lab Manual 2014-2015


Program 10: b. Design and develop a function isprime (x) that accepts an integer
argument and returns 1 if the argument is prime and 0 otherwise. The function is to
use plain division checking approach to determine if a given number isprime. Invoke
this function from the main with different values obtained from the user and print
appropriate messages.
Algorithm
1. Start
2. Read the number
3. Call function prime (n)
p= prime (n)
4. IF p 1
Print Number is prime
ELSE
Print Number not a prime
End IF
5. Stop.

Algorithm to check the prime number


1. FOR i 2 to n/2 in steps of 1
IF (n mod i) is equal to zero
Return 0
Return 1
End For
2. Return.
Flowchart

Computer Programming Lab Manual 2014-2015


*Program to generate prime numbers*/
#include <stdio.h>
int isprime (int n)
{
int i;
If (n==0 || n==1)
return 0;
for (i=2; i<=n/2; i++)
if (n % i ==0)
return 0;
return 1;
}
void main ( )
{
int x, y, i, flag=0;
clrscr ( );
printf ("Enter the Range\n");
scanf ("%d%d", &x, &y);
printf (The prime Numbers are\n);
for (i=x; i<=y; i++)
{
If (isprime (i))
{
printf ("%d\t", i);
flag=1;
}
}
if (flag==0)
printf ("There are no prime numbers between the given range\n");
}
Sample output
Run 1
Enter the range
10 20
The prime Numbers are
11 13 17 19

Run2
Enter the range
8 10
There are no prime numbers between the given ranges

Computer Programming Lab Manual 2014-2015


Program 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 C. Tabulate the
results for different values of n and r with suitable messages.
1) Start
2) Input a no n
3) Ncr = Call fact (n)/fact (n-r) * fact (r)
4) Output Ncr
5) Stop

Algorithm
Starting of fact ( )
If n==1 or n==0
Return 1
Otherwise
Return n * fact (n-1)
Flowchart

int fact (int n)

Start
Input n, r
Ncr= fact (n)/fact (n-r) * fact (r)
Output Ncr
Stop
#include<stdio.h>
#include<conio.h>
int fact (int n)
{
if(n==0||n==1)
return 1;
else
return(n*fact(n-1));
}
void main ( )
{
int n, r, ncr;
clrscr( );
printf ("enter the value of n & r\n");
scanf("%d%d", &n, &r);
ncr=fact(n)/fact(n-r)*fact(r);

int fact (int n)


False

Is
n=1 or 0

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

True
return 1

Computer Programming Lab Manual 2014-2015

printf ("The binomial coefficient is %d\n", ncr);


getch ( );

Sample Output
Enter the value of n & r
42
The binomial coefficient is 6

Computer Programming Lab Manual 2014-2015


Program 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
Name1
Name2
.
.
.

USN
USN1
USN2
.
.
.

Start

Open the files student.txt and


usn.txt in read-only mode
F

Is fp==NULL?

Print File Not Found

Read the Contents

Open the file output.txt


F

Until fp! = eof?


T
Student.txt

Usn.txt
Print contents of
Output.txt

Output.txt
Stop

Computer Programming Lab Manual 2014-2015


#include <stdio.h>
#include <conio.h>
int main( )
{
FILE *fp1, *fp2, *fp3;
char usn[20], name[20];
clrscr( );
fp1=fopen ("studname.txt", "r");
if(fp1 == NULL)
{
printf("File not Found");
return 0;
}
fp2 = fopen ("studusn.txt,"r);
if(fp2==NULL)
{
printf ("File Not Found\n");
return 0;
}
fp3=fopen ("output.txt", "w");
while(!feof(fp1) && !feof(fp2) )
{
fscanf(fp1,"%s", name);
fscanf(fp2,"%s", usn);
fprintf(fp3,"%15s %10s\n", name, usn);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
fp3= fopen("output.txt", "r");
printf("------------------------------------------\n");
printf("NAME
USN\n");
printf("------------------------------------------\n");
while(!feof(fp3))
{
fscanf(fp3,"%s",name);
fscanf(fp3,"%s\n", usn);
printf("%-15s %10s\n",name,usn);
}
fclose(fp3);
}
Sample Output
NAME
Abcd
Cdef
Defg
Ghij

USN

1AY14CS001
1AY14CS002
1AY14CS003
1AY14CS004

Computer Programming Lab Manual 2014-2015


Program 13: Write a C program to maintain a record of n student details using an
array of structures with four fields (Roll number, Name, Marks, and Grade). Each
field is of an appropriate data type. Print the marks of the student given student
name as input.
Flowchart
Start

Input student record


Input student i, n
Input S [I]

for i=0 to n-1 do


Is
strcmp (sname, s[i].name=0)
False

True

Output student
record
found = 1

I
Is
found=0

False

Stop

True

Record Not Found


record

Computer Programming Lab Manual 2014-2015


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct student
{
int rollno;
char name[20];
int marks;
char grade;
};
void main ( )
{
struct student s[20];
char sname[20];
int i ,n, found=0;
clrscr( );
printf("Enter the number of students\n");
scanf("%d", &n);
for (i=0; i<n; i++)
{
printf("Enter the %d student details\n", i+1);
printf("Enter the rollno\n");
scanf("%d", &s[i].rollno);
printf("Enter the name\n");
scanf("%s", s[i].name);
printf("Enter the marks\n");
scanf("%d", &s[i].marks);
printf("Enter the grade\n");
scanf("%s", &s[i].grade);
}
printf("The student details are\n");
printf("\nrollno\t name\t\t\t marks\t grade\n");
for (i=0; i<n; i++)
{
printf("%d\t %s\t\t\t %d\t %c\n",
s[i].rollno, s[i].name, s[i].marks,
s[i].grade);
}
printf("Enter the student name\n");
scanf("%s", sname);
for(i=0;i<n;i++)
{
if(strcmp(sname,s[i].name)==0)
{
printf("the marks of%s is %d",sname,s[i].marks);
found=1;
}
}
if (found==0)

Computer Programming Lab Manual 2014-2015

printf("given record not found\n");


getch( );

Sample Output
Enter the number of students
2
Enter the 1 student details
Enter the roll number
15
Enter the student name
Aruna
Enter the marks
24
Enter the grade
A
Enter the 2 student details
Enter the roll number
21
Enter the student name
Krishna
Enter the marks
22
Enter the grade
A
Student details are
Rollno
Name
Marks
Grade
14
Aruna
24
A
21
Krishna
22
A
Enter the student Name to print the marks: Aruna
Marks of the student is: 24

Computer Programming Lab Manual 2014-2015


Program 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.
1. Start
2. Read the values of i and n
3. Set sum = 0 and sumstd = 0
4. for i =0 to n-1 do
A[I]
End for
5. ptr = a
6. for i =0 to n-1 do
7. sum = sum + *ptr
ptr++
Start

Algorithm
8. mean = sum /n
[end step 6 for loop]
9. ptr = a
10. for i =0 to n-1 do
11. sumstd += pow ((*ptr - mean), 2)
12. std = sqrt (sumstd / n)
[end step 10 for loop]
13. Output [Sum, Mean, Standard Deviation]
14. Stop
Flowchart
I

Input i, n

Mean = Sum / n

for i =0 to n-1 do

for i =0 to n-1 do

Sum = 0, Sumstd =0

A [I]
I

ptr = a

for i =0 to n-1 do

Sum= Sum + *ptr


ptr++
I

ptr = a

sumstd += pow ((*ptr - mean), 2)


ptr ++
I

std = sqrt (sumstd / n)

Output Sum, Mean &


Standard Deviation
Stop

Computer Programming Lab Manual 2014-2015


/* Program to find standard deviation */

#include <stdio.h>
#include <conio.h>
#include <math.h>
void main ( )
{
float a[20], sum=0, mean, *ptr, sumstd=0, std;
int i, n;
clrscr( );
printf("Enter the size of the array\n");
scanf("%d", &n);
printf("Enter the array elements\n");
for (i=0; i<n; i++)
scanf("%f", &a[i]); //read array elements
ptr=a;
for (i=0; i<n; i++)
{
sum=sum + (*ptr);
ptr++;
}
mean=sum/n;
ptr=a;
for(i=0;i<n;i++)
{
sumstd = sumstd + pow ((*ptr - mean), 2); //calculate standard deviation
ptr++;
}
std=sqrt(sumstd/n);
printf("sum=%.3f\n, mean=%.3f\n, standard deviation=%.3f\n", sum, mean, std);
getch( );
}
Sample Output
Enter the no of elements
5
Enter the array elements
12345
Sum=15.000
Mean=3.000
Standard deviation=1.414

Computer Programming Lab Manual 2014-2015


VIVA VOCE
1. What is a computer?
2. Who is the father of computer?
3. What are the characteristics of computer?
4. What are applications of computer?
5. What are the different features of computer?
6. What are the functional units of computer?
7. What are the different types of computers?
8. What are the differences between analog and digital computers?
9. What are the different input and output devices?
10. What are the different types of mouse?
11. What is an optical input device?
12. What is barcode?
13. What is barcode reader?
14. What is printer? Mentions the different types of printers.
15. What is an algorithm?
16. What are the characteristics of an algorithm?
17. What are the notations used while writing an algorithm?
18. What is flowchart?
19. List the symbols used while writing flowchart.
20. What is bus? Mention the types of buses.
21. What is pseudo code?
22. What is software development life cycle?
23. Which steps to be followed while developing program?
24. What is testing?
25. What are the different types of testing?
26. What is ASCII?
27. What is software? What are different types of software?
28. What is hardware?
29. What is the difference between System software and Application software?
30. What is an operating system? What are the functions of operating system?
31. What is memory? Why is it required?
32. What are the different types of memory?
33. What is volatile and non-volatile memory?
34. What is cache memory?
35. What are magnetic storage devices?
36. What is a network? What are the advantages of using network?
37. What is LAN? What are the advantages and disadvantages of LAN?
38. What is WAN? What are the advantages and disadvantages of WAN?
39. What is a topology? Explain the different types of topology.
40. What are network linking devices?
41. What is Internet? What are the services of Internet?
42. What is high level language?
43. What is compiler?
44. What are tokens?
45. What are identifiers?
46. What are keywords? How many keywords is their in C programming language?

Computer Programming Lab Manual 2014-2015


47. What is a variable?
48. What is the significance of a variable?
49. What are the rules to be followed while declaring a variable?
50. What is a constant?
51. What is a datatype? What are the different dataypes?
52. What are the basic or primary or fundamental datatypes supported by C
programming language?
53. What are escape sequence characters?
54. What are backslash constants? Name some constants.
55. List the size and range of basic datatypes.
56. What is the difference between a character and string containing a single character?
57. What is the meaning of associativity of an operator?
58. What is left associativity and right associativity?
59. What is side effect?
60. What is implicit type conversion and explicit type conversion (type casting)?
61. What is precedence of an operator means?
62. List the precedence of all the types of operators along with associativity.
63. List the formatted input and output functions.
64. Describe printf() and scanf() functions.
65. What is an expression? What are the different types of expressions?
66. What is compound statement?
67. What is function? What are the advantages of functions?
68. What are the different types of functions?
69. What are the elements of functions?
70. What is a library function?
71. What is calling function and called function?
72. What is the meaning of actual parameter and formal parameter?
73. What is function prototype or function declaration?
74. What is a function call?
75. What are the various categories of user defined functions?
76. What is scope? What is the difference between local scope and global scope?
77. What is logical data?
78. Which are the logical operators?
79. Define decision making statement?
80. How does an if statement work? What are the verities of if-statements?
81. What is the purpose of switch statement? Explain with syntax.
82. What is loop? List the differences between pre-test and post-test loop.
83. What is the meaning of event controlled loop and counter controlled loop?
84. What are the advantages of loops?
85. What is control statement? What are the various types of control statements
available in C language?
86. Explain for loop with syntax.
87. What is the difference between while and do-while loop?
88. What are unconditional control statements (goto)?
89. What is the use of break and continue statements?
90. What is recursion? What are the advantages and disadvantages of recursion?
91. What is an array? What is the difference between an ordinary variable and an array
variable?

Computer Programming Lab Manual 2014-2015


92. How an array will be initialized? Explain with an example.
93. How to declare an array variable?
94. What is bubble sort?
95. What is binary search?
96. What is multi-dimensional array?
97. What are the differences between recursion and iteration?
98. What is string? How strings are represented?
99. How the strings are stored in memory?
100. What is the difference between a character and string containing a single character?
101. How to read all the characters except \n using scanf()?
102. What is the disadvantage of scanf(%s, str);
103. What are various I/O functions used in case of strings?
104. How to declare an array of strings?
105. What is a file?
106. What are difference file operations?
107. What is a structure? How is it different from an array?
108. What is a stack? Mention its applications.
109. What is a Queue? Mention its applications.
110. What is a Linked list? Mention its applications.
111. What is a tree? Mention its applications.
112. Which are the dynamic memory allocation functions available in C?

Você também pode gostar