Sie sind auf Seite 1von 232

First Year B-Tech

COMPUTER PROGRAMMING
AND DATA STRUCTURES












COMPUTER SCIENCE AND ENGINEERING
VIDYA VIKAS INSTITUTE OF TECHNOLOGY
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 2

VIDYA VIKAS INSTITUTE OF TECHNOLOGY










































COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 3

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

UNIT-I
Introduction to Computers:

Computer Systems:
A computer is a machine that manipulates data according to a list of instructions.
A computer is an electronic device that:
o accepts data
o processes data
o produces output
o stores the results for use later
A computer is a system made of two major components: hardware and software. The
computer hardware is the physical equipment. The software is the collection of
programs (instructions) that allow the hardware to do its job.




Computer Hardware
The hardware component of the computer system consists of five parts: input devices,
central processing unit (CPU) ,primary storage, output devices, and auxiliary storage
devices.



Hardware Software
Computer
System

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 4

VIDYA VIKAS INSTITUTE OF TECHNOLOGY


Central Processing Unit (CPU)
CPU - The CPU is the central electronic chip that determines the processing power of
the computer.
- CPU is the brain of the computer.
- It is Responsible for controlling all activities of the computer system.
Today, all CPUs are microprocessors
1. A microprocessor is a complete computer on a silicon chip
2. A microprocessor does all of the functions of a computer
stores data and instructions waiting to be used
follows changeable instructions
does input, processing, and output
CPUs have three basic parts
3. The Arithmetic Logic Unit (ALU)
does all of the mathematics in a computer
does all of the logic comparisons of values
some common logic comparison symbols
= equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
<> not equal
4. The Control Unit
directs the flow of information into the CPU and/or memory or
storage
controls which instructions the CPU will do next
5. Registers
Used to store data and instructions inside the processor
Size of the registers can affect the speed and performance of
the processor
Speed of CPUs
6. The speed of CPUs is measured in hertzs.
A hertz is on cycle per second.
Need to measure time to determine cycles per second
All computers have a clock built into them for timing
the cycles
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 5

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
The clock is usually located in a small metal box on the
motherboard.
Today, many CPUs can complete over six (6) instructions per
second.
7. Speeds of modern CPUs
Most computers have a CPU that can do more than 400 MHz.
MHz stands for megahertzs
A MHz is 1,000,000 cycles per second.
Computers will soon be at speeds of over a gigahertz,
1,000,000,000 Hertzs.
Memory unit:

Memory - Memory is the part of the computer that temporarily stores applications,
documents, and stem operating information.
Generally, memory divide into two categories
1. Primary memory (or) Main memory
2. Secondary memory (or) Auxiliary memory
Primary memory can be used directly by the CPU
1. Consists of silicon chips, usually either VLS or VLSI technology is used to
create the chips
2. Two forms of Primary Memory
o Read Only Memory (ROM)
o Random Access Memory (RAM)
3. Primary memory is also called primary storage
Read Only Memory (ROM)
1. Stores instructions that are used by the CPU
o Tells the CPU how to be the kind of computer it is, for example a
Windows, Macintosh, or Play Station computers.
o Tells the CPU how to work with the different parts of the computer
o ROM can also hold programs that are directly accessed by the CPU.
One such program is the self-test when the computer is first turned on.
The self-test tests to seem if all the parts on the main circuit board
(mother board) are working correctly.
2. The instructions in ROM can not usually be changed
o The instructions are built into the electronic circuits of the chips
o These instructions in ROM are called firmware
o To change the instructions in ROM you need to usually change the
chips or do some other special process that is normally not available to
an average user.
3. The instructions in ROM are nonvolatile. They stay in ROM even when the
computer is turned off.
4. Access to information is random access.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 6

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
o Random access means that any piece of information in ROM can be
accessed at any given time without access other information first. It is
a lot like the tracks on a music CD. You can access any track at any
time and in any order.
o The other kind of access is sequential access. You must access the
information in the order that they are located. This is a lot like a music
tape. You must play the songs in order, or you have to fast forward
past songs to get to the one you want.
Random Access Memory (RAM)
1. Store data and instructions that are used by the CPU to perform some task.
o These instructions are usually loaded into RAM from a secondary
storage device.
o RAM is also used to store instructions that tell the CPU how to work
with its parts. These instructions are usually called drivers.
2. The instructions in RAM are constantly changing, depending on the needs of
the CPU.
3. The instructions in RAM are volatile.
o When the computer is turned off the information in RAM disappears.
o The information in RAM needs to be saved to secondary storage
before the computer is turned off.
4. Access to information is random access.
Secondary memory:
- Secondary memory can be used for stores the large amount of data.
- Secondary memory is not directly interacts with CPU.
- Example: Magnetic disks, Magnetic tapes, optical disks, etc.

Storage Technology

Magnetic storage devices store data by magnetizing particles on a disk or tape.
They have a limited life-span of 1 to 5 years, depending on the device.
Optical storage devices store data as light and dark spots on the disk surface.
They have an unlimited life-span.

How a computer stores information
1. The computer stores information as a string of zeros (0) and ones (1)
The standard string length is eight 0's or 1's in a row
This standard length is called a byte
A byte equals one character
A character is a letter, number, or symbol - it is about
any thing that can be typed on a keyboard
There are 256 standard characters used by almost all
computers
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 7

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
2. Information size measurements
Kilobyte (KB)
One kilobyte equals about 1024 bytes
1KB is about 140 words, about a half page of typed
double-spaced text (words only)
Megabyte (MB)
One megabyte equals about 1000 KB
One megabyte equals about 1,000,000 bytes
One megabyte equals about 500 pages of text, or one
large book
Gigabyte (GB)
One gigabyte equals about 1000 MB
One gigabyte equals about 1,000,000 KB
One gigabyte equals about 1,000,000,000 bytes
One gigabyte equals over 1,000 books of text
Input-output units:
Input and output devices are used to communicate the system with outside world.

Input: the data entered into the system is called input.
Output: the system-produced result is called output.

An input device lets you communicate with a computer. You can use input devices to
enter information and issue commands. A keyboard, mouse, scanner, digital camera,
touch pads and joystick are examples of input devices.
An output device displays information on a screen, creates printed copies or generates
sound. A monitor, printer, and speakers are examples of output devices.
- Input device: Usually a keyboard and mouse, the input device is the conduit
through which data and instructions enter a computer.
- Output device: A display screen, printer, or other device that lets you see what
the computer has accomplished.
Peripheral device: A piece of hardware like a printer or disk drive, that is outside the
main computer.
Computer Software

Computer software is divided in to two broad categories: system software and
application software .System software manages the computer resources .It provides
the interface between the hardware and the users. Application software, on the other
hand is directly responsible for helping users solve their problems.





COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 8

VIDYA VIKAS INSTITUTE OF TECHNOLOGY











Fig: Types of software

System Software:

System software consists of programs that manage the hardware resources of a
computer and perform required information processing tasks. These programs are
divided into three classes: the operating system, system support, and system
development.

The operating system provides services such as a user interface, file and database
access, and interfaces to communication systems such as Internet protocols. The
primary purpose of this software is to keep the system operating in an efficient
manner while allowing the users access to the system.

System support software provides system utilities and other operating services.
Examples of system utilities are sort programs and disk format programs. Operating
services consists of programs that provide performance statistics for the operational
staff and security monitors to protect the system and data.

The last system software category ,system development software, includes the
language translators that convert programs into machine language for execution
,debugging tools to ensure that the programs are error free and computer assisted
software engineering(CASE) systems.

Application software

System
support
System
Development
General
Purpose
Application
Specific
System
software
Application
software
Software
Operating
Systems
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 9

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Application software is broken in to two classes :general-purpose software and
application specific software. General purpose software is purchased from a
software developer and can be used for more than one application. Examples of
general purpose software include word processors ,database management systems
,and computer aided design systems. They are labeled general purpose because they
can solve a variety of user computing problems.

Application specific software can be used only for its intended purpose.
A general ledger system used by accountants and a material requirements planning
system used by a manufacturing organization are examples of application-specific
software. They can be used only for the task for which they were designed they
cannot be used for other generalized tasks.

The relation ship between system and application software is shown in fig-2.In this
figure, each circle represents an interface point .The inner core is hard ware. The user
is represented by the out layer. To work with the system,the typical user uses some
form of application software. The application software in turn interacts with the
operating system ,which is apart of the system software layer. The system software
provides the direct interaction with the hard ware. The opening at the bottom of the
figure is the path followed by the user who interacts directly with the operating
system when necessary.



key terms:
Program: program is a set of instructions for which processes data

Hardware: Physical devices of computer system

Software: Programs that run on computers

Operating system: operating system is a program that controls the entire system

Bit: the smallest piece of information used by the computer. Derived from "binary
digit". In computer language, either a one (1) or a zero (0).
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 10

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

Byte: - a piece of computer information made up of eight bits.

Data: (the plural of datum) information processed by a computer.

Programming language: programming language consists of set of characters and
syntax rules to develops the programs


Computing Environments:

In the early days of computers, there was only one environment: the main frame
computer hidden in a central computing department. With the advent of mini
computers and personal computers, the environment changed, resulting in computers
on virtually every desktop.

Personal Computing Environment

In 1971,Marcian E.Hoff, working for Intel, combined the basic elements of the central
processing unit into the microprocessor. The first computer on a chip was the Intel
4004 and was the grandparent many times removed of Intels current system.

If we are using a personal computer, all of the computer hardware components
are tied together in our personal computer(PC).



Time-Sharing Environment

Employees in large companies often work in what is known as a time-sharing
environment. In the times-sharing environment, many users are connected to one or
more computers. These computers may be minicomputers or central mainframes. The
terminals they use are often nonprogrammable, although today we see more and more
microcomputers being used to simulate terminals. Also, in the time-sharing
environment, the output devices and auxiliary storage devices are shared by all of the
users. A typical
college lab in which a minicomputer is shared is shared by many students is shown in
figure :
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 11

VIDYA VIKAS INSTITUTE OF TECHNOLOGY


In the time-sharing environment ,all computing must be done by the central computer.
The central computer has many duties: It must control the shared resources; it must
manage the shared data and printing and it must do the computing.

Client/Server Environment

A client/server computing environment splits the computing function between a
central computer and users computers. The users are given personal computers or
work stations so that some of the computation responsibility can be moved from the
central computer and assigned to the workstations. In the client-server environment,
the users micro computers or workstations are called the client. The central
computer, which may be a powerful microcomputer, minicomputer, or central
mainframe system, is known as the server. Because the work is now shared between
the users computers and the central computer, response time and monitor display are
faster and the users are more productive.



Distributed Computing

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 12

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
A Distributed Computing environment provides a seamless integration of
computing functions between different servers and clients .The internet provides
connectivity to different servers throughout the world. For example eBay uses several
computers to provide its auction services. This environment provides a reliable,
scalable, and highly available network.
Fig: Distributed Computing



Computer Languages:

To write a program for a computer, we must use a computer language. Over the
years computer languages have evolved from machine languages to natural languages.


1940s Machine level Languages
1950s Symbolic Languages
1960s High-Level Languages

Machine Languages

In the earliest days of computers, the only programming languages available were
machine languages. Each computer has its own machine language, which is made of
streams of 0s and 1s.
Instructions in machine language must be in streams of 0s and 1s because the
internal circuits of a computer are made of switches transistors and other electronic
devices that can be in one of two states: off or on. The off state is represented by 0 ,
the on state is represented by 1.
The only language understood by computer hardware is machine language.

Symbolic Languages:

In early 1950s Admiral Grace Hopper, A mathematician and naval officer developed
the concept of a special computer program that would convert programs into machine
language. The early programming languages simply mirror to the machine languages
using symbols of mnemonics to represent the various machine language instructions
because they used symbols, these languages were known as symbolic languages.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 13

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Computer does not understand symbolic language it must be translated to the machine
language. A special program called assembler translates symbolic code into machine
language. Because symbolic languages had to be assembled into machine language
they soon became known as assembly languages.
Symbolic language uses symbols or mnemonics to represent the various ,machine
language instructions.

High Level Languages:

Symbolic languages greatly improved programming effificiency; they still required
programmers to concentrate on the hardware that they were using. Working with
symbolic languages was also very tedious because each machine instruction has to be
individually coded. The desire to improve programmer efficiency and to change the
focus from the computer to the problem being solved led to the development of high-
level language.
High level languages are portable to many different computers, allowing the
programmer to concentrate on the application problem at hand rather than the
intricacies of the computer. High-level languages are designed to relieve the
programmer from the details of the assembly language. High level languages share
one thing with symbolic languages, They must be converted into machine language.
The process of converting them is known as compilation.
The first widely used high-level languages, FORTRAN (FORmula TRANslation)was
created by John Backus and an IBM team in 1957;it is still widely used today in
scientific and engineering applications. After FORTRAN was COBOL(Common
Business-Oriented Language). Admiral Hopper was played a key role in the
development of the COBOL Business language.
C is a high-level language used for system software and new application code.

Creating and Running Programs:

Computer hardware understands a program only if it is coded in its machine language.
It is the job of the programmer to write and test the program .There are four steps in
this process:1.Writing and Editing the program2.Compiliing the program 3.Linking
the program with the required library modules 4.Executing the program.


COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 14

VIDYA VIKAS INSTITUTE OF TECHNOLOGY



Writing and Editing Programs

The software used to write programs is known as a text editor. A text editor helps us
enter, change, and store character data. Depending on the editor on our system, we
could use it to write letters, create reports, or write programs. The main difference
between text processing and program writing is that programs are written using lines
of code, while most text processing is done with character and lines.

Text editor is a generalized word processor, but it is more often a special editor
included with the compiler. Some of the features of the editor are search commands to
locate and replace statements, copy and paste commands to copy or move statements
from one part of a program to another, and formatting commands that allow us to set
tabs to align statements.
After completing a program, we save our file to disk. This file will be input to the
compiler; it is known as a source file.

Compiling Programs:

The code in a source file stored on the disk must be translated into machine language
,This is the job of the compiler. The c compiler is two separate programs. the
preprocessor and the translator.

The preprocessor reads the source code and prepares it for the translator. While
preparing the code ,it scans for special instructions known as preprocessor commands.
These commands tell the preprocessor to look for special code libraries, make
substitutions in the code ,and in other ways prepare the code for translation into
machine language. The result of preprocessing is called the translation unit.

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 15

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
After the preprocessor has prepared the code for compilation, the translator does the
actual work of converting the program into machine language. The translator reads
the translation unit and writes the resulting object module to a file that can then be
combined with other precompiled units to form the final program. An object module
is the code in machine language. The output of the compiler is machine language
code, but it is not ready to run; that is ,it is not executable because it does not have the
required C and other functions included.

Linking Programs:

A C program is made up of many functions. We write some of these functions, and
they are a part of our source program. There are other functions, such as input/output
processes and, mathematical library functions, that exist elsewhere and must be
attached to our program. The linker assembles all of these functions, ours and systems
into our final executable program.

Executing Programs:

Once program has been linked, it is ready for execution. To execute a program we use
an operating system command, such as run, to load the program into primary memory
and execute it. Getting the program into memory is the function of an operating
system program known as the loader. It locates the executable program and reads it
into memory. When everything is loaded, the program takes control and it begins
execution.

In a typical program execution, the reads data for processing ,either from the user or
from a file. After the program processes the data, it prepares the output. at output can
be to the users monitor or to a file. When the program has finished its job, it tells the
operating system ,which then removes the program from memory.

System Development Method

A software development process is a structure imposed on the development of a
software product. This critical process determines the overall quality and success of
our program. If we carefully design each program using good structured development
techniques, programs will be efficient, error-free, and easy to maintain.


System Development Life Cycle

Todays large-scale modern programming projects are built using a series of
interrelates phases commonly referred to as the system development cycle. Although
the exact number and names of the phases differ depending on the environment there
is general agreement as to the steps that must be followed. One very popular
development life cycle developed, this modal consists of between 5 and 7 phases.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 16

VIDYA VIKAS INSTITUTE OF TECHNOLOGY


The water fall modal starts with systems requirements in this phase the systems
analyst defines requirements that specify what the proposed system is to accomplish.
The requirements are usually stated in terms that the user understands. The analysis
phase looks at different alternatives from a systems point of view while the design
phase determined how the system will be built. In the design phase the functions of
the individual programs that will make up the system are determined and the design of
the files and / or the databases is completed. Finally in the 4
th
phase code, we write the
programs. After the programs have been written and tested to the programmers
satisfaction, the project proceeds to the system test. All of the programs are tested
together to make sure of the system works as a whole. The final phase maintenance
keeps the system working once it has been put into production.
Although the implication of the water falls approach is that the phases flow in a
continuous stream from the first to the last, this is not really the case. As each phase is
developed, errors and omissions will often be found in the previous work. When this
happens it is necessary to go back to the previous phase to rework it for consistency
and to analyze the impact caused by the changes.


ALGORITHM /PSEUDOCODE:

PSEUDOCODE:

Pseudo code is an artificial and informal language that helps programmers
develop algorithams.pseudocode is similar to everyday English, it is convenient and
user friendly although it is not an actual computer programming language.
Psuedocode programs are not actually executed on computer rather they merely help
the programmer think out a program before attempting to write it in a programming
language such as C.
Systems
Requirement
s
Analysis
Design
Code
System Test
Maintenance
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 17

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

ALGORITHM:

Algorithms was developed by an Arab mathematician. It is chalked out step-
by-step approach to solve a given problem. It is represented in an English like
language and has some mathematical symbols like ->, >, <, = etc. To solve a given
problem or to write a program you approach towards solution of the problem in a
systematic, disciplined, non-adhoc, step-by-step way is called Algorithmic approach.
Algorithm is a penned strategy(to write) to find a solution.

An Algorithm is a finite set of instructions, to accomplish a particular task.
Every algorithm must be satisfy the following criteria
Input: zero or more supplied externally
Output: at least one output is produced
Finiteness: the algorithm must be terminated in finite no of steps for all cases
Definiteness: In the algorithm, every instruction must be clear and
unambiguous.
Effectiveness: in the algorithm every instructions must be carried out in any
one case
Programs =Algorithms +Data
An algorithm is also called pseudocode.
An algorithm is the step-by-step method of performing any task.
Each step can be called as an instruction.
The algorithm is part of the blueprint or plan for the computer program, an algorithm
is:
"An effective procedure for solving a problem in a finite number of steps"
It is effective, which means that an answer is found and it finishes, that is it has a finite
number of steps. A well-designed algorithm will always provide an answer, A well-
designed algorithm is also guarantied to terminate.
The key features of an algorithm
Here is an example of an algorithm for making a pot of tea:
1. If the kettle does not contain water then fill the kettle
2. Plug the kettle into the power point and switch it on.
3. If the teapot is not empty then empty the teapot.
4. Place tea leaves in the teapot.
5. If the water in the kettle is not boiling then go to step 5
6. Switch the kettle off.
7. Pour water from the kettle into the teapot.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 18

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Algorithms show these three features:
1. Sequence (also known as Process)
2. Decision (also known as Selection)
3. Repetition (also known as Iteration or Looping)
Sequence
Sequence means that each step or process in the algorithm is executed in the specified
order. In the example algorithm above each process must be in the correct place
otherwise the algorithm will most probably fail.
The Decision constructs - If ... then, If ... then ... else ...
In algorithms the outcome of a decision is either true or false, there is no in between.
The outcome of the decision is based on some condition that can only result in a true
or false value, for example:
if today is Wednesday then collect pay
is a decision and the decision takes the form:
if proposition then process
A proposition in this sense is a statement which can only be true or false, it is either
true that today is Wednesday or it is false that today is Wednesday. It can't be both true
and false. If the proposition is true then the process which follows the then is
executed.
The decision can also be stated as:
if proposition
then process1
else process2
this is the if ... then ... else ... form of the decision. This means that if the proposition
is true then execute process1 else or otherwise execute process2.
The first form of the decision if proposition then process has a null else, that is, there
is no else.
The Repetition constructs - Repeat and While
Repetition takes two forms, the Repeat loop and the While loop.
The repeat loop is used to iterate or repeat a process or sequence of processes until
some condition becomes true. It has the general form:
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 19

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Repeat
Process 1
Process 2
Process N
until proposition
Here is an example:
Repeat
Put water in kettle
until kettle is full
The process is put water in kettle, the proposition is kettle is full.
The repeat loop does some processing before testing the state of the proposition, what
happens though if in the example above the kettle is already full? If the kettle was
already full at the start of the repeat loop, then putting more water in will lead to an
overflow.
In this case the While loop is more appropriate:
While kettle is not full
Put water in kettle
Since the decision about the kettle being full or not is made before putting water in
then the possibility of overflow is eliminated.

Analysis of algorithm:
- Analysis of algorithm means how much system resource to be utilized to
execute the algorithm.
- Algorithm performance can be measured based on time complexity and space
complexity.
- Space complexity: how much system space required to run the algorithm to
execute the algorithm is called space complexity.
- Time complexity: how much system time required to run the algorithm to
execute the algorithm is called Time complexity.
- The main aim of the programmer to produce an algorithm, minimum
utilization of the system resource.

Example: Algorithm/pseudo code to add two numbers

Step 1: Start
Step 2:Read the two numbers in to a,b
Step 3: c=a+b
Step 4: write/print c
Step 5: Stop.

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 20

VIDYA VIKAS INSTITUTE OF TECHNOLOGY



FLOW CHART :

A Flow chart is a Graphical representation of an Algorithm or a portion of an
Algorithm. Flow charts are drawn using certain special purpose symbols such as
Rectangles, Diamonds, Ovals and small circles. These symbols are connected by
arrows called flow lines.
(or)
The diagrammatic representation of way to solve the given problem is called
flow chart.
A flowchart is a graphical representation of an algorithm.
These flowcharts play a vital role in the programming of a problem and are quite
helpful in understanding the logic of complicated and lengthy problems.
Once the flowchart is drawn, it becomes easy to write the program in any high level
language..
A flowchart is a schematic representation of an algorithm or a stepwise process,
showing the steps as boxes of various kinds, and their order by connecting these with
arrows. Flowcharts are used in designing or documenting a process or program.

The following are the most common symbols used in Drawing flowcharts:


Oval Terminal start/stop/begin/end.


Parallelogram Input/output Making data available
For processing(input) or
recording of the process
information(output).


Document Print Out show data output in
the form of document.



Rectangle Process Any processing to be
Done .A process changes
or moves data.An
assignment operation.

Diamond Decision Decision or switching
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 21

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
type of operations.



Circle Connector Used to connect
Different parts of
flowchart.


Arrow Flow Joins two symbols
and also represents
flow of execution.


The following are some guidelines in flowcharting:
a. In drawing a proper flowchart, all necessary requirements should be list out in
logical order.
b. The flowchart should be clear, neat and easy to follow. There should not be
any room for ambiguity in understanding the flowchart.
c. The usual direction of the flow of a procedure or system is from left to right or
top to bottom.
d. Only one flow line should come out from a process symbol.
or
e. Only one flow line should enter a decision symbol, but two or three flow lines,
one for each possible answer, should leave the decision symbol.

f. Only one flow line is used in conjunction with terminal symbol.

h. If the flowchart becomes complex, it is better to use connector symbols to
reduce the number of flow lines. Avoid the intersection of flow lines if you
want to make it more effective and better way of communication.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 22

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
i. Ensure that the flowchart has a logical start and finish.
j. It is useful to test the validity of the flowchart by passing through it with a
simple test data.
Example of a flowchart:
Problem 1: Write an algorithm and draw the flowchart for finding the average of two
numbers
Algorithm:
Input: two numbers x and y
Output: the average of x and y
Steps:
1. input x
2. input y
3. sum = x + y
4. average = sum /2
5. output average



PROGRAM DEVELOPMENT STEPS :

Program Development is a multistep process that requires that we understand the
problem, develop a solution, write the program, and then test it. When we are given
the assignment to develop a program, we will be given a program requirements
statement and the design of any
program interfaces. We should also
receive an overview of the complete
project so that we will take the
inputs we are given and convert
them to the outputs that have been
specified. This is known as program
design.




START
Input x
Input y
Sum = x + y
Average = sum/2
Output
Average
END
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 23

VIDYA VIKAS INSTITUTE OF TECHNOLOGY




In problem solving having different phases

Problem definition: in this phase to understand the problem, and During phase one
the emphasis is on fact gathering and determining where the boundaries of the
problem are.
Problem analysis: in this phase involves the steps of identifying the variables and
processes which make up the problem. Analyze the problem means how much time,
cost, and methods required to solve etc
Algorithm development: In this phase design the problem with the help of algorithm
and flowchart. That means generates the algorithm and flowchart for the problem.
Coding and documentation: in this phase to write the code(program) according to
programming language and prepare the document for the problem. Documentation
means description about probem.
Test and debug: In this phase to test the program, it is properly works or not if any
errors occur, debug the errors and once again test the program. In this phase, also
checks the program produces correct output or not.
Maintenance: The maintenance phase, is the time when the solution is in active use.
It may undergo enhancements or it may have bugs fixed during its lifetime.










COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 24

VIDYA VIKAS INSTITUTE OF TECHNOLOGY



























COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 25

VIDYA VIKAS INSTITUTE OF TECHNOLOGY




UNIT II

INTRODUCTION TO C LANGUAGE:

C is a general-purpose programming language
Dennis Ritchie developed C Language. at AT & T Bell Laboratories of USA
in 1972.
C language was developed based on BCPL (Basic Combined Programming
language) called B language
The American National Standards Institute (ANSI) formed a committee in
1983 to establish a standard definition of C, which became known as ANSI
standard C.
C is a most powerful and flexible language
The first book on C was The C Programming Language by Brian Kernighan and
Dennis Ritchie, published in 1978.
In 1983, the American National Standards Institute (ANSI) established a committee to
standardize the definition of C. The resulting standard is known as ANSI C, and it is
the recognized standard for the language, grammar, and a core set of libraries. The
syntax is slightly different from the original C language, which is frequently called
K&R for Kernighan and Ritchie. There is also an ISO (International Standards
Organization) standard that is very similar to the ANSI standard.
It appears that there will be yet another ANSI C standard officially dated 1999 or in
the early 2000 years; it is currently known as "C9X."

Features of C language:

1. C is robust language.
That means C language contains rich set of operators and built-in functions and
several data types.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 26

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
2. I t is a middle-level language.
That means it support both high level and low level language features
Therefore, it is suitable for developing application software as well as system
software.
3. C is a portable language.
Portable means Programs written in C in one machine can be easily run on
some other machine without any modifications.
4. Fast execution of programs when compared to other languages.
For example, compare to BASIC if you want to increment I value 1 to 20000.It
takes nearly 60sec but our C language takes only 1sec
5. I t has the ability to deal efficiently with bits, bytes, addresses, etc.
6. it is easy to extends itself
That means easily add the new features and develop the other programming
languages
7. C language have only 32 keywords
In C language, have only 32 keywords but other languages have above 200
keywords like COBOL so easily remember the keywords to develop the programs
8. I t is a structured language.
Structured programs means large programs divide into sub programs that is
called modules or functions, easy to understand, easy to debug, maintenance is
very easy, parallel executions

Applications of C:

C is used for writing
Operating systems
Language Translators( Compiles, I nterpreters and
Assemblers)
Editors
Worksheets
Database Management Systems
games

Structure of C program:
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 27

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

The basic structure of C program is

Documentation section
Link Section
Definition Section
Global Declaration Section
main ()
{
Declaration section
Executable section
}
Sub-program Section
Function 1()
{
User defined program area;
}
Function 2 ()
{
Sub program or subroutine;
}

The documentation section consists of a set of comment lines giving the name of the
program, the author and other details such as a short description of the purpose of the
program.

The link section provides instructions to the compiler to link functions from the
system library.

The definition section defines all the symbolic constants. The variables can be
declared inside the main function or before the main function.

Declaring the variables before the main function makes the variables accessible to all
the functions in a C language program, such variables are called Global Variables.

Every C program must have one main() function section.
This section contains two parts, declaration part and executable part.
The declaration part declares all the variables used in the executable part.
There is at least one statement in the executable part.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 28

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
The program execution begins at the opening brace and ends at the closing brace.
The closing brace of the main function section is the logical end of the program.
All statements in the declaration and executable parts end with semicolon(;).

The subprogram section contains all the user-defined functions that are called in the
main function user-defined functions are generally placed immediately after the main
function.

All sections, except the main function, may be absent when they are not required.
Sample C program:

#include <stdio.h>
main ()
{
.../* Printing begins here */
.printf (C is a very good programming language.);
...../* Printing ends here */
}

The first line is a preprocessor command, which adds the stdio header file into our
program. Actually, stdio stands for standard input output; this header file supports the
input-output functions in a program.


The second line main () tell the compiler that it is the starting point of the program,
every program should essentially have the main function only once in the program.
The opening and closing braces indicates the beginning and ending of the program.
All the statements between these two braces form the function body. These statements
are actually the C code, which tells the computer to do something. Each statement is a
instruction for the computer to perform specific task.

The /*... */ is a comment and will not be executed, the compiler simply ignores this
statement. These are essential since it enhances the readability and understandability
of the program. It is a very good practice to include comments in all the programs to
make the users understand what is being done in the program.

The next statement printf() statement is the only executable line in the above sample
program. The printf() function is a standard inbuilt function for printing a given line
which appears inside the double quotes. Therefore, in the standard output device we
can see the following line

C is a very good programming language.

The next line is again a comment statement as explained earlier. The closing brace
indicates the end of the program.

The following basic steps are carried out in executing a C Program.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 29

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

1. Type the C language program.

2. Store the program by giving a suitable name and following it with an extension .c

3. Compile the program

4. Debug the errors if any, that is displayed during compile.

5. Run the program.

Character set:

The character set in C Language can be grouped into the following categories.

1. Letters
2. Digits
3. Special Characters
4. White Spaces

White Spaces are ignored by the compiler until they are a part of string constant.
White Space may be used to separate words, but are strictly prohibited while using
between characters of keywords or identifiers.


C Character-Set Table

Letters

Digits

Upper Case A to Z

0 to 9

Lower Case a to z

.

Special Characters

,

.Comma

&

.Ampersand

.

.Period

^

.Caret
;

.Semicolon

*

.Asterisk

:

.Colon

-

.Minus Sign

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 30

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

C-TOKENS :

Tokens are individual words and punctuations marks in English language
sentence. The smallest individual units are known as C tokens.


E.g. +, -, *

E.g. [ ], { }

E.g. asifia

E.g. -15.4, a, 200

E.g.rate,amount

E.g. int, goto


?

.Question Mark

+

.Plus Sign

'

.Apostrophe

<

.Opening Angle (Less than sign)

"

.Quotation Marks

>

.Closing Angle (Greater than
sign)

!

.Exclamation Mark

(

.Left Parenthesis

|

.Vertical Bar

)

.Right Parenthesis

/

.Slash

[

.Left Bracket

\

.Backslash

]

.Right Bracket

~

.Tilde

{

.Left Brace

-

.Underscore

}

.Right Bracket

$

.Dollar Sign

#

.Number Sign

%

.Percentage Sign . .
OPERATORS

SPECIAL
SYMBOLS
STRINGS
CONSTANTS
IDENTIFIERS
KEY WORDS
C
TOKENS
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 31

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
A C program can be divided into these tokens. A C program contains
minimum 3 c tokens no matter what the size of the program is.

Keywords and Identifiers:

- Keywords have special meaning that is defined by the system.
- Every word in C language is a keyword or an identifier.
- Keywords in C language cannot be used as a variable name.
- They are specifically used by the compiler for its own purpose and they serve
as building blocks of a c program.
- C language have 32 keywords.

The following are the Keyword set of C language.
auto break Case Char const continue
default do double Else enum extern
float for Goto If int long
register return Short Signed sizeof static
struct switch typedef Union unsigned void
volatile while


Identifiers refer to the name of user-defined variables, array and functions. A variable
should be essentially a sequence of letters and or digits and the variable name should
begin with a character.

Both uppercase and lowercase letters are permitted. The underscore character is also
permitted in identifiers.

. The identifiers must conform to the following rules.

1. First character must be an alphabet (or underscore)
2. Identifier names must consists of only letters, digits and underscore.
3. A identifier name should have less than 31 characters.
4. Any standard C language keyword cannot be used as a variable name.
5. A identifier should not contain a space.

Data Types:
A C language programmer has to tell the system beforehand, the type of numbers or
characters he is using in his program. These are data types. There are many data types
in C language. A C programmer has to use appropriate data type as per his
requirement.

C language data types can be broadly classified as

- Primary data type
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 32

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
- Derived data type
- User-defined data type
- Empty set data type

Primary data type
All C Compilers accept the following fundamental data types
1.

Integer

int

2.

Character

char

3.

Floating Point

float

4.

Double precision floating point

double



Integer Type :
- Integers are whole numbers with a machine dependent range of values.
- A good programming language as to support the programmer by giving a
control on a range of numbers and storage space.
- C has 3 classes of integer storage namely short int, int and long int.
- All of these data types have signed and unsigned forms.
- A short int requires half the space than normal integer values.
- Unsigned numbers are always positive and consume all the bits for the
magnitude of the number.
- The long and unsigned integers are used to declare a longer range of values.

Floating Point Types :
- Floating point number represents a real number with 6 digits precision.
- Floating point numbers are denoted by the keyword float.
- When the accuracy of the floating point number is insufficient,
- The double is same as float but with longer precision.
- To extend the precision further we can use long double which consumes 80
bits of memory space.

Character Type :
- A single character can be defined as a defined as a character type of data.
- Characters are usually stored in 8 bits of internal storage.
- The qualifier signed or unsigned can be explicitly applied to char.
- While unsigned characters have values between 0 and 255, signed characters
have values from 128 to 127.

Size and Range of Data Types on 16 bit machine.

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 33

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
TYPE

SIZE (Bits)

Range

Char or Signed Char

8

-128 to 127

Unsigned Char

8

0 to 255

Int or Signed int

16

-32768 to 32767

Unsigned int

16

0 to 65535

Short int or Signed short int

8

-128 to 127

Unsigned short int

8

0 to 255

Long int or signed long int

32

-2147483648 to 2147483647

Unsigned long int

32

0 to 4294967295

Float

32

3.4 e-38 to 3.4 e+38

Double

64

1.7e-308 to 1.7e+308

Long Double

80

3.4 e-4932 to 3.4 e+4932


Void Type :
Using void data type, we can specify the type of a function. It is a good practice to
avoid functions that does not return any values to the calling function.

Derived data types:
The derived data types mean to derived new data type from the basic data types for
examples arrays, structures, unions, etc.

User defined types:
the user defined types means to create a user defined data types. Using typedef, enum,
etc.


Variable:
- A variable is a data name that may be used to store a data value
- A variable is a named location in memory that is used to hold a value that can
be modified by the program
- A variable is an identifier that is used to represent a specified type of data
- All variable must be declared before they can be used
- Variables can be declared in three places: inside functions, in the definition of
function parameters, and outside of all functions

The rules to form the variables are
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 34

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
1 The variable name can be up to 31 characters long
2 The first character of variable name must be a letter, or underscore
3 The variable name should not be a keyword
4 White space not allowed
5 All variable names are case sensitive
6 The names are made up of letters, digits, underscore

Declaration of Variables:

The syntax for declaring a variable is as follows

data-type v1,v2, vn;

Declaration does two things
1 it tells the compiler what the variable name is
2 it specifies what type of data the variable will hold.

A Variable can be used to store a value of any data type
v1,v2, vn are the names of the variables, variables are separated by commas

A declaration statement must end with semicolon

Ex: int sum,sub;
float avg;
double x1,y,z;

Constants:

A constant value is the one, which does not change during the execution of a program.
C supports several types of constants.

1. Integer Constants
2. Real Constants
3. Single Character Constants
4. String Constants

Integer Constants
An integer constant is a sequence of digits. There are 3 types of integers namely
decimal integer, octal integers and hexadecimal integer.

Decimal I ntegers consists of a set of digits 0 to 9 preceded by an optional + or - sign.
Spaces, commas and non digit characters are not permitted between digits.
Example for valid decimal integer constants are

123
-31
0
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 35

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
562321
+ 78

Some examples for invalid integer constants are

15 750
20,000
Rs. 1000

Octal I ntegers constant consists of any combination of digits from 0 through 7 with a
O at the beginning. Some examples of octal integers are

O26
O
O347
O676

Hexadecimal integer constant is preceded by OX or Ox, they may contain alphabets
from A to F or a to f. The alphabets A to F refers to 10 to 15 in decimal digits.

Example of valid hexadecimal integers are

OX2
OX8C
OXbcd
Ox

Real Constants
Real Constants consists of a fractional part in their representation. Integer constants
are inadequate to represent quantities that vary continuously. These quantities are
represented by numbers containing fractional parts like 26.082. Example of real
constants are

0.0026
-0.97
435.29
+487.0

Real Numbers can also be represented by exponential notation. The general form for
exponential notation is mantissa exponent. The mantissa is either a real number
expressed in decimal notation or an integer. The exponent is an integer number with
an optional plus or minus sign.

Single Character Constants
A Single Character constant represent a single character which is enclosed in a pair of
quotation symbols.

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 36

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Example for character constants are

'5'
'x'
';'
' '

All character constants have an equivalent integer value which are called ASCII
Values.

String Constants
A string constant is a set of characters enclosed in double quotation marks. The
characters in a string constant sequence may be a alphabet, number, special character
and blank space.
Example of string constants are

"VISHAL"
"1234"
"God Bless"
"!.....?"

Backslash Character Constants [Escape Sequences]
Backslash character constants are special characters used in output functions.
Although they contain two characters they represent only one character. Given below
is the table of escape sequence and their meanings.

\a Audible Alert
\b Backspace
\f Formfeed
\n new line
\r carriage return
\t Horizontal tab
\v Vertical Tab
\ Single Quote
\ Double Quote
\\ Back Slash
\? Question Mark
\0 Null

Operators:

An operator is a symbol that performs the operation on the operands.
An operator is a symbol that operates on a certain data type and produces the output
as the result of the operation. The operand is a either variable or constant.

The C compiler tries to solve the expression as per the rules of precedence.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 37

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Category of operators
Unary Operators
A unary operator is an operator, which operates on one operand.
Binary
A binary operator is an operator, which operates on two operands
Ternary
A ternary operator is an operator, which operates on three operands.

Following are the different types of Operators

1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment operator
5. Increments and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators

1. Arithmetic Operator
The arithmetic operator is a binary operator, which requires two operands to perform
its operation of arithmetic.
Following are the arithmetic operators that are available
Operator Description
+ Addition
- Subtraction
/ Division
* Multiplication
% Modulo or remainder
Examples:
2+3*5
a*b

2. Relational Operators
Relational operators compare between two operands and return in terms of true or
false i.e. 1 or 0.
In C and many other languages a true value is denoted by the integer 1 and a false
value is denoted by the integer 0.
Relational operators are used in conjunction with logical operators and conditional &
looping statements.
Following are the various relational operators
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
Closely related to the relational operators is the equality operator as follows:
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 38

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
== Equal to
!= Not equal to
Example:
Suppose we have three integer variables a, b and c with values 1,2 and 3 respectively.
Expression Returns Meaning
A<b 1 True
(b+c)>(a+5) 0 False
(c!=3) 0 False
B==2 1 True

3. Logical Operators
A logical operator is used to compare or evaluate logical and relational expressions.
There are three logical operators available in the C language.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Truth table for Logical AND Truth table for Logical OR

1 1 1
1 0 1
0 1 1
0 0 0

4. Assignment Operator
An assignment operator (=) is used to assign a constant or a value of one variable to
another.
Example:
a = 5;
b = a;
result = (a/b) * 100;
Multiple assignments:
You can use the assignment for multiple assignments as follows:
a = b= c = 10;
At the end of this expression all variables a, b and c will have the value 10. Here the
order of evaluation is from right to left. First 10 is assigned to c, hence the value of c
now becomes 10. After that, the value of c (which is now 10) is assigned to b, hence
the value of b becomes 10. Finally, the value of b (which is now 10) is assigned to a,
hence the value of a becomes 10.
Arithmetic Assignment Operators
Arithmetic Assignment operators are a combination of arithmetic and the assignment
operator. With this operator, the arithmetic operation happens first and then the result
of the operation is assigned.
1 1 1
1 0 0
0 1 0
0 0 0
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 39

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
+=, -=, *=, /=, %=
Ex: a+=4 expand as a=a+4

5. Increment and Decrement Operators
The increment and decrement operators are very useful in C language. They are
extensively used in for and while loops.
The syntax of these operators is given below.
++
++


The ++ operator increments the value of the variable by one, whereas the operator
decrements the value of the variable by one.

These operators can be used in either the postfix or prefix notation as follows:
Postfix: a++ or a
Prefix: ++a or a



Postfix notation
In the postfix notation, the value of the operand is used first and then the operation of
increment or decrement takes place, e.g. consider the statements below:
int a,b;
a = 10;
b = a++;
printf(%d\n,a);
printf(%d\n,b);
Program Output
10
11

Prefix notation
In the prefix notation, the operation of increment or decrement takes place first after
which the new value of the variable is used.
int a,b;
a = 10;
b = ++a;
printf(%d\n,a);
printf(%d\n,b);
Program Output
11
11

6. Conditional Operator
A conditional operator checks for an expression, which returns either a true or a false
value. If the condition evaluated is true, it returns the value of the true section of the
operator, otherwise it returns the value of the false section of the operator.
Its general structure is as follows:
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 40

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Expression1 ? expression 2 (True Section): expression3 (False Section)
Example:
a=3,b=5,c;

c = (a>b) ? a+b : b-a;
The variable c will have the value 2, because when the expression (a>b) is checked, it
is evaluated as false. Now because the evaluation is false, the expression b-a is
executed and the result is returned to c using the assignment operator.

7. Bitwise Operators
C has a distinction of supporting special operators known as bitwise operators for
manipulation data at bit level. A bitwise operator operates on each bit of data. Those
operators are used for testing, complementing or shifting bits to the right on left.
Bitwise operators may not be applied to a float or double.

Operator

Meaning

&

Bitwise AND

|

Bitwise OR

^

Bitwise Exclusive

<<

Shift left

>>

Shift right


Examples: a=10, b=6
c= a&b;
Result is c = 14


8. Special Operators
C supports some special operators of interest such as comma operator, size of
operator, pointer operators (& and *) and member selection operators (. and ->). The
size of and the comma operators are discussed here. The remaining operators are
discussed in forth coming chapters.
The Comma Operator
The comma operator can be used to link related expressions together. A comma-
linked list of expressions are evaluated left to right and value of right most expression
is the value of the combined expression.
For example the statement
value = (x = 10, y = 5, x + y);
First assigns 10 to x and 5 to y and finally assigns 15 to value. Since comma has the
lowest precedence in operators the parenthesis is necessary. Some examples of
comma operator are
In for loops:
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 41

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
for (n=1, m=10, n <=m; n++,m++)
The size of Operator
The operator size of gives the size of the data type or variable in terms of bytes
occupied in the memory. The operand may be a variable, a constant or a data type
qualifier.
Example
m = sizeof (sum);
n = sizeof (long int);
k = sizeof (235L);
The size of operator is normally used to determine the lengths of arrays and structures
when their sizes are not known to the programmer. It is also used to allocate memory
space dynamically to variables during the execution of the program.

Type Conversions:

When an operators operands are of different data types, C automatically
converts them to the same data type. This can affect the results of mathematical
expressions. This is called type conversion. In C type conversion can be done by two
ways

Automatic Conversion (Arithmetic Promotion):

When a value is converted to a higher type, it is said to be promoted. Lets look at
the specific rules that govern the evaluation of mathematical expressions.

Rule 1: chars, shorts, unsigned shorts are automatically promoted to int.
Rule 2: When an operator works with two values of different data types, the lower
data type is promoted to a higher data type.

Type Casting
Type casting means to convert a higher data type to a lower data type. For the purpose
of type casting we require to use the type case operator, which lets you manually
promote or demote a value. It is a unary operator which appears as the data type name
followed by the operand inside a set of parentheses. E.g.
val = (int)number;

Explicit Conversion
Many times there may arise a situation where we want to force a type conversion in a
way that is different from automatic conversion.
The general form is
(type_name) expression

int b,c;
float a
Example: a=(float)b/c;

Expressions:

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 42

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Arithmetic Expressions
An expression is a combination of variables constants and operators written according
to the syntax of C language. In C every expression evaluates to a value i.e., every
expression results in some value of a certain type that can be assigned to a variable.
Some examples of C expressions are shown in the table given below.

Algebraic
Expression
C Expression

a x b c

a * b c

(m + n) (x +
y)

(m + n) * (x +
y)

(ab / c)

a * b / c

3x
2
+2x + 1

3*x*x+2*x+1

(x / y) + c

x / y + c


Order of Evaluation of Expressions

Expressions are evaluated using an assignment statement of the form
Variable = expression;
Variable is any valid C variable name. When the statement is encountered, the
expression is evaluated first and then replaces the previous value of the variable on
the left hand side. All variables used in the expression must be assigned values before
evaluation is attempted.

Example of evaluation statements are

x = a * b c
y = b / c * a
z = a b / c + d;

The following program illustrates the effect of presence of parenthesis in expressions.

.
main ()
{
float a, b, c x, y, z;
a = 9;
b = 12;
c = 3;
x = a b / 3 + c * 2 1;
y = a b / (3 + c) * (2 1);
z = a ( b / (3 + c) * 2) 1;
printf (x = %fn,x);
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 43

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
printf (y = %fn,y);
printf (z = %fn,z);
}
.

output

x = 10.00
y = 7.00
z = 4.00

Precedence in Arithmetic Operators
An arithmetic expression without parenthesis will be evaluated from left to right using
the rules of precedence of operators. There are two distinct priority levels of
arithmetic operators in C.

High priority * / %
Low priority + -

Rules for evaluation of expression
First parenthesized sub expression left to right are evaluated.
If parenthesis is nested, the evaluation begins with the innermost sub expression.
The precedence rule is applied in determining the order of application of operators in
evaluating sub expressions.
The associability rule is applied when two or more operators of the same precedence
level appear in the sub expression.
Arithmetic expressions are evaluated from left to right using the rules of precedence.
When Parenthesis are used, the expressions within parenthesis assume highest priority.
Type conversions in expressions:

Implicit type conversion
C permits mixing of constants and variables of different types in an expression. C
automatically converts any intermediate values to the proper type so that the
expression can be evaluated without loosing any significance. This automatic type
conversion is know as implicit type conversion
During evaluation it adheres to very strict rules and type conversion. If the operands
are of different types the lower type is automatically converted to the higher type
before the operation proceeds. The result is of higher type.
The following rules apply during evaluating expressions
All short and char are automatically converted to int then
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 44

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
1. If one operand is long double, the other will be converted to long double and result
.....will be long double.
2. If one operand is double, the other will be converted to double and result will be
double.
.3. If one operand is float, the other will be converted to float and result will be float.
.4. If one of the operand is unsigned long int, the other will be converted into
unsigned
.....long int and result will be unsigned long int.
5. If one operand is long int and other is unsigned int then
....a. If unsigned int can be converted to long int, then unsigned int operand will be
.........converted as such and the result will be long int.
.....b. Else Both operands will be converted to unsigned long int and the result will be
..........unsigned long int.
6. If one of the operand is long int, the other will be converted to long int and the
result will be long int. .
7. If one operand is unsigned int the other will be converted to unsigned int and the
.....result will be unsigned int.

Operator precedence and associativity:

Each operator in C has a precedence associated with it. The precedence is used to
determine how an expression involving more than one operator is evaluated. There
are distinct levels of precedence and an operator may belong to one of these levels.
The operators of higher precedence are evaluated first.
The operators of same precedence are evaluated from right to left or from left to right
depending on the level. This is known as associativity property of an operator.

The table given below gives the precedence of each operator.

Order Category Operator Operation

Associativity
1

Highest
precedence

( )
[ ]

: :
.

Function call

L R
Left to Right

2

Unary

!
~
+
-
++
- -
&
*
Size of

Logical negation
(NOT)
Bitwise 1s
complement
Unary plus
Unary minus
Pre or post increment
Pre or post decrement
Address
Indirection
Size of operant in bytes
R L
Right -> Left

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 45

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

3

Member Access

.*
*

Dereference
Dereference

L R

4

Multiplication

*
/
%

Multiply
Divide
Modulus

L R

5

Additive

+
-

Binary Plus
Binary Minus

L R

6

Shift

<<
>>

Shift Left
Shift Right

L R

7

Relational

<
<=
>
>=

Less than
Less than or equal to
Greater than
Greater than or equal to

L R

8

Equality

==
!=

Equal to
Not Equal to

L R

9

Bitwise AAND

&

Bitwise AND

L R

10

Bitwise XOR

^

Bitwise XOR

L R

11

Bitwise OR

|

Bitwise OR

L R

12

Logical AND

&&

Logical AND

L R

14

Conditional

? :

Ternary Operator

R L

15

Assignment

=
*=
%=
/=
+=
-=
&=
^=
|=
<<=
>>=

Assignment
Assign product
Assign reminder
Assign quotient
Assign sum
Assign difference
Assign bitwise AND
Assign bitwise XOR
Assign bitwise OR
Assign left shift
Assign right shift

R L

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 46

VIDYA VIKAS INSTITUTE OF TECHNOLOGY


Basic Input and Output Operations:

- One of the essential operations performed in a C language programs is to
provide input values to the program and output the data produced by the
program to a standard output device.
- We can assign values to variable through assignment statements such as x = 5
a = 0 ; and so on.
- Another method is to use the Input then scanf which can be used to read data
from a key board. For outputting results we have used extensively the function
printf which sends results out to a terminal.
- There exists several functions in C language that can carry out input output
operations.
- These functions are collectively known as standard Input/Output Library.
- Each program that uses standard input / out put function must contain the
statement.

# include < stdio.h >

at the beginning.
- Input and output statements are generally two types formatted and unformatted
- Unformatted input-output functions are used for only character data type
- Formatted input-output functions are deal with any type of data.

Formatted input-output functions:

The formatted input refers to input data that has been arranged in a particular format.
Input values are generally taken by using the scanf function.
The scanf function has the general form.

Scanf (control string, arg1, arg2, arg3 .argn);

The format field is specified by the control string and the arguments
arg1, arg2, .argn specifies the addrss of location where address is to be
stored.

The control string specifies the field format which includes format specifications and
optional number specifying field width and the conversion character % and also
blanks, tabs and newlines.

The Blanks tabs and newlines are ignored by compiler. The conversion character % is
followed by the type of data that is to be assigned to variable of the assignment. The
field width specifier is optional.

The general format for reading a integer number is

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 47

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
% x d

Here percent sign (%) denotes that a specifier for conversion follows and x is an
integer number which specifies the width of the field of the number that is being read.
The data type character d indicates that the number should be read in integer mode.

Example :

scanf (%3d %4d, &sum1, &sum2);

If the values input are 175 and 1342 here value 175 is assigned to sum1 and 1342 to
sum 2. Suppose the input data was follows 1342 and 175.

The number 134 will be assigned to sum1 and sum2 has the value 2 because of %3d
the number 1342 will be cut to 134 and the remaining part is assigned to second
variable sum2. If floating point numbers are assigned then the decimal or fractional
part is skipped by the computer.

To read the long integer data type we can use conversion specifier % ld & % hd for
short integer.

Input specifications for real number:

Field specifications are not to be use while representing a real number therefore real
numbers are specified in a straight forward manner using % f specifier.

The general format of specifying a real number input is

Scanf (% f , &variable);

Example:

Scanf (%f %f % f, &a, &b, &c);

With the input data

321.76, 4.321, 678 The values
321.76 is assigned to a , 4.321 to b & 678 to C.

If the number input is a double data type then the format specifier should be % lf
instead of %f.

Input specifications for a character.

Single character or strings can be input by using the character specifiers.
The general format is

% xc or %xs
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 48

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

Where C and S represents character and string respectively and x represents the field
width.
The address operator need not be specified while we input strings.

Example :

Scanf (%C %15C, &ch, nname):

Here suppose the input given is a, Robert then a is assigned to ch and name will be
assigned to Robert.

Printing One Line:

printf();

The most simple output statement can be produced in C Language by using printf
statement. It allows you to display information required to the user and also prints the
variables we can also format the output and provide text labels. The simple statement
such as
Syntax
The general form of the printf() is
Printf (conversion string, variable list);

The conversion string includes all the text labels, escape character and conversion
specifiers required for the desired output. The variable includes all the variable to be
printed in order they are to be printed. There must be a conversion specifies after each
variable. Printf (Enter 2 numbers);

Prompts the message enclosed in the quotation to be displayed.

A simple program to illustrate the use of printf statement:-

#include < stdio.h >
main ( )
{
printf (Hello!);
printf (Welcome to the world of Engineering!);
}

Output:

Hello! Welcome to the world of Engineering.

Both the messages appear in the output as if a single statement. If you wish to print
the second message to the beginning of next line, a new line character must be placed
inside the quotation marks.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 49

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

For Example :

printf (Hello!\n);
OR
printf (\n Welcome to the world of Engineering);

Conversion Strings and Specifiers:
The printf ( ) function is quite flexible. It allows a variable number of arguments,
labels and sophisticated formatting of output. The general form of the printf ( )
function is

Specifier Meaning
%c Print a character
%d Print a Integer
%i Print a Integer
%e Print float value in exponential form.
%f Print float value
%g Print using %e or %f whichever is smaller
%o Print actual value
%s Print a string
%x Print a hexadecimal integer (Unsigned) using lower case a F
%X Print a hexadecimal integer (Unsigned) using upper case A F
%a Print a unsigned integer.
%p Print a pointer value
%hx hex short
%lo octal long
%ld long



Unformatted input-output cunctions:

Single character input output:
The basic operation done in input output is to read a characters from the standard
input device such as the keyboard and to output or writing it to the output unit usually
the screen. The getchar function can be used to read a character from the standard
input device. The scanf can also be used to achieve the function.

The getchar has the following form.

Variable name = getchar():

Variable name is a valid C variable, that has been declared already and that possess
the type char.

Example program :
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 50

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

# include < stdio.h > // assigns stdio-h header file to
your program
void main ( ) // Indicates the starting point of the
program.
{
char C, // variable declaration
printf (Type one character:) ; // message to user
C = getchar () ; // get a character from key board and
Stores it in variable C.
Printf ( The character you typed is = %c, C) ; //
output
} // Statement which displays value of C on
// Standard screen.

The putchar function which in analogus to getchar function can be used for writing
characters one at a time to the output terminal. The general form is

putchar (variable name);

Where variable is a valid C type variable that has already been declared Ex:-

Putchar ( );

Displays the value stored in variable C to the standard screen.

Program shows the use of getchar function in an interactive environment.

#include < stdio.h > // Inserts stdio.h header file into the
Pgm
void main ( ) // Beginning of main function.
{
char in; // character declaration of variable in.
printf ( please enter one character); // message to user
in = getchar ( ) ; // assign the keyboard input value to in.
putchar (in); // out put in value to standard screen.
}

String input and output:
The gets function relieves the string from standard input device while put S outputs
the string to the standard output device. A strong is an array or set of characters.

The function gets accepts the name of the string as a parameter, and fills the string
with characters that are input from the keyboard till newline character is encountered.
(That is till we press the enter key). All the end function gets appends a null
terminator as must be done to any string and returns.


COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 51

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
The puts function displays the contents stored in its parameter on the standard screen.

The standard form of the gets function is

gets (str)

Here str is a string variable.

The standard form for the puts character is

puts (str)

Where str is a string variable.

Eample program (Involving both gets and puts)

# include < stdio.h >
Void main ( )
{
char s [80];
printf (Type a string less than 80 characters:);
gets (s);
printf (The string types is:);
puts(s);
}



Statements and blocks:
- A statement is a single command that performs some activity when
executed by the Compiler or interpreter.
- Two basic statements - expression statements, declaration statements.
- Expression statements - such as i++ -have a semi-colon at the end.
- Ex: printf(Have a Nice Day);
Expressions that can be made into statements
- Assignment: those that contain =
- Prefix or postfix forms of ++ and -
- Methods calls.
- Object creation statements (new operator).
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 52

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Declaration statements
- Declare a variable and initialize it to a value.
- Can appear anywhere inside a block.
- Local variables exist only as long as the block containing their code is
executing.
- Braces group zero or more statements into a block.
A pair of braces { and } is used to group declarations and statements together into a
compound statement or block. these are syntactically equivalent to a single statement.
The variables can be declared inside any block.
A program block is a group of statements that have the following two characteristics:
They have a single entry point and a single exit point. A loop has a program block at
its heart. A loop is used to repeatedly perform an operation or a block of code
through the use of a conditional expression.
The proper use of braces and indentations are important to maintain readable code.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
{
int a=20;
printf("\n in inner block a=%d",a);
}
printf("\n in outer block a=%d",a);
getch();
}
Output:
in inner block a=20
in outer block a=10


Control statements:

A control statement specifies the flow of the execution of the program.

- Sequence control statements
- Conditional control statements
- Repetitive structure/loops
- Unconditional control statements

Sequence control statements:
In Sequence control statements the flow of execution is sequence. That means the
program executions starts from first statement and executes one by one statements up
to end of the last statements statement, what they appear in the program.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 53

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

Conditional control statements:
Conditional control statements are used to check the conditions, depending on the
conditions the statements will be executes or not.

Conditional control statements are
- simple if
- if else
- nested if else
- else if ladder
- switch case

Simple if:

The simplest form of the control statement is the If statement. It is very frequently
used in decision making and allowing the flow of program execution.

The If structure has the following syntax
if (expression)
{
statement-block;
}

if the expression is nonzero(true), then statement is executed; otherwise, skip the
statement and control passes to the next statement.
Ex:
#include<stdio.h>
#include<conio.h>
void main()
{
Int marks=70;
true

false

Expression

Statement-block

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 54

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
if ( marks>=60)
printf(passed in first grade\n);
printf(good bye);
}

Output:
Passed in first grade
Good bye

The message passed in first grade is printed only when the value of marks is greater
than or equal to 60. the second printed (next statement) is always executed.

Usually the expression in an if statement is a relational, equality, or logical
expression.

The condition part should not end with a semicolon.

if else:

The syntax of the If else construct is as follows:-
if( test condition)
{
Statement-1;
}
else
{
Statement-2;
}



true

false

Expression

true

Statement-1

Statement-2

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 55

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

The if else is actually just on extension of the general format of if statement. If the
result of the condition is true, then program statement 1 is executed, otherwise
program statement 2 will be executed. If any case either program statement 1 is
executed or program statement 2 is executed but not both.

#include<stdio.h>
main()
{
int n;
clrscr();
printf(enter n value);
if(n>0)
printf(given number is positive);
else
printf(given number is negative);
}

Output:
enter n value 10
given number is positive

In the above program the If statement checks whether the given number is less than 0.
If it is less than zero then it is negative therefore the condition becomes true then the
statement The number is negative is executed. If the number is not less than zero the
If else construct skips the first statement and prints the second statement declaring
that the number is positive.

Nested if-else:
The if statement may itself contain another if statement is known as nested if
statement.

Syntax:
if (condition1)
if (condition2)
statement-1;
else
statement-2;
else
statement-3;

The if statement may be nested as deeply as you need to nest it. One block of
code will only be executed if two conditions are true. Condition 1 is tested first and
then condition 2 is tested. The second if condition is nested in the first. The second if
condition is tested only when the first condition is true else the program flow will skip
to the corresponding else statement.

Sample Code
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 56

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
1. #include <stdio.h> //includes the stdio.h file to your program
2. main () //start of main function
3. {
4. int a,b,c,big //declaration of variables
5. printf ("Enter three numbers") //message to the user
6. scanf ("%d %d %d", &a, &b, &c) //Read variables a,b,c,
7. if (a > b) // check whether a is greater than b if true then
8. if (a > c) // check whether a is greater than c
9. big = a // assign a to big
10. else big = c // assign c to big
11. else if (b > c) // if the condition (a > b) fails check whether b is greater
than c
12. big = b // assign b to big
13. else big = c // assign c to big
14. printf ("Largest of %d, %d & %d = %d", a,b,c,big) //print the given
numbers along with the largest number
15. }

In the above program the statement if (a>c) is nested within the if (a>b). If the first If
condition if (a>b)

If (a>b) is true only then the second if statement if (a>b) is executed. If the first if
condition is executed to be false then the program control shifts to the statement after
corresponding else statement.

Else if ladder:

When a series of many conditions have to be checked we may use the ladder else if
statement which takes the following general form.

if (condition1)
statement 1;
else if (condition2)
statement2;
else if (condition3)
statement3;
else if (condition)
statement n;
else
default statement;
statement-x;

This construct is known as if else construct or ladder. The conditions are evaluated
from the top of the ladder to downwards. As soon on the true condition is found, the
statement associated with it is executed and the control is transferred to the statement
x (skipping the rest of the ladder. When all the condition becomes false, the final
else containing the default statement will be executed.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 57

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
* Example program using If else ladder to grade the student according to the
following rules.

Marks Grade
70 to 100
60 to 69
50 to 59
40 to 49
0 to 39

DISTINCTION
IST CLASS
IIND CLASS
PASS CLASS
FAIL

Sample Code
1. #include <stdio.h> //include the standard stdio.h header file
2. void main () //start the function main
3. {
4. int marks //variable declaration
5.
6. printf ("Enter marks\n") //message to the user
7. scanf ("%d", &marks) //read and store the input marks.
8.
9. if (marks <= 100 && marks >= 70) //check whether marks is less than
100 or greater than 70
10. printf ("\n Distinction") //print Distinction if condition is True
11. else if (marks >= 60) //else if the previous condition fails Check
12. printf("\n First class") //whether marks is > 60 if true print Statement
13. else if (marks >= 50) //else if marks is greater than 50 print
14. printf ("\n second class") //Second class
15. else if (marks >= 35) //else if marks is greater than 35 print
16. printf ("\n pass class") //pass class
17. else
18. printf ("Fail") //If all condition fail apply default condition print Fail
19. }


The above program checks a series of conditions. The program begins from the first if
statement and then checks the series of conditions it stops the execution of remaining
if statements whenever a condition becomes true.

In the first If condition statement it checks whether the input value is lesser than 100
and greater than 70. If both conditions are true it prints distinction. Instead if the
condition fails then the program control is transferred to the next if statement through
the else statement and now it checks whether the next condition given is whether the
marks value is greater than 60 If the condition is true it prints first class and comes out
of the If else chain to the end of the program on the other hand if this condition also
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 58

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
fails the control is transferred to next if statements program execution continues till
the end of the loop and executes the default else statement fails and stops the program.

Switch case:

Unlike the If statement which allows a selection of two alternatives the switch
statement allows a program to select one statement for execution out of a set of
alternatives. During the execution of the switch statement only one of the possible
statements will be executed the remaining statements will be skipped.
The switch statement is the multi-way decision making statements.
The usage of multiple If else statement increases the complexity of the
program since when the number of If else statements increase it affects the readability
of the program and makes it difficult to follow the program.
The switch statement removes these disadvantages by using a simple and
straight forward approach.

The general format of the Switch Statement is :
switch (expression)
{
case case-label-1: statement-1;
case case-label-2: statement-2;
..


case case-label-n: statement-n;

default: default-block;
}

When the switch statement is executed the control expression is evaluated first and
the value is compared with the case label values in the given order. If the label
matches with the value of the expression then the control is transferred directly to the
group of statements which follow the label. If none of the statements matches then the
statement against the default is executed.
The default statement is optional in switch statement in case if any default statement
is not given and if none of the condition matches then no action takes place in this
case the control transfers to the next statement of the switch statement.

/* write a program to print student Grade using switch case*/
#include<stdio.h>
#include<conio.h>
void main()
{
int s1,s2,s3,s4,s5,tot,avg;
clrscr();
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 59

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
printf("Enter student 5 subject marks\n");
scanf("%d%d%d%d%d",&s1,&s2,&s3,&s4,&s5);
tot=s1+s2+s3+s4+s5;
avg=tot/5;
switch(avg/10)
{
case 10:
case 9:
case 8:
case 7: printf("Distinction");
break;
case 6:printf("First class");
break;
case 5:printf("second class");
break;
case 4:printf("Third class");
break;
default:printf("Fail");
}
getch();
}



Repetition Control Structure/ Loops:

Repetitive structure/loops are generally used for repeatedly executes the same code
in the program.

In C language loops are

- while loop
- do-while loop
- for loop

While loop:

The simplest of all looping structure in C is the while statement.
The general format of the while statement is:

while (test condition)
{
body of the loop
}
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 60

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

Here the given test condition is evaluated and if the condition is true then the
body of the loop is executed. After the execution of the body, the test condition is
once again evaluated and if it is true, the body is executed once again. This process of
repeated execution of the body continues until the test condition finally becomes false
and the control is transferred out of the loop. On exit, the program continues with the
statements immediately after the body of the loop. The body of the loop may have one
or more statements. The braces are needed only if the body contained two are more
statements

Example program for generating N Natural numbers using while loop:

# include < stdio.h > //include the stdio.h file
void main() // Start of your program
{
int n, i=0; //Declare and initialize the variables
printf(Enter the upper limit number); //Message to the user
scanf(%d, &n); //read and store the number
while(I < = n) // While statement with condition
{ // Body of the loop
printf(\t%d,I); // print the value of i
i++; //increment I to the next natural number.
}
}

In the above program the looping concept is used to generate n natural
numbers. Here n and I are declared as integer variables and I is initialized to value
zero. A message is given to the user to enter the natural number till where he wants to
generate the numbers. The entered number is read and stored by the scanf statement.
The while loop then checks whether the value of I is less than n i.e., the user entered
number if it is true then the control enters the loop body and prints the value of I using
the printf statement and increments the value of I to the next natural number this
process repeats till the value of I becomes equal to or greater than the number given
by the user.

For loop:
The for loop provides a more concise loop control structure.
The general form of the for loop is:
Test condition
test
Body of the loop

true

false

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 61

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

for (initialization; test condition; increment)
{
body of the loop
}








When the control enters for loop the variables used in for loop is initialized with the
starting value such as I=0,count=0. The value which was initialized is then checked
with the given test condition. The test condition is a relational expression, such as I <
5 that checks whether the given condition is satisfied or not if the given condition is
satisfied the control enters the body of the loop or else it will exit the loop. The body
of the loop is entered only if the test condition is satisfied and after the completion of
the execution of the loop the control is transferred back to the increment part of the
loop. The control variable is incremented using an assignment statement such as
I=I+1 or simply I++ and the new value of the control variable is again tested to check
whether it satisfies the loop condition. If the value of the control variable satisfies
then the body of the loop is again executed. The process goes on till the control
variable fails to satisfy the condition.

Additional features of the for loop:

We can include multiple expressions in any of the fields of for loop provided that we
separate such expressions by commas. For example in the for statement that begins

For( I = 0; j = 0; I < 10, j=j-10)

Sets up two index variables I and j the former initialized to zero and the latter to 100
before the loop begins. Each time after the body of the loop is executed, the value of I
will be incremented by 1 while the value of j is decremented by 10.

Test condition
test
Body of the loop

true

false

Increment/decrement

initialization

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 62

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Just as the need may arise to include more than one expression in a particular field of
the for statement, so too may the need arise to omit on or more fields from the for
statement. This can be done simply by omitting the desired filed, but by marking its
place with a semicolon. The init_expression field can simply be left blank in such a
case as long as the semicolon is still included:

For(;j!=100;++j)

/*Write a C program to find the sum of Natural numbers up to N*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n,sum=0;
clrscr();
printf("Enter n value ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf("\nSum of Natural numbers : %d",sum);
getch();
}
Output:
Enter n value
10

Sum of natural numbers : 55

Do-while loop:

The do while loop is also a kind of loop, which is similar to the while loop in
contrast to while loop, the do while loop tests at the bottom of the loop after executing
the body of the loop. Since the body of the loop is executed first and then the loop
condition is checked. we can be assured that the body of the loop is executed at least
once.

The syntax of the do while loop is:

Do
{
statement;
}
while(expression);


COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 63

VIDYA VIKAS INSTITUTE OF TECHNOLOGY





Here the statement is executed, then expression is evaluated. If the condition
expression is true then the body is executed again and this process continues till the
conditional expression becomes false. When the expression becomes false. When the
expression becomes false the loop terminates.

To realize the usefulness of the do while construct consider the following problem.
The user must be prompted to press Y or N. In reality the user can press any key other
than y or n. IN such case the message must be shown again and the user should be
allowed to enter one of the two keys, clearly this is a loop construct. Also it has to be
executed at least once.
/* write a C program usig do-while to calculate and print
the first m fibonacci numbers */

#include<stdio.h>
#include<conio.h>
void main()
{
int i=1,m,f1=0,f2=1,f;
clrscr();
printf("enter any number");
scanf("%d",&m);
printf("\nthe fibonacci sequence \n\n");
printf("%d",f2);
do
{
f=f1+f2;
printf("%4d",f);
f1=f2;
f2=f;
i++;
}while(i<m);
getch();
}
Test condition
test
true

false

Body of the loop


COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 64

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

OUTPUT
enter any number6

the Fibonacci sequence


1 1 2 3 5 8

Unconditional control statements:
break:
- Used to exit from any block (not just a switch).
- Most often used to break out of a loop.
- An unlabeled break terminates the innermost switch, for, while, or do-while.
- To terminate an outer statement, label the outer statement and use its label
name in the break statement.
The break statement can be used to exit from the loops or switch case.
The break statements provide an early exit from for, while, and do, just as from
switch.

The format of the break statement is simply the keyword followed by a semicolon.

break;

Example program for break statement

#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=20;i++)
{
if(i%5==0)
break;
printf("%4d",i);
}
getch();
}

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 65

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Continue:
- Skips to the end of a loop's body and evaluates the Boolean expression that
controls the loop.
- Has meaning only inside loops: while, do-while, and for.
- A labeled continue will break out of any inner loops on its way to the next
iteration of the named loop.
The continue statement is most often used to bypass a group of statements inside a
loop based upon some condition. But to otherwise continue execution of the loop.

The format of the continue statement is simply

continue;

Example:
Write a program to print the 1 to 100 except the numbers divisible by 5.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=100;i++)
{
if(i%5==0)
continue;
printf("%4d",i);
}
getch();
}






Go to:

Control can be unconditionally transferred to a labeled statement by executing a goto
statement of the form

goto label; label:
.
.
label: goto label;
..
..
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 66

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

Forward jump Backward jump

A label is any valid variable name and must be followed by a colon.
The label is placed immediately before the statement where the control is to be
transferred.
The goto statement interrupts the normal sequential flow of a program

A goto breaks the normal sequential execution of the program. If the label: is
before statement goto label; a loop will be formed and some statements will be
executed repeatedly, such a jump is known as a backward jump. On the other hand, if
the label: is placed after the goto label; some statements will be skipped and jump is
known as a forward jump.

write a program to find given number is even or odd using goto statement

#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter n value");
scanf("%d",&n);
if(n%2==0)
goto even;
else
goto odd;
even:
printf("Given number is even");
exit();
odd:
printf("Given number is odd");
getch();
}
OUTPUT:
Enter n value 12
Given number is even




COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 67

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

















UNIT III

DESIGNING STRUCTURED PROGRAMS:

The planning for large programs consists of first understanding the problem as
a whole, second breaking it into simpler, understandable parts. We call each of these
parts of a program a module and the process of subdividing a problem into
manageable parts top-down design.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 68

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
The principles of top-down design and structured programming dictate that a
program should be divided into a main module and its related modules. Each module
is in turn divided into sub-modules until the resulting modules are intrinsic; that is,
until they are implicitly understood without further division.
Top-down design is usually done using a visual representation of the modules
known as a structure chart. The structure chart shows the relation between each
module and its sub-modules. The structure chart is read top-down, left-right. First we
read Main Module. Main Module represents our entire set of code to solve the
problem.



Structure Chart

Moving down and left, we then read Module 1. On the same level with
Module 1 are Module 2 and Module 3. The Main Module consists of three sub-
modules. At this level, however we are dealing only with Module 1. Module 1 is
further subdivided into three modules, Module 1a, Module 1b, and Module 1c. To
write the code for Module 1, we need to write code for its three sub-modules.
The Main Module is known as a calling module because it has sub-modules.
Each of the sub-modules is known as a called module. But because Modules 1, 2, and
3 also have sub-modules, they are also calling modules; they are both called and
calling modules.
Communication between modules in a structure chart is allowed only through
a calling module. If Module 1 needs to send data to Module 2, the data must be
passed through the calling module, Main Module. No communication can take place
directly between modules that do not have a calling-called relationship.

How can Module 1a send data to Module 3b?

It first sends data to Module 1, which in turn sends it to the Main Module,
which passes it to Module 3, and then on to Module 3b.
The technique used to pass data to a function is known as parameter passing.
The parameters are contained in a list that is a definition of the data passed to the
function by the caller. The list serves as a formal declaration of the data types and
names.

FUNCTIONS :
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 69

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

A function is a self contained program segment that carries out some specific
well defined tasks.

Advantages of functions:

1. Write your code as collections of small functions to make
your program modular
2.Structured programming
3.Code easier to debug
4.Easier modification
5.Reusable in other programs


Function Definition :

type func_name( parameter list )
{
declarations;
statements;
}

FUNCTION HEADER :







FUNCTION PROTOTYPES
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 70

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

If a function is not defined before it is used, it must be declared by specifying
the return type and the types of the parameters.
double sqrt(double);
Tells the compiler that the function sqrt() takes an argument of type double
and returns a double. This means, incidentally, that variables will be cast to the
correct type; so sqrt(4) will return the correct value even though 4 is int not double.
These function prototypes are placed at the top of the program, or in a separate header
file, file.h, included as
#include "file.h"
Variable names in the argument list of a function declaration are optional:
void f (char, int);
void f (char c, int i); /*equivalent but makes code more readable */
If all functions are defined before they are used, no prototypes are needed. In this
case, main() is the last function of the program.


SCOPE RULES FOR FUNCTIONS :

Variables defined within a function (including main) are local to this function
and no other function has direct access to them. The only way to pass variables to
function is as parameters. The only way to pass (a single) variable back to the calling
function is via the return statement

Ex:
int func (int n)
{
printf(%d\n,b);
return n;
}//b not defined locally!

int main (void)
{
int a = 2, b = 1, c;
c = func(a);
return 0;
}


FUNCTION CALLS :

When a function is called, expressions in the parameter list are evaluated (in
no particular order!) and results are transformed to the required type. Parameters are
copied to local variables for the function and function body is executed when return
is encountered, the function is terminated and the result (specified in the return
statement) is passed to the calling function (for example main).

Ex:

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 71

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
int fact (int n)
{
int i, product = 1;
for (i = 2; i <= n; ++i)
product *= i;
return product;
}

int main (void)
{
int i = 12;
printf(%d,fact(i));
return 0;
}


PARAMETER PASSING :

Parameter passing mechanism in C is of two types.
1. Call by Value
2. Call by Reference.

The process of passing the actual value of variables is known as Call by
Value.
The process of calling a function using pointers to pass the addresses of
variables is known as Call by Reference. The function which is called by reference
can change the value of the variable used in the call.

Example of Call by Value:

#include <stdio.h>
void swap(int,int);
main()
{
int a,b;
printf(Enter the Values of a and b:);
scanf(%d%d,&a,&b);
printf(Before Swapping \n);
printf(a = %d \t b = %d, a,b);
swap(a,b);
printf(After Swapping \n);
printf(a = %d \t b = %d, a,b);
}


void swap(int a, int b)
{
int temp;
temp = a;
a = b;
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 72

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
b = temp;
}

Example of Call by Reference:

#include<stdio.h>
main()
{
int a,b;
a = 10;
b = 20;
swap (&a, &b);
printf(After Swapping \n);
printf(a = %d \t b = %d, a,b);
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}

STORAGE CLASSES :

In C a variable can have any one of four Storage Classes.
1. Automatic Variables
2. External Variables
3. Static Variables
4. Register Variables

SCOPE :
The Scope of variable determines over what parts of the program a
variable is actually available for use.




LONGEVITY :

Longevity refers to period during which a variable retains a given value during
execution of a program (alive). So Longevity has a direct effect on utility of a given
variable.
The variables may also be broadly categorized depending on place of their declaration
as internal(local) or external(global). Internal variables are those which are declared
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 73

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
within a particular function, while external variables are declared outside of any
function.

AUTOMATIC VARIABLES :

They are declared inside a function in which they are to be utilized. They are
created when function is called and destroyed automatically when the function is
exited, hence the name automatic. Automatic Variables are therefore private (or
local) to the function in which they are declared. Because of this property, automatic
variables are also referred to as local or internal variables.
By default declaration is automatic. One important feature of automatic
variables is that their value cannot be changed accidentally by what happens in some
other function in the program.

#include<stdio.h>
main()
{
int m=1000;
func2();
printf(%d\n,m);
}


func1()
{
int m=10;
printf(%d\n,m);
}
func2()
{
int m=100;
func1();
printf(%d,m);
}

First, any variable local to main will normally live throughout the whole program,
although it is active only in main.
Secondly, during recursion, nested variables are unique auto variables, a situation
similar to function nested auto variables with identical names.


EXTERNAL VARIABLES :

Variables that are both alive and active throughout entire program are known
as external variables. They are also known as Global Variables. In case a local and
global have same name local variable will have precedence over global one in
function where it is declared.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 74

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

#include<stdio.h>
int x;
main()
{
x=10;
printf(%d,x);
printf(x=%d,fun1());
printf(x=%d,fun2());
printf(x=%d,fun3());


}

fun1()
{
x=x+10;
return(x);
}
fun2()
{
int x;
x=1;
return(x);
}
fun3()
{
x=x+10;
return(x);
}
An extern within a function provides the type information to just that one function.


STATIC VARIABLES :

The value of Static Variable persists until the end of program. A variable can
be declared Static using Keyword Static like Internal & External Static Variables are
differentiated depending whether they are declared inside or outside of auto variables,
except that they remain alive throughout the remainder of program.

#include<stdio.h>
main()
{
int I;
for (I=1;I<=3;I++)
stat();
}
stat()
{
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 75

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
static int x=0;
x=x+1;
printf(x=%d\n,x);
}

REGISTER VARIABLES :

We can tell the Compiler that a variable should be kept in one of the machines
registers, instead of keeping in the memory. Since a register access is much faster
than a memory access, keeping frequently accessed variables in register will lead to
faster execution

Syntax:
register int Count.


USER DEFINED FUNCTIONS:

Every program must have a main function to indicate where the program has
to begin its execution. While it is possible to code any program utilizing only main
function, it leads to a number of problems. The program may become too large and
complex and as a result task of debugging, testing and maintaining becomes difficult.
If a program is divided into functional parts, then each part may be independently
coded and later combined into a single unit, these subprograms called functions are
much easier to understand debug and test.

There are times when some types of operation for calculation is repeated many
times at many points through out a program. For instance, we might use the factorial
of a number at several points in the program. In such situations, we may repeat the
program statements whenever they are needed. Another approach is to design a
function that can be called and used whenever required.

The advantages of using functions are
1. It facilitates top-down modular programming.
2. The length of a source program can be reduced by using functions at
appropriate places.
3. It is easy to locate and isolate a faculty function for further investigations.
4. A function may be used by many other programs.

A function is a self-contained block of code that performs a particular task.
Once a function has been designed and packed it can be treated as a black box that
takes some data from main program and returns a value. The inner details of the
program are invisible to the rest of program.

The form of the C functions.
function-name ( argument list )
argument declaration;
{
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 76

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
local variable declarations;
executable statement 1;
executabie statement 2;
- - - - - - - - - -
- - - - - - - - - -
- - - - - - - - - -
return (expression) ;
}

The return statement is the mechanism for returning a value to the calling
function. All functions by default returns int type data. we can force a function to
return a particular type of data by using a type specifier in the header.
A function can be called by simply using the function name in the statement.

A function depending on whether arguments are present or not and whether a
value is returned or not may belong to.
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.

1. Functions with no arguments and no return values :

When a function has no arguments, it does not receive any data from calling
function. In effect, there is no data transfer between calling function and called
function.

#include<stdio.h>
main()
{
printline();
value();
printline();
}
printline()
{
int i;
for(i=1;i<=35;i++0)
printf(%c,-);
printf(\n);
}
value()
{
int year, period;
float inrate,sum,principal;
printf(Enter Principal, Rate,Period);
scanf(%f%f%f,&principal,&inrate,&period);
sum=principal;
year=1;
while(year<=period)
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 77

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
{
sum=sum*(1+inrate);
year=year+1;
}
printf(%f%f%d%f,principal,inrate,period,sum);
}

2. Arguments but no return values :

The function takes argument but does not return value.
The actual (sent through main) and formal(declared in header section) should match
in number, type and order.
In case actual arguments are more than formal arguments, extra actual
arguments are discarded. On other hand unmatched formal arguments are initialized
to some garbage values.


#include<stdio.h>
main()
{
float prin,inrate;
int period;
printf(Enter principal amount, interest);
printf(rate and period\n);
scanf(%f%f%d,&principal,&inrate,&period);
printline(z);
value(principal, inrate, peiod);
printline(c);
}
printline(ch)
char ch;
{
int i;
for(i=1;i<=52;i++)
printf(%c,ch);
printf(\n);
}


STANDARD LIBRARY FUNCTIONS AND HEADER FILES:


C functions can be classified into two categories, namely, library functions and user-
defined functions .Main is the example of user-defined functions.Printf and scanf
belong to the category of library functions. The main difference between these two
categories is that library functions are not required to be written by us where as a user-
defined function has to be developed by the user at the time of writing a
program.However, a user-defined function can later become a part of the c program
library.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 78

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

ANSI C Standard Library Functions :

The C language is accompanied by a number of library functions that perform various
tasks.The ANSI committee has standardized header files which contain these
functions.

Some of the Header files are:

<ctype.h> character testing and conversion functions.
<math.h> Mathematical functions
<stdio.h> standard I/O library functions
<stdlib.h> Utility functions such as string conversion routines
memory
allocation routines , random number generator,etc.
<string.h> string Manipulation functions
<time.h> Time Manipulation functions

MATH.H

The math library contains functions for performing common mathematical
operations. Some of the functions are :

abs : returns the absolute value of an integer x
cos : returns the cosine of x, where x is in radians
exp: returns "e" raised to a given power
fabs: returns the absolute value of a float x
log: returns the logarithm to base e
log10: returns the logarithm to base 10
pow : returns a given number raised to another number
sin : returns the sine of x, where x is in radians
sqrt : returns the square root of x
tan : returns the tangent of x, where x is in radians
ceil : The ceiling function rounds a number with a decimal part up to the next
highest integer (written mathematically as x)
floor : The floor function rounds a number with a decimal part down to the next
lowest
integer (written mathematically as x)


STRING.H

There are many functions for manipulating strings. Some of the more useful are:

strcat : Concatenates (i.e., adds) two strings
strcmp: Compares two strings
strcpy: Copies a string
strlen: Calculates the length of a string (not including the null)
strstr: Finds a string within another string
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 79

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
strtok: Divides a string into tokens (i.e., parts)


STDIO.H

Printf: Formatted printing to stdout
Scanf: Formatted input from stdin
Fprintf: Formatted printing to a file
Fscanf: Formatted input from a file
Getc: Get a character from a stream (e.g, stdin or a file)
putc: Write a character to a stream (e.g, stdout or a file)
fgets: Get a string from a stream
fputs: Write a string to a stream
fopen: Open a file
fclose: Close a file

STDLIB.H

Atof: Convert a string to a double (not a float)
Atoi: Convert a string to an int
Exit: Terminate a program, return an integer value
free: Release allocated memory
malloc: Allocate memory
rand: Generate a pseudo-random number
system: Execute an external command

TIME.H

This library contains several functions for getting the current date and time.

Time: Get the system time
Ctime: Convert the result from time() to something meaningful

RECURSIVE FUNCTIONS :

Recursion is a repetitive process in which a function calls itself (or) A function
is called recursive if it calls itself either directly or indirectly. In C, all functions can
be used recursively.

Example: Fibonacci Numbers

A recursive function for Fibonacci numbers (0,1,1,2,3,5,8,13...)

/* Function with recursion*/
int fibonacci(int n)
{
if (n <= 1)
return n;
else
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 80

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
return (fibonacci(n-1) + fibonacci(n-2));
}

With recursion 1.4 x 10
9
function calls needed to find the 43rd Fibonacci
number(which has the value 433494437) .If possible, it is better to write iterative
functions.

int factorial (int n) /* iterative version */
{
for ( ; n > 1; --n)
product *= n;
return product;
}

C PREPROCESSOR :

C Preprocessor is a program that processes source program before it is passed to the
compiler.Preprocessor commands often known as directives.We can write C programs
without knowing anything about the preprocessor or its facilities.But preprocessor is
such a great convenience that virtually all C programmers rely on it.

FEATURES OF C PREPROCESSOR :

The C program is often known as source code.The preprocessor works on
the source code and creates Expanded source code. If the sorce code is stored in a
file pr1.C ,then the expanded source code gets stored in a file pr1.I .It is this
expanded source code that is sent to the compiler for compilation.

The preprocessor offers several features called preprocessor directives .Each
of these preprocessor directives begins with a # symbol.The directives can be placed
anywhere in a program but are most ofhen placed at the beginning of a program .

PREPROCESSOR DIRECTIVES:

Preprocessor directives are:

1.Macro expansion
2.File inclusion
3.Conditional compilation
4.Miscellaneous directives





MACRO EXPANSION:

EXAMPLE:

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 81

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
#include<stdio.h>
#define UPPER 25
void main()
{
int I;
for(i=1;i<=UPPER;i++)
printf(\n%d,i);
}

In this program instead of writing 25 in the for loop we are writing it in the form of
UPPER, which has already been defined before main() through the statement,

#define UPPER 25

This statement is called Macro definition or more commonly just a Macro.
During preprocessing , the preprocessor replaces every occurrence of UPPER in the
program with 25.

MACROS WITH ARGUMENTS:

The Macros that we have used so far are called simple macros. Macros can have
arguments,just as functions can.

Example:

#include<stdio.h>
#define AREA(x) (3.14*x*x)
void main()
{
float r1=6.25,r2=2.5,a;
a=AREA(r1);
printf(\nArea of circle=%f,a);
a=AREA(r2);
printf(\nArea of circle=%f,a);
}

OUTPUT:
Area of circle=122.656250
Area of circle=19.625000

In this program , whenever the preprocessor finds the phrase AREA(x) it expands it
into the statement (3.14 * x * x ).The x in the macro template AREA(x) is an
argument that matches the x in the macro expansion (3.14 * x * x). The statement
AREA(r1) in the program causes the variable r1 to be substituted for x. Thus the
statement AREA(r1) is equalent to:
(3.14*r1*r1)

After the above source code has passed through the preprocessor , the compiler gets to
work on will be this:
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 82

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

#include<stdio.h>
void main()
{
float r1=6.25,r2=2.5,a;
a=3.14*r1*r1;
printf(Area of circle=%f\n,a);
a=3.14*r2*r2;
printf(Area of circle=%f,a);
}


SOME IMPORTANT POINTS TO REMEMBER WHILE WRITING
MACROS WITH ARGUMENTS:

(A) Be careful not to leave a blank between the macro template anf its arfument
nwhile defining the macro. For example there should be no blank between
AREA and (x) in the definition,

#define AREA(x) (3.14*x*x)

If we write AREA (x) instead of AREA(x), the (x) would become a part of
macro expansion,which we certainly dont want .What would happen is ,the template
would be expanded to
(r1) (3.14*r1*r1)
which wont run.

b)The entire macro expansion should be enclosed within parentheses.
Ex:
#include<stdio.h>
#define SQUARE(n) n*n
void main()
{
int j;
j=64/SQUARE(4);
printf(j=%d, j);
}
The output of the above program will be:
J=64
Where as ,we expected was j=4;
In this case macro was expanded into
J=64/4*4;
Which yields 64.

c)Macros can be split into multiple lines, with a \(back slash) present at the end of
each line.

Ex:
#include<stdio.h>
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 83

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
#define HLINE for(i=0;i<79;i++)\printf(%c,196);
#define VLINE { \ gotoxy(X,Y);\ printf(%c,179);\ }
void main()
{
int i,y;
clrscr();
gotoxy(1,12);/*position cursor in row x and column y*/
HLINE
For(y=1;y<25;y++)
VLINE(39,y);
}
This program draws a vertical and horizontal line in the center of the screen.

d) If for any reason ,you are unable to debug a macro,then you should view the
expanded code of the program to see how the macros are getting expanded. If your
source code is present in the file pr1.c then the expanded source code would be stored
in pr1.I.You need to generate this file at the command prompt by saying:
cpp pr1.c

Here CPP stands for C PreProcessor.It generates the expanded source code and stores
it in a file called pr1.I.You can now open this file and see the expanded source code.


MACROS VERSUS FUNCTIUONS :

Macro calls are like function calls ,they are not really the same things.The difference
between these two are:

1.In a macro call call ,the preprocessor replaces the macro template with its
macro expansion ,In function call the contol is passed to a function along with certain
arguments.,some calculations are performed in the function and a useful value is
returned back from the function.
2. Macros make the program run faster but increase the size of the
program,where as functions make the program smaller and compact.
3.If we use a macro hundred times in a program ,the macro expansion goes
into sorce code at hundred different places,thus increasing the program size.On the
other hand ,if a function is used ,then even if it is called from hundred different places
in the program,it would take the same amount of space in the program.
4.Passing parameters to a function and getting back the returned value does
take time and would therefore slowdown the program.
5. The macro is simple and it avoids the overhead associated with function
calls if we have a fairly large macro and it is used fairly often ,we ought to replace it
with a function.
6.If memory space in the machine in which the program is being executed is
less,then it may make sense to use functions instead of macros.By doing so,the
program may run slower,but will need less memory space.


FILE INCLUSION:
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 84

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

The first and most common job of a preprocessor is File inclusion, the copying
of one or more files in toi programs the files are usually header files that contain
function and data declaratuions for the program,but they can contain any valid C
statement.
The preprocessor command is #include,and it has two different formats.
The first format is used to direct the preprocessor to include header files from the
system library.In thus format, the name of the header file is enclosed in pointed
brackets .
The second format makes the preprocessor look for the header files in the userdefined
directory. In this format, the name of the file pathname is enclosed in double quotes.

Example:
#include<filename.h>
#includefilepath.h


CONDITIONAL COMPILATION:

Conditional compilation allows us to control the compilation process by
including or excluding statements.

TWO WAY COMMANDS:

The two way command tells the preprocessor to select between two choices this is
similar to selection.
Syntax:
#if expression
//code to be included if expression is true
#else
//code to be included if expression is false
#endif

The expression is a constant value that evaluates to zero or non zero.If the value is
nonzero ,it is interpreted as true and the code after #if is included.If it is zero,it is
interpreted as false and the code after #else is executed.
The #if part (or ) the #else part can be empty.

Example:

#if expression #if !expression
#else //code to be included if expression is
false //code to be included if expression is false #endif
#endif


#if expression #if expression
//code to be included if expression is true //code to be included if expression is true
#else #endif
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 85

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
#endif


Two abbreviations:

The C language provides two additional macro commands they are

#if defined name # ifdef name

#if !defined name #ifndef name


MULTI-WAY COMMANDS:

Conditional commands can also be multi-way by selecting one of the choices among
several. In the preprocessor, we use the #elif command.

Syntax:
#if expression1
//code to be included if expression1 is true
#elif expression2
//code to be included if expression2 is true
#else
//code to be included if both expressions are false
#endif

MISCELLANEOUS DIRECTIVES:

There are two or more preprocessor directives available,though they are not very
commonly used . They are
A) #undef
B) #pragma

#undef directive: In order to undefined a macro that has been earlier #defined ,
we use #undef directive.

Syntax:
#undef macro template

example:

#undef Pentium

The above example cause the definition of Pentium to be removed from the
system.All subsequent #ifdef Pentium statements would evaluate to false.


#pragma directive: This directive is another special purpose directive that you can
use to turn on or off certain features.pragmas vary from one compiler to another.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 86

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Example:

#pragma tokens

This command causes the compiler to perform implementation defined actions.


ARRAYS :

An array is a group of related data items that share a common name.
Ex:- Students
The complete set of students are represented using an array name students. A
particular value is indicated by writing a number called index number or subscript in
brackets after array name. The complete set of value is referred to as an array, the
individual values are called elements.

ONE DIMENSIONAL ARRAYS :

A list of items can be given one variable index is called single subscripted
variable or a one-dimensional array.

The subscript value starts from 0. If we want 5 elements the declaration will
be

int number[5];

The elements will be number[0], number[1], number[2], number[3],
number[4]
There will not be number[5]

Declaration of One - Dimensional Arrays :

Type variable name [sizes];

Type data type of all elements Ex: int, float etc.,
Variable name is an identifier
Size is the maximum no of elements that can be stored.
Ex:- float avg[50]
This array is of type float. Its name is avg. and it can contains 50 elements
only. The range starting from 0 49 elements.

Initialization of Arrays :

Initialization of elements of arrays can be done in same way as ordinary
variables are done when they are declared.

Type array name[size] = {List of Value};
Ex:- int number[3]={0,0,0};

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 87

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
If the number of values in the list is less than number of elements then only that
elements will be initialized. The remaining elements will be set to zero automatically.
Ex:- float total[5]= {0.0,15.75,-10};

The size may be omitted. In such cases, Compiler allocates enough space for all
initialized elements.

int counter[ ]= {1,1,1,1};

/* Program Showing one dimensional array */

#include<stdio.h>
main()
{
int i;
float x[10],value,total;
printf(Enter 10 real numbers\n);
for(i=0;i<10;i++)
{
scanf(%f,&value);
x[i]=value;
}
total=0;
for(i=0;i<10;i++)
total=total+x[i]
for(i=0;i<10;i++)
printf(x[%2d]=%5.2f\n,I+1,x[I]);
printf(total=%0.2f,total);
}

TWO DIMENSIONAL ARRAYS:

To store tables we need two dimensional arrays. Each table consists of rows
and columns. Two dimensional arrays are declare as
type array name [row-size][col-size];

/* Write a program Showing 2-DIMENSIONAL ARRAY */

/* SHOWING MULTIPLICATION TABLE */

#include<stdio.h>
#include<math.h>
#define ROWS 5
#define COLS 5
main()
{
int row,cols,prod[ROWS][COLS];
int i,j;
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 88

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

printf(Multiplication table);
for(j=1;j< =COLS;j++)
printf(%d,j);
for(i=0;i<ROWS;i++)
{
row = i+1;
printf(%2d|,row);
for(j=1;j < = COLS;j++)
{
COLS=j;
prod[i][j]= row * cols;
printf(%4d,prod[i][j]);
}
}
}

INITIALIZING TWO DIMENSIONAL ARRAYS:



They can be initialized by following their declaration with a list of initial
values enclosed in braces.

Ex:- int table[2][3] = {0,0,0,1,1,1};

Initializes the elements of first row to zero and second row to one. The initialization
is done by row by row. The above statement can be written as
int table[2][3] = {{0,0,0},{1,1,1}};

When all elements are to be initialized to zero, following short-cut method may be
used.

int m[3][5] = {{0},{0},{0}};

MULTI-DIMENSIONAL ARRAYS:

C allows arrays of three or more dimensions. The exact limit is determined by
Compiler.
type array-names[s1][s2][s3] - - - - - [s
n
];
where s
i
is size of dimension.
Ex:- int Survey[3][5][2];

#include <stdio.h>

void printArray( const int a[][ 3 ] );

int main()
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 89

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
{
int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };
int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };

printf( "Values in array1 by row are:\n" );
printArray( array1 );

printf( "Values in array2 by row are:\n" );
printArray( array2 );

printf( "Values in array3 by row are:\n" );
printArray( array3 );

return 0;

}

void printArray( const int a[][ 3 ] )
{
int i;
int j;

for ( i = 0; i <= 1; i++ ) {
for ( j = 0; j <= 2; j++ ) {
printf( "%d ", a[ i ][ j ] );
}

printf( "\n" );
}
}
4 0 0


APPLICATIONS OF ARRAYS :

1.Frequency arrays with their graphical representations.
2.Random number permutations.

FREQUENCY ARRAYS :

Two common statistical applications that use arrays are frequency
distributions and histograms. A frequency array shows the number of elements with
an identical value found in a series of numbers.

For example ,suppose we have taken a sample of 100 values between 0 and
19.We want to know how many of the values are 0,how many are 1,how many are
2,and so forth up through 19.

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 90

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
We can read these numbers into an array called numbers. Then we create an
array of 20 elements that will show the frequency of each number in the series.

One way to do it is to assign the value from the data array to an index and then
use the index to access the frequency array.
F=numbers[i];
Frequency[F]++;

Since an index is an expression ,however ,we can simply use the value from
our data array to index us in to the frequency array .The value of numbers[i] is
determined first ,and then that value is used to index in to frequency.

Frequency[numbers[i]]++;
Fig-8-14


HISTOGRAMS:

A histogram is a pictorial representation of a frequency array .Instead of
printing the values of the elements to show the frequency of each number, we print a
histogram in the form of a bar chart. For example ,the following figure is a histogram
for a set of numbers in the range 0 19.In this example, asterisks (*) are used to
build the bar. Each
asterisk represents one occurrence of the data value.

0 0
1 4 * * * * (four 1s)
2 7 * * * * * * *
3 7 * * * * * * *(seven 3s)
.
.
.
18 2 * *
19 0 (zero 19s)


RANDOM NUMBER PERMUTATIONS :

A random number permutation is a set of random numbers in which no
numbers are repeated. For example, given a random number permutation of 10
numbers, the values from 0 to 9 would all be included with no duplicates.
Generating random numbers:
To generate a random integral in a range x to y,we must first scale the number
and then ,if x is greater than 0 ,shift the number within the range. We scale the
number using the modulus operator.
Ex: To produce a random number in the range 0 50,we simply scale the
random number and scaling factor must be one greater than the highest number
needed.

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 91

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
rand ( ) %51
modulus works well when our range starts at 0.for example ,suppose we want a
random number between 10 and 20.for this we will use one formula
range = ( 20 - 10 ) +1;
randno = rand ( ) % range + 10;

To generate a permutation ,we need to eliminate the duplicates. Using
histogram concept we can solve the problem most efficiently by using two arrays. The
first array contains the random numbers. The second array contains a logical value
that indicates whether or not the number represented by its index has been placed in
the random number array.

Only the first five random numbers have been placed in the permutation. For
each random number in the random number array ,its corresponding location in the
have-random array is set to 1. Those locations representing numbers that have not yet
been generated are still set to 0.














COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 92

VIDYA VIKAS INSTITUTE OF TECHNOLOGY




UNIT IV


POINTERS :

One of the powerful features of C is ability to access the memory variables by
their memory address. This can be done by using Pointers. The real power of C lies
in the proper use of Pointers.
A pointer is a variable that can store an address of a variable (i.e., 112300).We
say that a pointer points to a variable that is stored at that address. A pointer itself
usually occupies 4 bytes of memory (then it can address cells from 0 to 232-1).

Advantages of Pointers :

1. A pointer enables us to access a variable that is defined out side the
function.
2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.

Definition :
A variable that holds a physical memory address is called a pointer variable or
Pointer.

Declaration :

Datatype * Variable-name;

Eg:- int *ad; /* pointer to int */
char *s; /* pointer to char */
float *fp; /* pointer to float */
char **s; /* pointer to variable that is a pointer to char */


A pointer is a variable that contains an address which is a location of another
variable in memory.

Consider the Statement
p=&i;

Here & is called address of a variable.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 93

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
p contains the address of a variable i.

The operator & returns the memory address of variable on which it is
operated, this is called Referencing.

The * operator is called an indirection operator or dereferencing operator
which is used to display the contents of the Pointer Variable.

Consider the following Statements :

int *p,x;
x =5;
p= &x;

Assume that x is stored at the memory address 2000. Then the output for the
following printf statements is :

Output
Printf(The Value of x is %d,x); 5
Printf(The Address of x is %u,&x); 2000
Printf(The Address of x is %u,p); 2000
Printf(The Value of x is %d,*p); 5
Printf(The Value of x is %d,*(&x)); 5


POINTER FUNCTION ARGUMENTS

Function arguments in C are strictly pass-by-value. However, we can simulate
pass-by-reference by passing a pointer. This is very useful when you need to Support
in/out(bi-directional) parameters (e.g. swap, find replace) Return multiple outputs
(one return value isn't enough) Pass around large objects (arrays and structures).
/* Example of swapping a function can't change parameters */
void bad_swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
/* Example of swapping - a function can't change parameters, but if a parameter is a
pointer it can change the value it points to */

void good_swap(int *px, int *py)
{
int temp;
temp = *px;
*px = *py;
*py = temp;
}
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 94

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

#include <stdio.h>
void bad_swap(int x, int y);
void good_swap(int *p1, int *p2);
main() {
int a = 1, b = 999;
printf("a = %d, b = %d\n", a, b);
bad_swap(a, b);
printf("a = %d, b = %d\n", a, b);
good_swap(&a, &b);
printf("a = %d, b = %d\n", a, b);
}

POINTERS AND ARRAYS :

When an array is declared, elements of array are stored in contiguous
locations. The address of the first element of an array is called its base address.

Consider the array


2000 2002 2004 2006 2008

a[0] a[1] a[2] a[3] a[4]


The name of the array is called its base address.

i.e., a and k& a[20] are equal.

Now both a and a[0] points to location 2000. If we declare p as an integer pointer,
then we can make the pointer P to point to the array a by following assignment

P = a;

We can access every value of array a by moving P from one element to another.
i.e., P points to 0
th
element
P+1 points to 1
st
element
P+2 points to 2
nd
element
P+3 points to 3
rd
element
P +4 points to 4
th
element


Reading and Printing an array using Pointers :


main()
{
int *a,i;
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 95

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
printf(Enter five elements:);
for (i=0;i<5;i++)
scanf(%d,a+i);
printf(The array elements are:);
for (i=o;i<5;i++)
printf(%d, *(a+i));
}

In one dimensional array, a[i] element is referred by
(a+i) is the address of i
th
element.
* (a+i) is the value at the i
th
element.

In two-dimensional array, a[i][j] element is represented as
*(*(a+i)+j)


POINTERS AND FUNCTIONS :

Parameter passing mechanism in C is of two types.

1.Call by Value
2.Call by Reference.

The process of passing the actual value of variables is known as Call by
Value.The process of calling a function using pointers to pass the addresses of
variables is known as Call by Reference. The function which is called by reference
can change the value of the variable used in the call.

Example of Call by Value:

#include <stdio.h>
void swap(int,int);
main()
{
int a,b;
printf(Enter the Values of a and b:);
scanf(%d%d,&a,&b);
printf(Before Swapping \n);
printf(a = %d \t b = %d, a,b);
swap(a,b);
printf(After Swapping \n);
printf(a = %d \t b = %d, a,b);
}


void swap(int a, int b)
{
int temp;
temp = a;
a = b;
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 96

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
b = temp;
}

Example of Call by Reference:

#include<stdio.h>
main()
{
int a,b;
a = 10;
b = 20;
swap (&a, &b);
printf(After Swapping \n);
printf(a = %d \t b = %d, a,b);
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}

ADDRESS ARITHIMETIC :

Incrementing/Decrementing a pointer variable ,adding and subtracting an
integer from pointer variable are all legal and known as pointer arithmetic. Pointers
are valid operands in arithmetic expressions ,assignment expressions ,and comparison
expressions. However not all the operators normally used in these expressions are
valid in conjunction with pointer variable.
A limited set of arithmetic operations may be performed on pointers. A pointer
may be incremented(+ +) or decremented(--) ,an integer may be added to a pointer
(+ or +=),an integer may be subtracted from a pointer(- or -=),or one pointer may be
subtracted from another.

We can add and subtract integers to/from pointers the result is a pointer to another
element of this type

Ex : int *pa; char *s;

s-1 points to char before s (1 subtracted)
pa+1 points to next int (4 added!)
s+9 points to 9th char after s (9 added)
++pa increments pa to point to next int





COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 97

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

NULL POINTER :

Zero is a special value we can assign to a pointer which does not point to
anything most frequently, a symbolic constant NULL is used. It is guaranteed, that no
valid address is equal to 0.The bit pattern of the NULL pointer does not have to
contain
all zeros usually it does or it depends on the processor architecture. On many
machines, dereferencing a NULL pointer causes a segmentation violation.

NULL ptr is not the same as an EMPTY string.

const char* psz1 = 0;
const char* psz2 = "";
assert(psz1 != psz2);

Always check for NULL before dereferencing a pointer.

if (psz1)
/* use psz1 */
sizeof(psz1) // doesn't give you the number of elements in psz1. Need
additional size variable.


VOID POINTER :

In C ,an additional type void *(void pointer) is defined as a proper type for
generic pointer. Any pointer to an object may be converted to type void * without loss
of information. If the result is converted back to the original type ,the original pointer
is recovered .

Ex:
main()
{
void *a;
int n=2,*m;
double d=2.3,*c;
a=&n;
m=a;
printf(\n%d %d %d,a,*m,m);
a=&d;
c=a;
printf(\n%d %3.1f %d,a,*c,c);
}

In the above program a is declared as a pointer to void which is used to carry the
address of an int(a=&n)and to carry the address of a double(a=&d) and the original
pointers are recovered with out any loss of information.

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 98

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

POINTERS TO POINTERS :

So far ,all pointers have been pointing directely to data.It is possible and with
advanced data structures often necessary to use pointers to that point to other pointers.
For example,we can have a pointer pointing to a pointer to an integer.This two level
indirection is seen as below:
//Local declarations
int a;
int* p;
int **q;

q p a
Ex:

397870 234560 287650


pointer to pointer to integer pointer to integer integer
variable

//statements
a=58;
p=&a;
q=&p;
printf(%3d,a);
printf(%3d,*p);
printf(%3d,**q);

There is no limit as to how many level of indirection we can use but
practically we seldom use morethan two.Each level of pointer indirection requires a
separate indirection operator when it is dereferenced .

In the above figure to refer to a using the pointer p, we have to dereference
it as shown below.
*p
To refer to the variable a using the pointer q ,we have to dereference it
twice toget to the integer a because there are two levels of indirection(pointers)
involved.If we dereference it only once we are referring p which is a pointer to an
integer .Another way to say this is that q is a pointer to a pointer to an integer.The
doule dereference is shown below:
**q

In above example all the three references in the printf statement refer to the variable
a.
The first printf statement prints the value of the variable a directly,second uses the
pointer p,third uses the pointer q.The result is the value 58 printed 3 times as
below

234560 287650 58
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 99

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
58 58 58


DYNAMIC MEMORY ALLOCATION :

Dynamic memory allocation uses predefined functions to allocate and release
memory for data while the program is running. It effectively postpones the data
definition ,but not the declaration to run time.
To use dynamic memory allocation ,we use either standard data types or
derived types .To access data in dynamic memory we need pointers.

MEMORY ALLOCATION FUNCTIONS:

Four memory management functions are used with dynamic memory. Three of
them,malloc,calloc,and realloc,are used for memory allocation. The fourth ,free is
used to return memory when it is no longer needed. All the memory management
functions are found in standard library file(stdlib.h).

BLOCK MEMORY ALLOCATION(MALLOC) :

The malloc function allocates a block of memory that contains the number of
bytes specified in its parameter. It returns a void pointer to the first byte of the
allocated memory. The allocated memory is not initialized.

Declaration:
void *malloc (size_t size);

The type size_t is defined in several header files including Stdio.h. The type is
usually an unsigned integer and by the standard it is guaranteed to be large enough to
hold the maximum address of the computer. To provide portability the size
specification in mallocs actual parameter is generally computed using the sizeof
operator. For example if we want to allocate an integer in the heap we will write like
this:

Pint=malloc(sizeof(int));

Malloc returns the address of the first byte in the memory space allocated. If it
is not successful malloc returns null pointer. An attempt to allocate memory from
heap when memory is insufficient is known as overflow.

The malloc function has one or more potential error if we call malloc with a
zero size, the results are unpredictable. It may return a null pointer or it may return
someother implementation dependant value.

Ex:
If(!(Pint=malloc(sizeof(int))))
// no memory available
exit(100);
//memory available
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 100

VIDYA VIKAS INSTITUTE OF TECHNOLOGY


In this example we are allocating one integer object. If the memory is allocated
successfully,ptr contains a value. If does not there is no memory and we exit the
program with error code 100.


CONTIGIOUS MEMORY ALLOCATION(calloc) :
Calloc is primarily used to allocate memory for arrys.It differs from malloc
only in that it sets memory to null characters. The calloc function declaration:
Void *calloc(size_t element_count, size_t element_size);

The result is the same for both malloc and calloc.

calloc returns the address of the first byte in the memory space allocated. If it is not
successful calloc returns null pointer.
Example:
If(!(ptr=(int*)calloc(200,sizeof(int))))
//no memory available
exit(100);
//memory available

In this example we allocate memory for an array of 200 integers.

REALLOCATION OF MEMORY(realloc):

The realloc function can be highly inefficient and therefore should be used
advisedly. When given a pointer to a previously allocated block of memory realloc
changes the size of the block by deleting or extending the memory at the end of the
block. If the memory can not be extended because of other allocations realloc
allocates completely new block,copies the existing memory allocation to the new
location,and deletes the old allocation.

Void *realloc(void*ptr,size_t newsize);




Ptr
Before




10 Integers




18 55 33 121 64 1 90 31 5 77

Ptr=realloc(ptr,15*sizeof(int));
New
elements
not
initialized
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 101

VIDYA VIKAS INSTITUTE OF TECHNOLOGY


ptr
18 55 33 121 64 1 90 31 5 77 ? ? ? ? ?

15 Integers

After




Releasing Memory(free):When memory locations allocated by malloc,calloc or
realloc are no longer needed, they should be freed using the predefined function free.
It is an error to free memory with a null pointer, a pointer to other than the first
element of an allocated block, a pointer that is a different type then the pointer that
allocated the memory, it is also a potential error to refer to memory after it has been
released.

Void free(void *ptr);




ptr ptr

Before After
Free(ptr);

In above example it releases a single element to allocated with a malloc,back to heap.


BEFORE AFTER



Ptr 200 integers ptr 200 integers

Free(ptr);


In the above example the 200 elements were allocated with calloc. When we
free the pointer in this case, all 200 elements are return to heap. First, it is not the
pointers that are being released but rather what they point to. Second , To release an
array of memory that was allocated by calloc , we need only release the pointer once.
It is an error to attempt to release each element individually.
Releasing memory does not change the value in a pointer. Still contains the
address in the heap. It is a logic error to use the pointer after memory has been
released.





COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 102

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

Note: Memory space should be freed whenever it is not required. The operating
system will release all memory when your program terminates.

COMMAND LINE ARGUMENTS:

When we see the main() always it has empty parantheses. We can also pass
arguments to main(). The arguments can be passed from Operating System
Command Prompt. Therefore they are called as Command Line Arguments.
We have two such arguments namely argc and argv. Argc is an integer
variable where as argv is array of pointers to character, i.e., an array of strings. Each
string in this array will represent a argument that is passed to main. The value of argc
will indicate the number of arguments passed. The Skeleton of main along with
arguments will look like.

main(int argc, char *argv[])
{

}
In order to pass one or more arguments to the program when it is executed
from the Operating System, the parameters must follow the program name on the
Command line as.
Programme arg1,arg2. argn
The individual parameters must be separated by a blank space.
The program name will be stored as the first item argv, followed by each of the
parameters.
If there are n parameters, there will be (n+1) entries in argv. argc will
automatically be assigned the value (n+1).

Eg:-
#include<stdio.h>
main(int argc, char *argv[])
{
int count;
printf(argc = %d\n,argc);
for (count =0;count<argc;count++)
printf(argv[%d] = %s\n, count, argv[count]);
}

Suppose if the above program is saved as cmdprg.c, then the command line for
executing program is like

C:\>cmdprg one two three
Then output will be ------------
argc =4
argv[0] =cmdprg
argv[1] =one
argv[2] =two
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 103

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
argv[3] = three.


/* Demonstrate the use of command-line arguments */

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(int argc,char * argv[])
{
//statements
printf(the number of arguments: %d\n,argc);
printf(the name of the program : %s\n,argv[0]);
for(int i=1;I<argc; i++)
printf(user value no. %d: %s\n , I,argv[i]);
return 0;
}//main

output:

c:>cmdline hello
The number of arguments :2
The name of the program:cmdline
User value number.1:hello

CHARACTER ARRAYS (STRINGS) :

A String is an array of characters. Any group of characters (except double
quote sign )defined between double quotes is a constant string.
Ex: C is a great programming language.

If we want to include double quotes.

Ex: \C is great \ is norm of programmers .
Declaring and initializing strings :-
A string variable is any valid C variable name and is always declared as an array.
char string name [size];

size determines number of characters in the string name. When the compiler assigns a
character string to a character array, it automatically supplies a null character (\0) at
end of String. Therefore, size should be equal to maximum number of character in
String plus one.

String can be initialized when declared as
1. char city[g]= NEW YORK;
2. char city[g]= {N,E,W, ,Y,O,R,K,/0};
C also permits us to initializing a String without specifying size.
Ex:- char Strings[ ]= {G,O,O,D,\0};

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 104

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
READING STRINGS FROM USER:

%s format with scanf can be used for reading String.

char address[15];
scanf(%s,address);

The problem with scanf function is that it terminates its input on first white space it
finds. So scanf works fine as long as there are no spaces in between the text.

Reading a line of text :

If we are required to read a line of text we use getchar(). which reads a single
characters. Repeatedly to read successive single characters from input and place in
character array.
/* Program to read String using scanf & getchar */
#include<stdio.h>
main()
{
char line[80],ano_line[80],character;
int c;
c=0;
printf(Enter String using scanf to read \n);
scanf(%s, line);
printf(Using getchar enter new line\n);
do
{
character = getchar();
ano_line[c] = character;
c++;
} while(character !=\n);
c=c-1;
ano_line[c]=\0;
}
STRING INPUT/OUTPUT FUNCTIONS:

C provides two basic ways to read and write strings.First we can read and write
strings with the formatted input/output functions,scanf/fscanf and prinf/fprinf.Second
we can use a special set of strin only functions ,get string(gets/fgets)and put
string(puts/fputs).

Formatted string Input/Output:

Formatted String Input:scanf/fscanf:

Declarations:

int fscanf(FILE *stream, const char *format, ...);
int scanf(const char *format, ...);
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 105

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
The ..scanf functions provide a means to input formatted information from a stream
fscanf reads formatted input from a stream
scanf reads formatted input from stdin
These functions take input in a manner that is specified by the format argument and
store each input field into the following arguments in a left to right fashion.
Each input field is specified in the format string with a conversion specifier which
specifies how the input is to be stored in the appropriate variable. Other characters in
the format string specify characters that must be matched from the input, but are not
stored in any of the following arguments. If the input does not match then the function
stops scanning and returns. A whitespace character may match with any whitespace
character (space, tab, carriage return, new line, vertical tab, or formfeed) or the next
incompatible character.
INPUT CONVERSION SPECIFICATION:

FLAG:
There is only one flag for input formatting,The assignment suppression
flag(*).
The assignment suppression flag tells scanf that the next input field is to be read but
not stored. It is discarded.

Example:
Scanf(%d%*c%f, &x,&y);

WIDTH:

The width specifies the maximum width of the input(in characters).This
allows us to break out a code that may be stored in the input without spaces.


SIZE:

A size specification is a modifier for the conversion code. Used in
combination with the conversion code,specifies the type of the associative variable.

CONVERSION CODES:

Integer(d): The decimal (d) format code accepts a value from the input stream and
formats it in to the specified variables. It reads only decimal digits and an optional
plus or minus sign is the first character of the value.

Integer(i): The integer format code (i) allows the user to create decimal ,octal or
hexadecimal numbers. Numbers starting with any digit other than zero are read and
stored as decimal values. Numbers starting with zero are interpretes as octal values
and are converted to decimal and stored. Hexadecimal numbers must be prefixed with
0x (or) 0X, The hexadecimal value is converted to decimal and stored.

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 106

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Octal and hexadecimal(o,x): The octal (o) and hexadecimal (x) conversion codes
perform unsigned conversion. For octal only valid input digits are 07. For
Hexadecimal input valid digits are 09, af and AF.

Scientific notation (e,g,a): The C languages uses three real format codes for
scientific notation. In scientific notation the significand and exponent are specify
separately. The significant part is a floating point number that contains as many
significant digits as possible.

Count(n): To verify the number of input characters we use the n-conversion code.
The code requires a matching variable address in to which scanf places the count of
the characters input.

The Common Input Format Mistakes: Two common mistakes while formatting
input stream, They are

Invalid Address
Datatype conflict

Invalid address: The common mistake is to use a data value rather than an address for
the input parameter

Data type conflict: It is conflict between the format stream and the input stream. It
occurs, For example when the format string calls for a numeric value and the input
stream contains alphabetic character then scanf operation aborts.
Formatted String Output:printf/fprintf:
Declarations:
int fprintf(FILE *stream, const char *format, ...);
int printf(const char *format, ...);
The ..printf functions provide a means to output formatted information to a stream.
fprintf sends formatted output to a stream
printf sends formatted output to stdout
These functions take the format string specified by the format argument and apply
each following argument to the format specifiers in the string in a left to right fashion.
Each character in the format string is copied to the stream except for conversion
characters which specify a format specifier.

Flags:
- Value is left justified (default is right justified). Overrides the 0 flag.
+ Forces the sign (+ or -) to always be shown. Default is to just show the - sign.
Overrides the space flag.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 107

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Width:
The width of the field is specified here with a decimal value. If the value is not large
enough to fill the width, then the rest of the field is padded with spaces (unless the 0
flag is specified). If the value overflows the width of the field, then the field is
expanded to fit the value. If a * is used in place of the width specifer, then the next
argument (which must be an int type) specifies the width of the field. Note: when
using the * with the width and/or precision specifier, the width argument comes first,
then the precision argument, then the value to be converted.
Precision:
The precision begins with a dot (.) to distinguish itself from the width specifier. The
precision can be given as a decimal value or as an asterisk (*). If a * is used, then the
next argument (which is an int type) specifies the precision. Note: when using the *
with the width and/or precision specifier, the width argument comes first, then the
precision argument, then the value to be converted. Precision does not affect the c
type.
String Input/Output
In addition to the Formatted string functions,C has two sets of string functions that
read and write strings without reformatting any data.These functions convert text file
lines to strings and strings to text file lines.
Line to String:
gets():
Declaration:
char *gets(char *str);

Reads a line from stdin and stores it into the string pointed to by str. It stops when
either the newline character is read or when the end-of-file is reached, whichever
comes first. The newline character is not copied to the string. A null character is
appended to the end of the string.
On success a pointer to the string is returned. On error a null pointer is returned. If the end-of-file occurs before any
characters have been read, the string remains unchanged.
fgets():

Declaration:

char *fgets(char *str, int n, FILE *stream);

Reads a line from the specified stream and stores it into the string pointed to by str. It
stops when either (n-1) characters are read, the newline character is read, or the end-
of-file is reached, whichever comes first. The newline character is copied to the string.
A null character is appended to the end of the string.
On success a pointer to the string is returned. On error a null pointer is returned. If the end-of-file occurs before any
characters have been read, the string remains unchanged.
String to Line:
puts:
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 108

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Declaration:
int puts(const char *str);

Writes a string to stdout up to but not including the null character. A newline
character is appended to the output.
On success a nonnegative value is returned. On error EOF is returned.
fputs():
Declaration:
int fputs(const char *str, FILE *stream);
Writes a string to the specified stream up to but not including the null character.
On success a nonnegative value is returned. On error EOF is returned.
ARRAY OF STRINGS:
Arrays of strings (arrays of character arrays) can be declared and handled in a similar manner to that described for 2-D
arrays.
Consider the following example:
#include< stdio.h>

void main(void)
{
char names[2][8] = {"Frans", "Coenen"};

/* Output */

printf("names = %s, %s\n",names[0],names[1]);
printf("names = %s\n",names);

/* Output initials */

printf("Initials = %c. %c.\n",names[0][0],names[1][0]);
}
Here we declare a 2-D character array comprising two "roes" and 8 "columns". We then initialise this array with two character
strings. The output the array we need to index into each row --- using the 2-D array name on its own (strings) as a pointer
cause only the first element ("row") to be produced. Note that we can still index to individual elements using index pairs. The
output from the above will be:
names = Frans, Coenen
names = Frans
Initials = F. C.

ARRAYS OF STRINGS AS POINTER ARRAYS
The declaration of an array of character pointers is an extremely useful extension to single string pointer declarations.For
example:
char *names[2];
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 109

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Creates a two element array of character pointers (i.e. each element is a pointer to a character). As individual pointers each
can be assigned to point to a string using a normal assignment statement:
names[0] = "Frans";
names[1] = "Coenen";
Alternatively we can initialise the names array as shown in the following programs:
#include< stdio.h>

void main(void)
{
char *names[2] = {"Frans", "Coenen"};

/* Output */

printf("names = %s, %s\n",names[0],names[1]);

/* New assignments */

names[0] = "Ray";
names[1] = "Paton";

/* Output */

printf("names = %s, %s\n",names[0],names[1]);
}
In the above the declaration of names both creates an array of pointers and initilises
the pointers with appropriate addresses. Once addresses have been assigned to the
pointers, each pointer can be used to access its corresponding string. The output from
the above is as follows:
names = Frans, Coenen
names = Ray, Paton
STRING/DATA CONVERSION:
String to Data Conversion:
sscanf():
The string scan function is called sscanf. The sscanf function accepts a string from
which to read input, then, in a manner similar to printf and related functions, it accepts
a template string and a series of related arguments. It tries to match the template string
to the string from which it is reading input, using conversion specifier like those of
printf.
The sscanf function is just like the deprecated parent scanf function, except that the
first argument of sscanf specifies a string from which to read, whereas scanf can only
read from standard input. Reaching the end of the string is treated as an end-of-file
condition.
ret = sscanf( s, format [, p1, p2, ...] );

const char *s;
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 110

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
points to the string which is to be read.
const char *format;
is a format string similar to that for "scanf".
p1, p2, p3, ...
are pointers to various data types.
int ret;
is the number of matching data items that were read in. This may be zero if the
first data item found does not match the type that was expected. If an error or
end of string occurs before the first item could be read in, EOF is returned.
Description:
"sscanf" reads input from the string "s" and assigns it to the areas of memory pointed
to by the pointers "p1", "p2", and so on. The "format" string indicates how to interpret
the characters being read in.
Important difference between sscanf and printf is that the arguments to sscanf must be
pointers; this allows sscanf to return values in the variables they point to. If you forget
to pass pointers to sscanf, you may receive some strange errors, and it is easy to forget
to do so; therefore, this is one of the first things you should check if code containing a
call to sscanf begins to go awry.
A sscanf template string can contain any number of any number of whitespace
characters, any number of ordinary, non-whitespace characters, and any number of
conversion specifiers starting with %. A whitespace character in the template string
matches zero or more whitespace characters in the input string. Ordinary, non-
whitespace characters must correspond exactly in the template string and the input
stream; otherwise, a matching error occurs. Thus, the template string " foo " matches
"foo" and " foo ", but not " food ".

Data to String Conversion:
The string print function,sprintf. Returns a string formatted by the usual printf()
conventions of the C library function sprintf().
i = sprintf( s, control [, arg1, arg2, ...] );

char *s;
is the string to which the output should be written.
const char *control;
is a "printf" control string.
arg1, arg2, ...
are the values to be output.
int i;
is the number of characters that were output. If a write error occurred, a
negative number is returned.
Description:
"sprintf" writes to the string "s". "sprintf" converts, formats, and prints its arguments
under control of the string "control.
STRING HANDLING FUNCTIONS:

strcat( ) Concatenates two Strings
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 111

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
strcmp( ) Compares two Strings
strcpy( ) Copies one String Over another
strlen( ) Finds length of String

strcat() :

This function yours two strings together.
strcat(string1,string2);
string1 = VERY

string2 = FOOLISH

strcat(string1,string2);

string1=VERY FOOLISH
string2 = FOOLISH

strcmp() function :

This function compares two strings identified by arguments and has a value 0
if they are equal. If they are not, it has the numeric difference between the first non-
matching characters in the Strings.
strcmp(string1,string2);
Ex:- strcmp(name1,name2);
strcmp(name1,John);
strcmp(ROM,Ram);

strcpy() function :

It works almost as a string assignment operators. It takes the form
strcpy(string1,string2);
string2 can be array or a constant.


strlen() function :

Counts and returns the number of characters in a string.
n= strlen(string);
n integer variable which receives the value of length of string.

/* Illustration of string-handling */

#include<stdio.h>
#include<string.h>
main()
{
char s1[20],s2[20],s3[20];
int X,L1,L2,L3;
printf(Enter two string constants\n);
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 112

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
scanf(%s %s,s1,s2);
X=strcmp(s1,s2);
if (X!=0)
{
printf(Strings are not equal\n);
strcat(s1,s2);
}
else
printf(Strings are equal \n);
strcpy(s3,s1);
L1=strlen(s1);

L2=strlen(s2);
L3=strlen(s3);
printf(s1=%s\t length=%d chars \n,s1,L1);
printf(s2=%s\t length=%d chars \n,s2,L2);
printf(s3=%s\t length=%d chars \n,s3,L3);
}






UNIT - V
STRUCTURES :

A Structure is a collection of elements of dissimilar data types. Structures
provide the ability to create user defined data types and also to represent real world
data.
Suppose if we want to store the information about a book, we need to store its
name (String), its price (float) and number of pages in it(int). We have to store the
above three items as a group then we can use a structure variable which collectively
store the information as a book.
Structures can be used to store the real world data like employee, student,
person etc.

Declaration :

The declaration of the Structure starts with a Key Word called Struct and ends
with ; . The Structure elements can be any built in types.

struct <Structure name>
{
Structure element 1;
Structure element 2;
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 113

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
-
-
-
Structure element n;
};

Then the Structure Variables are declared as

struct < Structure name > <Var1,Var2>;

Eg:- struct emp
{
int empno.
char ename[20];
float sal;
};
struct emp e1,e2,e3;

The above Structure can also be declared as :

struct emp struct
{ {
int empno; int empno;
char ename[20]; (or) char ename[20];
float sal; float sal;
}e1,e2,e3; }e1,e2,e3;


Initialization :

Structure Variables can also be initialised where they are declared.
struct emp
{
int empno;
char ename[20];
float sal;
};
struct emp e1 = { 123,Kumar,5000.00};

To access the Structure elements we use the .(dot) operator.
To refer empno we should use e1.empno
To refer sal we whould use e1.sal

Structure elements are stored in contiguous memory locations as shown
below. The above Structure occupies totally 26 bytes.


e1.empno E1.ename E1.sal
123 Kumar 5000.00
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 114

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
2000 2002 2022


1. Program to illustrate the usage of a Structure.

main()
{
struct emp
{
int empno;
char ename[20];
float sal;
};
struct emp e;
printf ( Enter Employee number: \n);
scanf(%d,&e.empno);
printf ( Enter Employee Name: \n);
scanf(%s,&e.empname);
printf ( Enter the Salary: \n);
scanf(%f,&e.sal);
printf ( Employee No = %d, e.empno);
printf (\n Emp Name = %s, e.empname);
printf (\n Salary = %f, e.sal);
}




NESTING OF STRUCTURES :

One Structure can be enclosed in another Structure. The Structure which is
to be nested must be declared before it is used. We can nest a Structure within a
Structure, which is in still another Structure and so on. Nesting of Structure can be
done to any no of levels.
The elements of the nested Structure are accessed by using one more dot(.)
operator.

Eg:- struct date
{
int dd, mm, yy;
};
struct student
{
int rno;
char sname[15];
struct date dob;
};
struct student s;
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 115

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Here, dob is the Nested Structure. To access this we use s.dob.dd or
s.dob.mm or s.dob.yy.

/* Program to read Student Details and Calculate total and average using
structures */

#include<stdio.h>
main()
{
struct stud
{
int rno;
char sname[20];
int m1,m2,m3;
};
struct stud s;
int tot;
float avg;

printf(Enter the student roll number: \n);
scanf(%d,&s.rno);
printf(Enter the student name: \n);
scanf(%s,&s.sname);
printf(Enter the three subjects marks: \n);
scanf(%d%d%d,&s.m1,&s.m2,&s.m3);

tot = s.m1 + s.m2 +s.m3;
avg = tot/3.0;



printf(Roll Number : %d\n,s.rno);
printf(Student Name: %s\n,s.sname);
printf(Total Marks : %d\n,tot);
printf(Average : %f\n,avg);
}

/* Program to read Item Details and Calculate Total Amount of Items*/

#include<stdio.h>
main()
{
struct item
{
int itemno;
char itemname[20];
float rate;
int qty;
};
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 116

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
struct item i;
float tot_amt;

printf(Enter the Item Number \n);
scanf(%d,&i.itemno);
printf(Enter the Item Name \n);
scanf(%s,&i.itemname);
printf(Enter the Rate of the Item \n);
scanf(%f,&i.rate);
printf(Enter the number of %s purchased ,i.itemname);
scanf(%d,&i.qty);

tot_amt = i.rate * i.qty;

printf(Item Number: %d\n,i.itemno);
printf(Item Name: %s\n,i.itemname);
printf(Rate: %f\n,i.rate);
printf(Number of Items: %d\n,i.qty);
printf(Total Amount: %f,tot_amt);
}

/*Program to illustrate the use of Nested Structures */
#include<stdio.h>
main()
{
struct date
{
int dd, mm, yy;
};
struct stud
{
int rno;
char sname[15];
struct date dob;
int tot;
};
struct stud s;
printf(Enter the student roll number: \n);
scanf(%d,&s.rno);
printf(Enter the student name: \n);
scanf(%s,&s.sname);
printf(Enter the date of birth of student(dd/mm/yy): \n);
scanf(%d%d%d,&s.dob.dd,&s.dob.mm,&s.dob.yy);

printf(Roll Number : %d\n,s.rno);
printf(Student Name: %s\n,s.sname);
printf(Date of Birth: %d/%d/%d\n, s.dob.dd,s.dob.mm,s.dob.yy);
printf(Total Marks : %f\n,s.tot);
}
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 117

VIDYA VIKAS INSTITUTE OF TECHNOLOGY


ARRAYS OF STRUCTURES :

To store more number of Structures, we can use array of Structures. In array
of Structures all elements of the array are stored in adjacent memory location.

/* Program to illustrate the usage of array of Structures.

main()
{
struct book
{
char name[20];
float price;
int pages;
};
struct book b[10];
int i;
for (i=0;i<10;i++)
{
print(\n Enter Name, Price and Pages);
scanf(%s%f%d, b[i].name,&b[i].price,&b[i].pages);
}
for (i i=0;i<10;i++)
printf( \n%s%f%d, b[i].name,b[i].price,b[i].pages);
}





STRUCTURES WITH FUNCTIONS :

The entire Structure can be passed to a function at once. Whenever a
Structure is passed to a function the Structure should be declared outside the main(),
otherwise it will not be known to all the functions in the program.

Program to illustrate the use of Structures with functions.
struct stud
{
int rno;
char name[20];
int tot;
};
main()
{
struct stud s = { 111, Ramoo,500};
display(s);
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 118

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
}
display(struct stud s)
{
printf(Roll Number: %d\n, s.rno);
printf(Student Name: %s\n, s.name);
printf(Total Marks: %d\n, s.tot);
}


STRUCTURE POINTER :

A Pointer pointing to a struct is called Structure Poniter. A Structure
Pointer can be used to store the address of a Structure Variable. An arrow operator
() is used to refer the Structure elements when a pointer is used with a Structure.


/* Program to illustrate the usage of Structures with Pointer */

struct emp
{
int empno;
char ename[20];
float sal;
};

main()
{
struct emp e;

reademp(&e);
displayemp(&e);
}
reademp(struct emp *e)
{
printf(Enter Emp Details:);
scanf(\n%d%s%f, &eempno, eename, &esal);
}
display emp(struct emp *e)
{
printf(empno:%d\tename:%s\tSalary=%f,eempno, ename,esal);
}


SELF REFERENTIAL STRUCTURES:

A Self referential Structure is one that includes with in its structure atleast
one member which is a pointer to the same structure type. With self referential
structures we can create very useful data structures such as linked lists,trees etc.
Example:
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 119

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Struct tag
{
char name[40];
struct emp*next;
};

A structure contains teo members a 40 element character array called name,and a
pointer to another structure of the same called next.

APPLICATIONS OF STRUCTURES :

Structures can be used for a Variety of Applications like:
a) Database Management.
(To maintain data about employees in an organisation, book in
a library, items in a Store etc)
b) Changing the size of the Cursor.
c) Clearing the contents of the Screen.
d) Placing the Cursor at appropriate position on Screen.
e) Drawing any graphics Shape on the Screen.
f) Receiving a Key from the Keyboard.
g) Checking the memory size of the Computer.
h) Finding the list of equipment attached to the Computer.
i) Formatting a Floppy.
j) Hiding a file from the Directory.
k) Displaying the Directory of a Disk.
l) Sending the Output to Printer.
m) Interacting with the Mouse.


UNIONS :

Union, similar to Structures, are collection of elements of different data types.
However, the members within a union all share the same storage area within the
computers memory, whereas each member within a Structure is assigned its own
unique Storage area.

Structure enables us to treat a member of different variables stored at different
places in memory, a union enables us to treat the same space in memory as a number
of different variables. That is, a union offers a way for a section of memory to be
treated as a variable of one type on one occasion and as a different variable of a
different type on another occasion.

Unions are used to conserve memory. Unions are useful for applications
involving multiple members, where values need not be assigned to all of the members
at any given time. An attempt to access the wrong type of information will produce
meaningless results.

The union elements are accessed exactly the same way in which the structure
elements are accessed using dot(.) operator.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 120

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

The difference between the structure and union in the memory representation
is as follows.

struct cx
{
int i;
char ch[2];
};
struct cx s1;

The Variable s1 will occupy 4 bytes in memory and is represented as

---------- s.i ------- s.ch[0] s.ch[1]

4002 4003 4004 4005


The above datatype, if declared as union then

union ex
{
int i;
char ch[2];
}
union ex u;

--------u.i ---------------

u.ch[0] u.ch[0]




/* Program to illustrate the use of unions */

main()
{
union example
{
int i;
char ch[2];
};
union exaple u;

u.i = 412;

print(\n u.i = %d,u.i);
print(\n u.ch[0] = %d,u.ch[0]);
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 121

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
print(\n u.ch[1] = %d,u.ch[1]);

u.ch[0] = 50; /* Assign a new value */

print(\n\n u.i = %d,u.i);
print(\n u.ch[0] = %d,u.ch[0]);
print(\n u.ch[1] = %d,u.ch[1]);
}


Output :

u.i = 512
u.ch[0] = 0
u.ch[1] =2
u.i = 562
u.ch[0] = 50
u.ch[1] =2

A union may be a member of a structure, and a structure may be a member of a union.
And also structures and unions may be freely mixed with arrays.




/* Program to illustrate union with in a Structure */

main()
{

union id
{

char color;
int size;

};

struct {

char supplier[20];
float cost;
union id desc;

}pant, shirt;

printf(%d\n, sizeof(union id));

shirt.desc.color = w;
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 122

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
printf(%c %d\n, shirt.desc.color, shirt.desc.size);

shirt.desc.size = 12;
printf(%c %d\n, shirt.desc.color, shirt.desc.size);

}

/* Program to raise a number to a power */

#include <stdio.h>
#include <math.h>

typedef union {

float fexp; /* float exponent */
int nexp; /* integer exponent */

}nvals;

typedef struct{

float x; /* value to raised to a power */
char flag; /* f if exponent is float i if exponent is integer */

nvals exp; /* union containing exponent */

}values;

float power (values a ) /* function calculations power */
{
int i;
float y = a.x;
if (a.flag = = i){ /* integer exponent */

if (a.exp.nexp = = 0) /* zero exponent */
y = 1.0;
else {
for (i = 1;i<abs(a.exp.nexp);++i)
y * = a.x;
if (a.exp.nexp<0)
y = 1.0/y; /* negative integer exponent */
}
}
else
y = exp(a.exp.fexp*log(a.x)); /* floating point exponent */
return(y);
}

main()
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 123

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
{

values a ;
int i;
float n,y;

printf(Enter the value for X);
scanf(%f,&a.x);

printf(Enter the value for n);
scanf(%f,&n);

/* determine type of exponent */

i = (int)n;
a.flag = (i = = n) ? i : f 3

if((a.flag = = i)

a.exp.nexp = i;

else

a.exp.fexp = n;

/* raise X to the power */

if(a.flag = = f && a.x <= 0.0)

printf(ERROR, cannont raise negative number to floating point
power);

else{

y = power(a);
printf(\n y = % .4f,y);

}
}
TYPEDEF:

Typedef is used to create new datatype.The statement typedef is used while
defining the new data type.

Syntax:

Typedef type dataname;

Here , type is the data type and dataname is the user defined name for that type.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 124

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

Typedef int hours;
Here, hours is another name for int and now we can use hours instead of int in the
program as follows:

Program:

#define H 60
main()
{
typedef int hours;
hours hrs;
clrscr();
printf(Enter hours\n);
scanf(%d,&hrs);
printf(minutes=%d,hrs*H);
printf(\nseconds=%d,hrs*H*H);
}

output:

Enter hours: 2
Minutes=120
Seconds=7200

Explanation of program:

In the above example with typedef we had declared hours as an integer data
type. Immediately after the typedef statement hrs is a variable of hours datatype which
is similar to int. further the program calculates minuter and seconds using hrs
variable.


BITFIELDS:
A bitfield allows structures to be subdivided into groups of bits. This process allows multiple variables to be packed
into a single block of memory.
syntax :type_name <variable_name> : number_of_bits
The type can be char, short, int, or int64 (unsigned or signed) or any of the equivalent types. If the variable name
is omitted, the given number of bits will be skipped.
For example:
int alpha : 5;
int : 12;
int beta : 15;

would pack alpha and beta into one 32-bit value, but skip 12 bits in the middle.

Example: Suppose we want to store the following data about an employee. Each
employee can:
(a) be male or female
(b) be single,married,divorced or widowed
(c) have one of the eight different hobbies
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 125

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
(d) can chose from any of the fifteen different schemes proposed by the company
to pursue his/her hobby.

This means one bit is needed to store gender, two bits to store marital status, three for
hobby and four for scheme i.e there is a need for ten bits altogether which means we
can pack all this information in to a single integer since an integer is 16 bits long.
To do this using bit fields we declare the following structure:

Struct employee
{
unsigned gender:1;
unsigned mat_stat:2;
unsigned hobby:3;
unsigned scheme:4;
};
The colon in the above declaration tells the compiler that we are talking about bit
fields and the number after it tells how many bits to allot for the field. Once we have
established a bit field, we can reference it just like any other structure element as
shown in the program given below:

#include<stdio.h>
#define MALE 0;
#define FEMALE 1;
#define SINGLE 0;
#define MARRIED 1;
#define DIVORCED 2;
#define WIDOWED 3;

void main()
{
struct employee
{
unsigned gender:1;
unsigned mar_stat:2;
unsigned hobby:3;
unsigned scheme:4;
};
struct employee e;
e.gender=MALE;
e.mar_status=DIVORCED;
e.hobby=5;
e.scheme=9;

printf(\nGender=%d,e.gender);
printf(\nMarital status=%d,e.mar_status);
printf(\nBytes occupied by e=%d, sizeof(e));
}


COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 126

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
output:
Gender=0
Marital status=2
Bytes occupied by e=2

Two special bitfield modes that determine how the bits are packed into variables is:
1.padded bitfields
2. unpadded bitfields.
PADDED BI TFI ELDS:

With padded bitfields (the default), how the bits are packed into a variable
depends upon the current endianness. By default, bits are packed right-to-left for little
endian files, and left-to-right for big endian files. For example, for the bitfields:
ushort a : 4;
ushort b : 7;
ushort c : 5;
In little endian mode, this structure would be stored as the bits:
cccccbbb bbbbaaaa
(and stored on disk as bbbbaaaa cccccbbb). In big endian mode, this structure would
be stored as the bits:
aaaabbbb bbbccccc
(and stored on disk as aaaabbbb bbbccccc). Whether the bits are packed left-to-right
or right-to-left can be controlled by the functions BitfieldLeftToRight, and
BitfieldRightToLeft.
In this mode, the program will automatically add padding bits when needed. If
the size of the type being defined changes, padding will be added so the bitfield will
be defined on the next variable boundary. Also, if the specified bitfield would step
across the boundary of a variable, padding is added so the bitfield starts at the next
variable.
For example:
int apple : 10;
int orange : 20;
int banana : 10;
int peach : 12;
short grape : 4;
The bitfields apple and orange would be packed into one 32 bit value. However,
banana steps over the variable boundary, so 2 bits of padding are added so that it
starts at the next 32 bit value. Banana and peach are packed into another 32-bit value,
but because the size of the type changes with grape, an extra 10 bits of padding is
added before grape is defined.
UNPADDED BITFIELDS:
Unpadded bitfield mode treats the file as one long bit stream. No padding bits
are added if the variable type changes or if the bits cannot be packed into a single
variable. The unpadded mode can be entered by calling the function
BitfieldDisablePadding (padding can be turned back on by calling
BitfieldEnablePadding).
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 127

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
In unpadded bitfield mode, each variable defined reads some bits from the
bitstream. For example:
BitfieldDisablePadding();
short a : 10;
int b : 20;
short c : 10;
Here a reads the first 10 bits from the file, b reads the next 20 bits from the file,
and so on. If the bitfields are defined as reading from right to left (this is the default
for little endian data and can enabled using the function BitfieldRightToLeft), the
variables would be stored as the bits:
aaaaaaaa bbbbbbaa bbbbbbbb ccbbbbbb cccccccc
If the bitfields are defined as reading from left to right (this is the default for big
endian data and can enabled using the function BitfieldLeftToRight), the variables
would be stored as the bits:
aaaaaaaa aabbbbbb bbbbbbbb bbbbbbcc cccccccc


NOTE:When declaring structures containing unpadded bitfields, no extra padding
bits are added between the structures. (Note that internally, any unpadded right-to-left
bitfield is forced to be declared in little endian mode and any unpadded left-to-right
bitfield is forced to be declared in big endian mode.)

ENUMERATED DATA TYPES
In computer programming, an enumerated type (also called enumeration or enum)
is a data type consisting of a set of named values called elements, members or
enumerators of the type. The enumerator names are usually identifiers that behave as
constants in the language. A variable that has been declared as having an enumerated
type can be assigned any of the enumerators as a value.
Enumerated data type variables can only assume values which have been previously
declared.

enum month { jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec };
enum month this_month;

this_month = feb;

In the above declaration, month is declared as an enumerated data type. It consists of a
set of values, jan to dec. Numerically, jan is given the value 1, feb the value 2, and so
on. The variable this_month is declared to be of the same type as month, then is
assigned the value associated with feb. This_month cannot be assigned any values
outside those specified in the initialization list for the declaration of month.

#include <stdio.h>

main()
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 128

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
{
char *pwest = "west",*pnorth = "north", *peast="east",
*psouth="south";
enum location { east=1, west=2, south=3, north=4};
enum location direction;

direction = east;

if( direction == east )
printf("Cannot go %s\n", peast);
}

The variables defined in the enumerated variable location should be assigned initial
values.













UNIT - VI
FILES :

Files are used to store the information permanently and to access information
whenever necessary. Files are stored in the Secondary Storage Devices like Floppy
Disks, Hard Disks etc. Unlike other programming languages, C does not distinguish
between sequential and direct access (random access) files.

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 129

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
There are two different types of files in C. They are Stream Oriented (or
Standard) files and System-Oriented (or Low-Level) files.

STREAMS:

All input and output operations in C is performed with streams. Stream is a
sequence of characters organized into lines (text stream), each line consists of 0 or
more characters and ends with the newline character \n. Streams provide
communications channels between files and programs. A stream can be connected to
a file by opening it and the connection is broken by closing the stream.

When program execution begins, three files and their associated streams are
connected to the program automatically. They are

the standard input stream
the standard output stream
the standard error stream

Standard input: It is connected to the keyboard & it enables a program to read data
from the keyboard.
Standard output: It is connected to the screen & it enables a program to write data
to the screen.
Standard error: It is+ connected to the screen & all error messages are output to
standard error.

Operating systems often allow these streams to be redirected to other devices,
Standard input, standard output and standard error are manipulated with file pointers
stdin, stdout and stderr.

BINARY FILES:

Binary files contain fixed length records, They are in binary format (machine
readable) not a human readable format like text files, Binary files can be accessed
directly (i.e. random access). The record structure for a binary file is created using
structures, They are more efficient than text files as conversion from ASCII to binary
(reading) and vice versa for writing does not have to occur , They cannot be read
easily by other non-C programs. Binary files are appropriate for online transaction
processing systems.

E.x: Airline reservation, Order processing, Banking systems.

fwrite function:

The function fwrite is used to write to a binary file.

SYNTAX:
size_t fwrite (void *ptr, size_t size, size_t n, FILE *fptr);

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 130

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
- fwrite writes from array ptr, n objects of size size to file pointed to by fptr
- fwrite returns the number of objects written
- which is less than n if an error occurs

fread:

The function fread is used to read from a binary file.

SYNTAX:

size_t fread (void *ptr, size_t size,size_t n, FILE *fptr);

fread reads n objects of size size from a file pointed to by fptr, and places them in
array ptr
fread returns the number of objects read which may be less than the number
requested
call to feof() is necessary to distinguish EOF and error condition.


TEXT FILES :

Text files are classified in to two types.These are:

1.Formatted Text files
2.Unformatted textfiles



FORMATTED TEXT FILES :

Formatted Text files contain variable length records must be accessed
sequentially, processing all records from the start of file to access a particular record.

For formatted input and output to files we use fprintf and fscanf functions.
These functions are the same as printf and scanf except that the output is directed to
the stream accessed by the file pointer, fptr.

fprintf :

Fprintf is used to write a record to the file.

Syntax : int fprintf (FILE *fptr, const char* fmt,...)

Ex :fprintf (fptr,"%d %s %.2f\n",accNo,name,balance);

fprintf returns the number of characters written or negative if an error occurs.

fscanf :
Fscanf is used toRead a record from the file.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 131

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

Syntax : int fscanf (FILE *fptr, const char* fmt, ... )

Ex :fscanf (fptr,"%d %20s %f",&accNo,name, &balance);

fscanf returns the number of input items assigned or EOF if an error or EOF occurs
before any characters are input.Rewind(FILE* ptr) - resets the current file position to
the start of the file.

SEARCHING THE FILE:

Accessing a particular record(s) requires
a sequential read from the start of the file
testing each record to see is it being searched for
reset the file pointer to the start of the file ready for the next search.

UPDATING RECORDS:

Records cannot be updated , To update a text file the entire file is rewritten.

UNFORMATTED TEXT FILES :

stdio.h provides many functions for reading and writing to unformatted text
files.


fgetc :

This function is used to read the next character from the stream,This is similar to
getchar().


Syntax : int fgetc (FILE *stream)

It returns the character (as an integer) or EOF if end of file or an error occurs.

fputc :

This function is used to write the character c to the stream.This is similar to
putchar(int).


Syntax : int fputc (int c, FILE *stream)

It returns the character or EOF for error.

fgets :

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 132

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
This function Reads at most the next n-1 characters from the stream into the
array s. Reading stops after an EOF or a newline. If a newline is read, it is stored into
the buffer. A '\0' is stored after the last character in the buffer. This is similar to
gets(char* ).

Syntax : char* fgets (char *s,int n,FILE *stream)

It returns s or NULL if EOF or error occurs

fputs :

This is used to write the string s to the stream. This is similar to puts(const char*).


Syntax : int fputs (const char *s, FILE *stream)

It returns EOF for error.


These file handling functions can be used instead of reading and writing characters
and strings from the keyboard and to the screen.

Positioning The File Pointer :

Fseek is used to position the file pointer at the appropriate record in the file
before reading or writing a record. The function fseek sets the file position for a
stream. Subsequent reads and writes will access data in the file beginning at the new
position

SYNTAX: int fseek (FILE *fp, long offset,int origin)

The position is set to the offset from the origin
fseek returns non zero on error

fseek takes 3 arguments
fp the file pointer for the file in question
offset is an offset in a file we want to seek to
origin is the position that the file pointer is set to origin can be either
SEEK_SET - beginning of file
SEEK_CUR - current position in file
SEEK_END - end of file
It may be necessary when performing a number of different types of access to a
single file to reset the file pointer in certain instances.

Ex: searching for a particular record in a file may leave the file pointer in the middle
of the file.

To write a new record to this file the pointer should be reset to point to the end of
file.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 133

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

rewind :

The function rewind resets the file pointer back to the start of file.

Syntax : void rewind (FILE *fp)
rewind(fp) is equivalent to fseek(fp,0,SEEK_SET).

feof :
The function feof tests for end of file.

Syntax : int feof(FILE *fptr)

Feof accepts a pointer to a FILE, It returns non-zero if EOF and zero otherwise.
It is used when reading a file to check whether the EOF has been reached

These are three main areas where text and binary mode files are different. There are

Handling of New Lines :

In Text Mode, a newline character is connected into the carriage return
linefeed combination before being written to the disk. Likewise, the carriage return-
linefeed combination on the disk is converted back into a newline when the file is
read by a C program.
In Binary Mode, these conversions will not take place.

End of File :

In Text Mode, a special character, whose ascii value is 26, is inserted after the
last character in the file to mark the end of file. If this character is detected at any
point in the file, the read function would return the EOF signal to the program.
In Binary Mode, these is no such special character present in the binary mode
files to mark the end of file. The Binary Mode files keep track of the end of file from
the number of characters present in the directory entry of the file.
The file that has been written in text mode is read back only in text mode.
Similarly, the file that has been written in binary mode must be read back only in
binary mode.

Storage of Numbers :

In Text Mode, numbers are stored as strings of characters. Thus 1234 even
though occupies two bytes in memory, when transferred to the disk would occupy
four bytes, one byte per character.
In Binary Mode, the number will be stored in Binary format. Each number
would occupy same number of bytes on disk as it occupies in memory.


STEPS IN WORKING WITH FILES:

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 134

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
1. Establish a Buffer Area
2. Opening a File
3. Reading from a File or Writing to a File
4. Closing a File.

I. Establish a Buffer Area :

The first step is to establish a buffer area, where the information is temporarily
stored while being transferred between the computers memory and the file.
The Buffer Area is established by writing
FILE *ptrvar;
FILE is a Structure which has been defined in the header file stdio.h
(Standard input/output header file), which is a link between the Operating System and
Program. It is necessary to include the header file stdio.h. The FILE Structure
contain information about the file being used, such as its current size, its location in
memory etc. This buffer area allows information to be read from or written to file
more fastly.
*prtvar is a pointer variable, which contains address of the Structure FILE.

2. Opening a File :

A File must be opened before it can be created or processed. This association
the file name with the buffer area. It also specifies how the file will be utilized i.e.
read-only file, write-only file, or read/write file.
We use the library function fopen() for opening a file.
ptrvar = fopen(filename, mode)
where filename and mode are strings. Filename represent the name of the file,
mode represents how the file opened i.e., read only, write only etc.
The fopen() function returns a pointer to the begins of the buffer area
associated with the file. A NULL value is returned if the file cannot be created or
when existing file cannot be found.
The different file opening modes area listed below.

Mode Meaning
r Open an existing file for reading only
w Open a new file for writing only. If the file exists, its contents are
over written.
a Open an existing file for appending (i.e., for adding new information
at the end of the file). A new file will be created if the file does not
exists.
r+ Open an existing file for both reading and writing.
w+ Open a new file for both reading and writing. If the file exists, the
contents are over written
a+ Open an existing file for both reading and appending. A new file
will be created if the file does not exists


To open the file in Binary file mention the mode along with a extra letter b
as rb, wb, rb+ and so on.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 135

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

3. Reading /Writing form/to a File :

(i) After opening the file we can read the characters from a file or write
the characters into the file by using the two library functions fgetc()
and fputc().
fgetc() reach a character from the current position and advances the
pointer position to the next character, and returns the
character that is read.

Eg:- ch = fgetc(ptrvar)
Fputc() Writes a character into the file.

Eg:- fputc(ch,ptrvar)
(ii) fscanf() and fprintf() are two functions used for formatted reading and
writing of characters, Strings, integers and floats.
(iii) fread() and fwrite():
These are two functions to read and write structures with file in
binary mode.
The Syntax is as follows:
fwrite(&record, sizeof(record),no of records, fileptr);
fread(&record, sizeof(record),no of records, fileptr);
The first argument is the address and the structure.
The second argument is the size of the structure in bytes.
The third argument is the number of structures to read or write.
The last argument is pointer to the file.

4. Closing the File :

Finally, the file must be closed at the end of the program. This can be done
by using the function fclose().
fclose(ptrvar);
It is good programming practice to close a file explicitly, even though C
compiler will automatically close the file.

/* Program to Create a File */

main()
{
FILE *fp;
char ch;
fp = fopen(chars,w);
printf(Enter the characters(enter * to stop)\n);
while((ch=getchar())!=*)
putc(ch,fp);
printf(File Created);
fclose(fp);
}

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 136

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
/* Program to Create a read an Existing File */
#include<stdio.h>
main()
{
FILE *fp;
char ch;
fp = fopen(chars,r);
printf(The contents of the file are:\n);
while((ch=fgetc(fp))!=EOF)
printf(%c,ch);
fclose(fp);
}

/* Program to Copy One File to Another File */

#include<stdio.h>
main()
{
FILE fs,ft;
char ch;
fs = fopen(source,r);
if(fs = =NULL)
{
puts(Cannot open source file);
exist();
}
fr = fopen(target,w);
if(ft = =NULL)
{
puts(Cannot open target file);
fclose(fs);
exist();
}
while((ch=fgetc(fs))!=EOF)
putc(ch,ft);
printf(File Copied);

fclose(fs);
fclose(ft);
}

/* Program to illustrate the use of fprintf() */

#include<stdio.h>
main()
{
FILE *fp;
char itemname[20];
int qty;
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 137

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
float rate;
char choice = y;

fp = fopen (Item,w);

while (choice = = y)
{
printf(Enter Item Name, Quantity and Rate \n);
scanf(%s%d%f,itemname,&qty,&rate);
fprintf(fp, %s%d%f\n,itemname, age,rate);
printf(Do you want to Continue (y/n));
fflush(stdin);
choice = getch();
}
fclose(fp);
}
/* Program to illustrate the use of fscanf() */

#include<stdio.h>
main()
{
FILE *fp;
char itemname[20];
int qty;
float rate;

fp = fopen (Item,r);

while (fscanf(fp,%s%d%f,itemname,&qty,&rate)!=EOF)
{
printf(Item Name : %s\n,itemname);
printf(Quantity =%d\n,qty);
printf(Rate = %f\n,rate);
}
fclose(fp);
}

Till now, we have seen examples of writing individual items into the file.
Now we see how to write a record into a file and read a record from the file by using
fprintf() and fscanf() respectively.
Here is the program.

/* Program for writing records into a file using Structures */

#include<stdio.h>
main()
{
FILE *fp;
char choice = y;
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 138

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
struct emp
{
char name[40];
int age;
float bs;
};
struct emp e;
fp = fopen(emp.dat, w);
if(fp = = NULL)
{
puts(Cannot open file);
exit();
}
while (choice = =y)
{
printf(Enter Name, age and Basic Salary);
scanf(%s%d%f, e.name, &e.age, &e.bs);
fprintf(fp, %s%d%f\n,e.name,e.age,e.bs);
printf(Do you want to add one more record (y/n));
fflush(stdin);
choice =getch();
}
fclose(fp);
}


/* Program to read records from file using Structures */

#include<stdio.h>
main()
{
FILE *fp;
struct emp
{
char name[40];
int age;
float bs;
};
struct emp e;
fp = fopen(emp.dat, r);
if(fp = = NULL)
{
puts(Cannot open file);
exit();
}
while (fscanf(fp,%s%d%f, e.name, &e.age, &e.bs)!=EOF)
{
printf(\n Employee Name : %s\n,e.name);
printf(\n Employee Age:%d,e.age);
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 139

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
printf(\nBasic Salary = %f,e.bs);
}
fclose(fp);
}

In the above programs the Structure elements are handled individually. Since
the above program is opened in text mode it would occupy more number of bytes. If
the number of fields in the Structure increases, writing Structures using fprintf(), or
reading them using fscanf() becomes complex. So overcome these disadvantages we
open the file in binary mode and also handle the structures collectively as a single one
by using fread() and fwrite() function.


/* Writing records into file in Binary Mode */

#include<stdio.h>
main()
{
FILE *fp;
char choice = y;
struct emp
{
char name[20];
int age;
float bs;
};
struct emp e;
fp = fopen(Employee.dat, wb);
if(fp = = NULL)
{
puts(Cannot open file);
exit();
}
while (choice = =y)
{
printf(Enter Name, age and Basic Salary);
scanf(%s%d%f, e.name, &e.age, &e.bs);
fwrite(&e,sizeof(e),1,fp);
printf(Do you want to add one more record (y/n));
fflush(stdin);
choice =getch();
}
fclose(fp);
}


/* Read the records from Binary File */

#include<stdio.h>
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 140

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
main()
{
FILE *fp;
struct emp
{
char name[20];
int age;
float bs;
};
struct emp e;
fp = fopen(Employee.dat, rb);
if(fp = = NULL)
{
puts(Cannot open file);
exit();
}
while (fread(&e,sizeof(e),1,fp)
{
printf(\n Employee Name : %s\n,e.name);
printf(\n Employee Age:%d,e.age);
printf(\nBasic Salary = %f,e.bs);
}
fclose(fp);
}

/* Program for copying one file to another file using command line arguments */

#include<stdio.h>
main(int argc, char *argv[])
{
FILE *fs, *ft;
Char ch;

if (argc!=3)
{
puts(In sufficient arguments);
exit();
}
fs = fopen(argv[1], r);
if (fs= =NULL)
{
puts(Cannot open source file);
exit();
}
ft = fopen(argv[2],w);
if (ft = =NULL)
{
puts(Cannot open target file);
fclose(fs);
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 141

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
exit();
}
while ((ch=fgetc(fs))!=EOF)
fputc(ch,ft);
fclose(fs);
fclose(ft);
}

If the above program is saved as filecopy.c and executed at command line as
filecopy first.txt second.txt
argv[1] will be replaced with first.txt
argv[2] will be replaced with second.txt
The advantages of the above program are
a) There is no need to recompile the program every time.
b) Source and target files can be passed from command prompt.
c) Once executable file is created we cannot after the original source file.


/* Program to add two numbers using command line arguments */

main(int argc, char *argv[])
{
int a,b,c;
a = atoi(argv[1);
b= atoi(argv[2]);
c = a+b;
printf(The sum of two numbers is:%d,c);
}

If program is saved as add.c then to execute
add 20 30

Note:- Since 20 and 30 are entered from Command line, they are treated as strings, so
convert them into numbers using atoi() function.


STANDARAD INPUT/OUTPUT :

In C a file is basically stream of bytes(more commonly referred as
stream),which can be interpreted by a c program.When a c program is started ,the
operating system is responsible for opening three file(streams).
When program execution begins, three files and their associated streams are
connected to the program automatically. They are

the standard input stream
the standard output stream
the standard error stream

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 142

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Standard input: It is connected to the keyboard & it enables a program to read data
from the keyboard.

Standard output: It is connected to the screen & it enables a program to write data
to the screen.
Standard error: It is connected to the screen & all error messages are output to
standard error.

Standard input and standarad output functions are handled through several library
functions such as scanf(),getchar(),gets(),printf(),etc.


ERROR HANDLING DURING I/O OPERATIONS:

It is possible that an error may occur during I/O operations on a file. Typical error
situations include the following:

Trying to read beyond the end-of-file mark
Device Overflow
Trying to use a file that has not been opened
Trying to perform an operation on a file, When the file is opened for another
type of operation.
Opening a file with an invalid filename.
Attempting to write to a write-protected file.


If we fail to check such a read and write errors a program may behave abnormally
when an error occurs an unchecked error may result in a premature termination of the
program or incorrect output.
We have two library functions FEOF and FERROR that can help us to detect I/O
errors in the files.
The FEOF function can be used to test for an End Of File condition. It takes a file
pointer as its only argument and returns a non zero integer value, if all of the data
from the specified file has been read, and returns zero otherwise. If fp is pointer to file
that has just been open for reading, then the statement

If (FEOF(fp))
Printf(End of data);

Wouls display the message End of data on reaching the end of file condition.

FERROR: The FERROR function reports the status of the file indicated. It also takes
a file pointer as its argument and returns a non zero integer if an error has been
detucted up to that point during process it returns zero otherwise.

Example:
If(FERROR(fp)!=0)
Printf( an error has occurred);
The above statement print the error message if the reading is not successful.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 143

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

If a file is open using FOPEN function, A file pointer is returned. If the file cannot be
opened for some reason then the function returns a null pointer. This facility can be
used to test whether a file has been opened or not.

Example:
If(fp==NULL)
Printf(File could not be opened);

FORMATTED INPUT/OUTPUT FUNCTIONS :

There are two formatting input/output functions that is scanf and printf.The
scanf function receives a text stream from the keyborad and converts in to data values
to be stored in variables.The printf function receives data values from the program
and converts them into text stream to be displayed on the monitor.
These two functions can be used only with the keyboard and monitor.The C
library defines two more general functions that is fscanf and fprintf that can be used
with any text stream.
Formatting Functions

















Stream pointer:
Stream pointer is the pointer to the streams that has been declared and
associated with atext file.

Ex:
FILE * spIn;

spIn=fopen(file name,r);

fscanf(spIn,format string,address list);

Terminal input/output

Scanf(control string,);
Printf(control string,);

General input/output

Fscanf(stream_pointer, control string,);
Fprintf(stream_pointer, control string,);


COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 144

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
While we normally read data from the terminal keyboard using scanf,we can
also use fscanf.When we use fscanf we must specify that the stream pointer is
stdin,for example

fscanf(spIn,format string,address list);


Ex:
FILE * spOut;

spOut=fopen(file name,w);

fprintf(spOut,format string,address list);

We can use fprintf to print to the terminal monitor by specifying the stream stdout, as
shown below

fprintf(spOut,format string,address list);

Format Contol Strings:

Input and output functions for text files use a format string to dexcribe how
data are to be formatted when read or written.The format control string consist of
three types of data ,which may be repeated: whitespace ,text characters and
conversion specification. That describes how the data are to be formatted as they are
read or written.


Whitespace :
A whitespace character in an input format string causes leading whitespace
characters in the input to be discarded.A whitespace character in an output format
string is copied to the output stream.

Text :
Any text character other than a white space in an input format string must
match exactly the next character of the input stream. If it does not match, a conflict
occurs that causes the opration to be terminated. The conflicting input character
remains in the input stream to be read by the next input operation on that stream.
Text characters in an output format string are copied to the output stream.
They are usually used to displat messages to the user or to label data being output.

Conversion specification:

The conversion specification consists of a percentage character(%), optional
formatting instructions and a conversion code. With one exception each conversion
specificartion must have a matching parameter in the parameter list that follows the
format string. The type in the conversion specification and the type of the parameter
must match.
Conversion specifications can have up to six elements ,they are
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 145

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

- Conversion specification token(%)
- Flag
- Minimum width
- Precision
- Size
- Conversion code

First and last element elements are compulsory and the remaining elements are
optional.

Conversion codes:

The conversion code specifies the type of data that are being formatted for input it
specifies the type of variable in to which the formatted data are stored. For output
specifies the type of data in the parameter associated with the specification.

INPUT FORMATTING:

The scanf and fscanf functions read text data and convert the data to the types
specified by a format string. Only difference between thejm is that scanf reads data
from the standard input unit(keyboard) and fscanf reads the input from file specified
by the first parameter. This file can be standard input (stdin).
The name scanf stands for scan formatted, the name fscanf stands for file scan
formatted. The functions have the following formats:
Scanf (format string,address list).
fscanf (sp,format string,address list).

Where sp is the address of a stream defined as type FILE*, format string is a
string containing formatting instructions and the address list specifies the addresses
where the data are to be stored after they have been formatted. A comma must
separate the format string from the variable list.

INPUT DATA FORMATTING:

The conversion operation processes input characters until any of the following occurs

End Of File is reached.
An inappropriate character is encountered
The number of characters read is equal to an explicitly specified maximum
field width.

INPUT CONVERSION SPECIFICATION:

FLAG:
There is only one flag for input formatting,The assignment suppression
flag(*).
The assignment suppression flag tells scanf that the next input field is to be read but
not stored. It is discarded.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 146

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

Example:
Scanf(%d%*c%f, &x,&y);

WIDTH:

The width specifies the maximum width of the input(in characters).This
allows us to break out a code that may be stored in the input without spaces.


SIZE:

A size specification is a modifier for the conversion code. Used in
combination with the conversion code,specifies the type of the associative variable.

CONVERSION CODES:

Integer(d): The decimal (d) format code accepts a value from the input stream and
formats it in to the specified variables. It reads only decimal digits and an optional
plus or minus sign is the first character of the value.

Integer(i): The integer format code (i) allows the user to create decimal ,octal or
hexadecimal numbers. Numbers starting with any digit other than zero are read and
stored as decimal values. Numbers starting with zero are interpretes as octal values
and are converted to decimal and stored. Hexadecimal numbers must be prefixed with
0x (or) 0X, The hexadecimal value is converted to decimal and stored.

Octal and hexadecimal(o,x): The octal (o) and hexadecimal (x) conversion codes
perform unsigned conversion. For octal only valid input digits are 07. For
Hexadecimal input valid digits are 09, af and AF.

Scientific notation (e,g,a): The C languages uses three real format codes for
scientific notation. In scientific notation the significand and exponent are specify
separately. The significant part is a floating point number that contains as many
significant digits as possible.

Count(n): To verify the number of input characters we use the n-conversion code.
The code requires a matching variable address in to which scanf places the count of
the characters input.

The Common Input Format Mistakes: Two common mistakes while formatting
input stream, They are

Invalid Address
Datatype conflict

Invalid address: The common mistake is to use a data value rather than an address for
the input parameter

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 147

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Data type conflict: It is conflict between the format stream and the input stream. It
occurs, For example when the format string calls for a numeric value and the input
stream contains alphabetic character then scanf operation aborts.

OUTPUT FORMATTING (PRINTF AND FPRINTF) :

Two print formatted functions display output in human readable form under
the control of a format string that is very similar to the format string in scanf.

Synatax: Printf(format string , value list);
Fprintf(sp,formatstring, value list);

One of the first difference is thatg the value list is optional .Where as you always need
a variable when you are reading,in many situations ,such as user prompts ,displays
strings without a value list.

Ex: printf(\n welcome to calculator\n);
Printf(\nThe answer is %6.2f\n,x);
Printf(thank you for using calculator);
The fprintf function works just like printf except that it specifies the file in which the
data will be displayed.

Print Conversion Specifications:

Printf family contains printf conversion specifications they are:
Flags
Sizes
Precision
Flags:
- Value is left justified (default is right justified). Overrides the 0 flag.
+ Forces the sign (+ or -) to always be shown. Default is to just show the - sign.
Overrides the space flag.
Width:
The width of the field is specified here with a decimal value. If the value is not large
enough to fill the width, then the rest of the field is padded with spaces (unless the 0
flag is specified). If the value overflows the width of the field, then the field is
expanded to fit the value. If a * is used in place of the width specifer, then the next
argument (which must be an int type) specifies the width of the field. Note: when
using the * with the width and/or precision specifier, the width argument comes first,
then the precision argument, then the value to be converted.
Precision:
The precision begins with a dot (.) to distinguish itself from the width specifier. The
precision can be given as a decimal value or as an asterisk (*). If a * is used, then the
next argument (which is an int type) specifies the precision. Note: when using the *
with the width and/or precision specifier, the width argument comes first, then the
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 148

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
precision argument, then the value to be converted. Precision does not affect the c
type.

/*Create a file containing customer records */

#include<stdio.h>
#include<string.h>
typedef struct {
int mm;
int dd;
int yy;
}date;

typedef struct{
char name[80];
char street[80];
char city[80];
int acc_no;
char acc_type; /* C =current, O =overdue D =delinquent */

float old_bal;
float new_bal;
float payment;
date lastpayment;
}record;
record read(record customer); /*function prototype */

FILE *fp;

main()
{

record cust;
char choice;

fp = fopen(custold,w);

printf(CUSTOMER BILLING SYSTEM \n\n);
printf(Enter today date (mm/dd/yyyy));

scanf(%d%d%d,&cust.lastpayment.mm,&cust.lastpayment.dd,
&cust.lastpayment.yy);
cust.new_bal=0;
cust.payment =0;
cust.acc_type=C;

do
{
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 149

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
printf(Enter Customer Name:);
scanf(%s,cust.name);
printf(Enter Street:);
scanf(%s,cust.street);
printf(Enter City:);
scanf(%s,cust.city);
printf(Enter Account Number:);
scanf(%d,&cust.acc_no);
printf(Enter Current Balance:);
scanf(%f,&cust.old_bal);

fwrite (&cust, sizeof(cust),1,fp);

printf(Do you want to continue (y/n));
fflush(stdin);
scanf(%c,&choice);
}while(choice = =y);
fclose(fp);
}

/* Updating the file containing customer records */

#include<stdio.h>
#include<string.h>
typedef struct {
int mm;
int dd;
int yy;
}date;

typedef struct{
char name[80];
char street[80];
char city[80];
int acc_no;
char acc_type; /* C =current, O =overdue D =delinquent */

float old_bal;
float new_bal;
float payment;
date lastpayment;
}record;
record update(record cust);

FILE *fp_old, *fp_new;
int month, day, year; /*Declaring Temporary Variables*/

main()
{
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 150

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
record cust;

fp_old = fopen(custold,r);
fp_new=fopen(custnew,w);
clrscr():
printf(CUSTOMER BILLING SYSTEM \n\n):
printf(Enter today date (mm/dd/yyyy));
scanf(%d%d%d, &month,&day,&year);

while(fread(&cust,sizeof(cust),1,fp_old))
{
cust = update(cust); /*Calling Update Function*/
fwrite(&cust,sizeof(record),1,fp_new);
fread(&cust,sizeof(record),1,fp_old);
}
fclose(fp_old);
fclose(fp_new);
}
record update (record cust)
{
printf(\n\n Name: %s,cust.name);
printf(Account Number: %d\n,cust.acc_no);
printf(Enter current payment);
scanf(%f,&cust.payment);

if(cust.payment>0)
{
cust.lastpayment.mm=month;
cust.lastpayment.dd = day;
cust.lastpayment.yy = year;
cust.acc_type = (cust.payment<0.1 *cust.old_bal) ? O : C;
}
else
cust.acc_type = (cust.old_bal>0) ? D : C;

cust.new_bal = cust.old_bal cust.payment;
printf(New balance: %7.2f,cust.new_bal);
printf( Account Status : );
switch(cust.acc_type)
{
case C : printf(Current \n);
break;

case O : printf(Overdue \n);
break;

case D : printf(Delinquent \n);
break;

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 151

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
default : printf(ERROR \n);
}
return(cust);
}


/* Menu driven program for adding, modifying, deleting and viewing records
with a file */

#include<stdio.h>
struct emp
{
int empno;
char ename[20];
float sal;
}e;

FILE *fp, *ft;
Long recsize;

main()
{
char choice;
int opt;

fp =fopen(employee.dat,rb+);
if(fp = =NULL)
{
fp = fopen(employee.dat,wb+);
if(fp = =NULL)
{
printf(Cannot Open File\n);
exit();
}
recsize = sizeof(e);
}
do
{
clrscr();
printf(1.Adding Records \n);
printf(2.Modifying Records \n);
printf(3.Deleting Records \n);
printf(4.Viewing Records \n);
printf(5.Exit \n);
printf(Enter yout option(1/2/3/4/5) \n);
scanf(%d,&opt);

switch(opt)
{
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 152

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
case 1 : addrecords();
break;
case 2 : modifyrecords();
break;
case 3 : deleterecords();
break;
case 4 : viewrecords();
break;
case 5 : fclose(fp);
exit();
}
printf(Do you want to continue (y/n) \n);
fflush(stdin);
scanf(%c,&choice);
}while(choice = = y);
}

addrecords()
{
char more = y;
fseek (fp,0,SEEK_END);
while(more = =y)
{
printf(Enter empno,ename and salary);
scanf(%d%s%f, &e.empno,e.ename,&e.sal);

fwrite(&e,recsize,1,fp);

printf(Do you want to add one more record(y/n));
fflush(stdin);
more =getch();
}
}
modifyrecords()
{
char more =y;
int temp_empno,t;
while (more = =y)
{
printf(Enter the empno of employee to modify\n);
fflush(stdin);
scanf(%d,temp_empno);
rewind(fp);
while(fread(&e,recsize,1,fp) = =1)
{
if(temp_empno = = e.empno)
{
printf(\nEnter new name and new salary);
scanf(%s%d,e.ename,e.sal);
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 153

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
fseek(fp,-recsize,SEEK_CUR);
fwrite(&e,recsize,1,fp);
}
}
printf(Do you want to modify one more record(y/n));
fflush(stdin);
more =getch();
}
}
deleterecords()
{
char more =y;
int temp_empno;
while (more = =y)
{
printf(Enter the empno of employee to delete\n);
scanf(%d,temp_empno);
ft = fopen(temp.dat,wb);

rewind(fp);
while(fread(&e,recsize(e),1,fp) )
{
if(e.empno!= temp_empno)
fwrite(&e,recsize(e),1,fp);
}
fclose(fp);
fclose(ft);

remove(employee.dat);
rename(temp.dat,employee.dat);
fp = fopen(employee.dat,rb+);


printf(Do you want to modify one more record(y/n));
fflush(stdin);
more =getch();
}
}
viewrecords()
{
rewind(fp);
while(fread(&e,recsize(e),1,fp) )
{
printf(Employee Number : %d\n,e.empno);
printf(Employee Name : %s\n,e.ename);
printf(Employee Salary : %f\n,e.sal);
}
}

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 154

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
































COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 155

VIDYA VIKAS INSTITUTE OF TECHNOLOGY




















UNIT - VII

SEARCHING:

Searching for items is one of the most critical activities in many applications.
Examples of few search activities are spell checking, searching for a name in list of
names, opening files etc. The efficiency of a search depends on three things.

1. The size and organization of the collection of data we are searching.
2. The search algorithm that is used.
3. The efficiency of the test used to determine if the search is successful.

We will describe two searching methods in this session.

a) Linear Search which starts searching from the beginning of the list and
checks each element until a match is found.

b) The second technique binary search which can only be used on a sorted
list. It successively divides the array into two parts, then discards the
part
that cannot contain the element we are searching for.

Searching involves following:

a) Search List: The search list is simply a common term for the collection of
elements that we are storing in. The elements in the list may or may not be
ordered (ascending or descending).
b) Target Element: The element that we are searching for. (sometimes referred
to as key element).
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 156

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

LINEAR SEARCH (SEQUENTIAL SEARCH):

Linear Search is the traditional method of searching. It is very simple but very
poor in performance at times.

We begin search by comparing the first element of the list with the target
element. If it matches, the search ends. Otherwise, we will move to next element and
compare. In this way, the target element is compared with all the elements until a
match occurs. If the match do not occur and there are no more elements to be
compared, we conclude that
target element is absent in the list.


For example consider the following list of elements.

5 9 7 8 11 2 6 4

Suppose we want to search for element 11(i.e. Target element = 11). We first
compare the target element with first element in list i.e. 5. Since both are not
matching we move on the next elements in the list and compare. Finally we will find
the match after 5 comparisons.

Function for linear search:

int LinearSearch(int a[], int n, int key)
{
int i = 0;
while(i<n-1)
{
if (a[i] == key)
return(i);
i++;
}
return (-1);
}

The function returns the position of the target element, if it exists in the search
list otherwise it returns a negative value (-1) to indicate unsuccessful search. The test i
< n-1 provides a check to see that the array list is not crossed. For large lists, the
performance of linear search degrades.

Table below lists performance for search list of N items.

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 157

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Case
Meaning Number of Iteration Time Complexity
Best
The item to be
searched is the first
item in the list
1 u(1)
Average
The item to be
searched is found
some where close to
middle of list
N/2 u(N)
Worst
The item to be
searched is the last
item in list, or it
does not exist at all
N u(N)

Note:- Linear Search requires no ordering of elements in the list.


BINARY SEARCH:

Binary Search is a vast improvement over the linear search but it cannot
always be used. For binary search to work, the items in the list must be in a sorted
order (either increasing (ascending) or decreasing (descending) order similar to the
way words in a dictionary are arranged.

The pre-requisite for Binary Search method is that the input elements list must
be in the sorted order. The method starts with looking at the middle of the list. If it
matches with the target element, then the search is complete Otherwise, the target
element may be in the upper half or lower half. The search progresses with the upper
half if the target element is greater than the middle element or with the lower half if
the target element is less than the middle. The process is continued until the target
element is found or the portion of the sub list to be searched is empty.

For example consider the ordered list of elements 2,5,8,9,11,15,17,23,43,65 to
search the element 17(key).

Initially low = 1, high = 10. The middle element position is calculated by
dividing the sum of lower bound and upper bound by 2 taking integer division. The
search process can be seen as below,


2 5 8 9 11 15 17 23 43 65
| | |
low mid high


2 5 8 9 11 15 17 23 43 65
| | |
low mid high

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 158

VIDYA VIKAS INSTITUTE OF TECHNOLOGY


2 5 8 9 11 15 17 23 43 65
| |
low high
mid


2 5 8 9 11 15 17 23 43 65
|
high
low
mid

Therefore the key element 17 is at 7
th
position.

The function for binary search can be written as

int BinarySearch(int a[], int n, int key)
{
int low, high, midpos;
low = 0; high = n-1;
while(low <= high)
{
midpos = (low+high)/2;
if (key = = a[midpos])
return(midpos);
else
if(key<a[midpos])
high = midpos 1;
else
low = midpos 1;
}
return(-1);
}

The function returns the position at which the item is found, otherwise 1 if the item
is not found.

RECURSIVE BINARY SEARCH:

A recursive binary search differs from the iterative version mainly in that it
requires the upper bound and lower bound indices to be passed as arguments.

Recursive Binary Search Function:

r_binarysearch( int a[], int key, int low, int high)
{
int mid;
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 159

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
if (low>high)
return (-1)
mid = (low +high)/2;
if ( key = = a[mid])
return(mid);
if (key < a[mid])
r_binarysearch( a, key,low, mid-1);
else
r_binarysearch( a, key, mid+1,high);
}

The recursive function determines whether the search key lies in lower or
upper half of the array, then it calls itself on appropriate half.


Each step of algorithm divides the list into two parts and the search continues
in one of them and other is discarded. The search requires at most k steps where 2
k
>n
which results in time complexity of k = log
2
n i.e., O(log n) for average and worst
cases.

SORTING TECHNIQUES:

Sorting:

The process of getting data elements into order is called Sorting.

We have different techniques in Sorting
1) Exchange Sort
2) Selection Sort
3) Insertion Sort
4) Quick Sort
5) Merge Sort
6) Tree Sort

1) EXCHANGE SORT:

Fundamental Mechanism in an exchange sort is to repeatedly make
comparisons, and if required, to change adjacent items. Bubble Sort is an example of
the exchange sort technique.

BUBBLE SORT PROCESS:

In this technique the first element in the list in tested with all the rest elements,
and whenever the first element is found smaller than the rest element (to sort in
descending order) then the swapping (exchanging) is done. This process will be
repeated until the elements in list gets in sorted order

Bubble Sort for Strings:

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 160

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
void bubble_sort(char *str; int length)
{
for(i=0; i<length; i++)
for(j=i+1; j<length;j++)
{
if (str[i]>str[j])
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
printf(Sorted String is %s\n,str);
}

Bubble Sort for Integers:

(For Ascending Order)

bubblesort(int a[], int n)
{
int pass, j, noexchange;
for(pass=0;pass<n-1;pass++)
{
noexchange=1;
for(j=0;j<n-pass-1;j++)
{
if(a[j]>a[j+1])
{
swap(a[j]>a[j+1]);
noexchange = 0;
}
}
if (noexchange);
return;
}
}


SELECTION SORT:

Suppose that items in a list are to be sorted in their correct sequence. Using
Selection Sort, the first item is compared with the remaining n-1 items, and whichever
of all is lowest, is put in the first position. Then the second item from the list is taken
and compared with the remaining (n-2) items, if an item with a value less than that of
the second item is found on the (n-2) items, it is swapped (Interchanged) with the
second item of the list and so on.

Algorithm for Selection Sort:
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 161

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

Procedure Selection_Sort(A,N)
For Index = 1 to N-1 do
begin
MinPostion Index
For j = Index+1 to N do
begin
if A[j] < A[MinPosition] then
MinPosition j
end
swap (A[Index], A[MinPosition])
end
Return


Function to perform Selection Sort:

void selection_sort(char *str, int len)
{
int i, j, k, swap;
char temp;
for(I=0;I<len;I++)
{
swap = 0;
k=I;
temp = str[I];
for (j = I+1; j<len; j++)
{
if( str[j] < temp)
{
k=j;
temp = str[j];
swap =1;
}
}
if (swap)
{
str[k] = str[i];
str[i] = temp;
}
}
}

Step by Step Iteration

I Present Sequence

I = 0 b d a c

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 162

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
I = 1 a d b c

I = 2 a b d c

I = 3 a b c d



INSERTION SORT:

Insertion sort is implemented by inserting a particular element at the
appropriate position. In this method, the first iteration starts with comparison of 1
st

element with the 0
th
element. In the second iteration 2
nd
element is compared with the
0
th
and 1
st
element. In general, in every iteration an element is compared with all
elements before it. During comparison if it is found that the element in question can
be inserted at a suitable position then space is created for it by shifting the other
elements one position to the right and inserting the element at the suitable position.
This procedure is repeated for all the elements in the array.

Suppose the sequence is:

25, 17, 31, 13, 2

Step by Step Iteration

I Present Sequence

I = 0 17 25 31 13 2

I = 1 17 25 31 13 2

I = 2 13 17 25 31 2

I = 3 2 13 17 25 31


Explanation:

a) In the first iteration the 1
st
element 17 is compared with the 0
th
element 25.
Since 17 is smaller than 25, 17 is inserted at 0
th
place. The 0
th
element 25 is
shifted one position to the right.
b) In the second iteration, the 2
nd
element 31 and 0
th
element 17 is compared.
Since, 31 is greater than 17, nothing is done. Then the 2
nd
element 31 is
compared with the 1
st
element 25.Again no action is taken as 25 is less than
31.
c) In the third iteration, the 3
rd
element 13 is compared with the 0
th
element
17.Since, 13 is smaller than 17, 13 is inserted at the 0
th
place in the array and
all the elements from 0
th
till 2
nd
position are shifted to right by one position.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 163

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
d) In the fourth iteration the 4
th
element 2 is compared with the 0
th
element 13.
Since, 2 is smaller than 13, the 4
th
element is inserted at the 0
th
place in the
array and all the elements from 0
th
till 3
rd
are shifted right by one position. As
a result, the array now becomes a sorted array.



The complexity of the insertion sort algorithm is shown below:

Algorithm Worst case Average case Best case

Insertion sort

O(n
2
)

O(n
2
)

n-1


QUICK SORT:

It is a fast sorting algorithm invented by C.A.R. Hoare. It approaches sorting
in a radically different way from the other sorting techniques. It attempts to partition
the data set into two sections, then sort each section separately adopting divideand
conquer strategy.

Given a list of n elements, which is to be sorted, quick sort identifies an item
(say k) in the list. It moves all the items in the list that have values less than k, to the
left of k, and all the items that have a value greater than k to the right of k. Thus, we
have two sub-lists, say list-1 and list-2 with in the main list, with k standing between
list-1 and list-2. We then identify new ks in the list-1 as well as list-2. Thus list-1
and list-2 each will be portioned further into two sub-lists, and on. This continues
until the entire list is exhausted.

Algorithm for Quick Sort:

/* A is an array of N elements to be sorted. LowBound and UpBound are lower and
upper bound indices of array. */

if(LowBound < UpBound) then
begin
i LowBound
j UpBound
pivot LowBound
while (i<j) do
begin
while((A[i]<=A[pivot]) and (i<UpBound)) do
i i+1
while(A[j]>A[pivot])do
jj-1
if(i<j) then
swap(A[i],A[j])
end
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 164

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
swap(A[pivot],A[j])
Call QuickSort(A,LowBound,*j-1)
Call QuickSort(A,j+1,UpBound)
end
Return

Quick Sort Function:

void qsort(int a[], int lb, int ub)
{
int i,j,pivot;
if(lb<ub)
{
i = lb;
j = ub;
pivot = lb;
while(i<j)
{
while((a[i]<=a[pivot] && (i<ub))
i++;
while (a[j]>a[pivot])
j--;
if(i<j)
swap(&a[i],&a[j]);
}
swap(a[pivot],&a[j]);
qsort(a,lb,a[j-1]);
qsort(a,j+1,ub);
}
}

swap(int *a, int *b)
{
int t;
t = *a;
*a = * b;
*b = t;
}


MERGE SORT:

Merging means combining two sorted lists into one sorted list. For this the
elements from both the sorted lists are compared. The smaller of both the elements is
then stored in the third array. The sorting is complete when all the elements from both
the lists are placed in the third list.

Two Lists before sorting:
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 165

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

a b

11 2 9 13 57 25 17 1 90 3

The two sorted lists are:

a b

2 9 11 13 57 1 3 17 25 90


Step by step iteration:

I Present Sequence (The third List)

I=0 1

I=1 1 2

I=2 1 2 3

I=3 1 2 3 9

I=4 1 2 3 9 11

I=5 1 2 3 9 11 13

I=6 1 2 3 9 11 13 17

I=7 1 2 3 9 11 13 17 25

I=8 1 2 3 9 11 13 17 25 57

I=9 1 2 3 9 11 13 17 25 57 90

Suppose arrays a and b contain 5 elements each. Then merge sort algorithm
works as follows:
a) The arrays a and b are sorted using any algorithm.
b) The 0
th
element from the first array, 2, is compared with the 0
th
element of
second array 1. Since 1 is smaller than 2, 1 is placed in the third array.
c) Now the 0
th
element from the first array, 2, is compared with 1
st
element from
the second array, 3. Since 2 is smaller than 3, 2 is placed in the third array.
d) Now the 1
st
element from the first array, 9, is compared with the 1
st
element
from the second array, 3. Since 3 is smaller than 9, 3 is placed in the third
array.
e) Now the 1
st
element from the first array, 9, is compared with the 2nd element
from the second array, 17. Since 9 is smaller than 17, 9 is placed in the third
array.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 166

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
f) The same procedure is repeated till end of the array is reached. Now, the
remaining elements from the other array are placed directly into the third list
as they are already in sorted order.

The complexity of the merge sort algorithm is shown below:

Algorithm Worst case Average case Best case

Merge sort

O(n log n)

O(n log n)

O(n log n)


The following program implements the merge sort algorithm:

#include<stdio.h>
#include<conio.h>
void main()
{
int a[5]={ 11, 2, 9, 13, 57 };
int b[5]={ 25, 17, 1, 90, 3 };
int c[10];
int i,j,k,temp;

clrscr();

printf(Merge sort.\n);

printf(\nFirst array:\n);
for(i=0;i<=4;i++)
printf(%d\t,a[i]);

printf(\nSecond array:\n);
for(i=0;i<=4;i++)
printf(%d\t,b[i]);

for(i=0;i<=3;i++)
{
for(j=i+1;j<=4;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
if(b[i]>b[j])
{
temp=b[i];
b[i]=b[j];
b[j]=temp;
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 167

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
}
}
}

for(i=j=k=0;i<=9;)
{
if(a[j]<=b[k])
c[i++)=a[j++];
else
c[i++]=b[k++];

if(j==5 || k==5)
break;
}

for(;j<=4;)
c[i++]=a[j++];

for(;k<=4;)
c[i++]=b[k++];

printf(\nArray after sorting:\n);
for(i=0;i<=9;i++)
printf(%d\t,c[i]);

getch();
}

HEAP SORT:

It is a sorting algorithm which was originally described by Floyed. It is a
completely binary tree with the property that a parent is always greater than or equal
to either of its children (if they exist).

Steps Followed:
a) Start with just one element. One element will always satisfy heap
property.
b) Insert next elements and make this heap.
c) Repeat step b, until all elements are included in the heap.
Sorting:

a) Exchange the root and last element in the heap.
b) Make this heap again, but this time do not include the last node.
c) Repeat steps a and b until there is no element left.

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 168

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Algorithms:

Building Heap:

Procedure BuildHeap(A,N)
For j = 2 to N do
begin
key A[j]
i trunc(j/2)
while (i>0) and (A[i]<key) do
begin
A[j]A[i]
ji
itrunc(j/2)
end
A[i]key
end
return
Recreate the Heap:

Procedure ReHeap(A, k)
Parent1
Child2
Keya[Parent]
HeapFalse
while(Child<=k) and (not Heap) do
begin
if(Child < k) then
if A[Child + 1 ] > A[Child] then
Child Child +1
If A[Child]>Key then
begin
A[Parent]A[Child]
ParentChild
Child Parent*2
end
else
HeapTrue
end
A[Parent]Key
Return

Heap Sort Algorithm:

Procedure HeapSort(A,N)
Call Build Heap(A,N)
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 169

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
For Pos = N to 2 in Steps of 1 do
begin
swap (A[1],A[Pos])
Call ReHeap (A,Pos-1)
end
Return
















UNIT - VIII
DATA STRUCTURES

Data structure is often confused with data types. Data type is a collection of
finite set of permitted values and a set of operations on these values, where as, data
structure is a study about the organizing the related data to enable us to work
efficiently with data, exploring the relationships with in the data.
Data structure is a study of different methods of organizing the data and
possible operations in these structures.

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 170

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
ABSTRACT DATA TYPES

In computing, an abstract data type or abstract data structure is a
mathematical model for a certain class of data structures that have similar behavior; or
for certain data types of one or more programming languages that have similar
semantics. An abstract data type is defined indirectly, only by the operations that may
be performed on it and by mathematical constraints on the effects (and possibly cost)
of those operations.
This approach doesn't always work on large programs in the real world, because these
programs evolve as a result of new requirements or constraints. A modification to a
program commonly requires a change in one or more of its data structures. For
instance, a new field might be added to a personnel record to keep track of more
information about each individual; an array might be replaced by a linked structure to
improve the program's efficiency; or a bit field might be changed in the process of
moving the program to another computer. You don't want such a change to require
rewriting every procedure that uses the changed structure. Thus, it is useful to
separate the use of a data structure from the details of its implementation. This is the
principle underlying the use of abstract data types.
Here are some examples.
- stack: operations are "push an item onto the stack", "pop an item from
the stack", "ask if the stack is empty"; implementation may be as array
or linked list or whatever.
- queue: operations are "add to the end of the queue", "delete from the
beginning of the queue", "ask if the queue is empty"; implementation
may be as array or linked list or heap.
- search structure: operations are "insert an item", "ask if an item is in
the structure", and "delete an item"; implementation may be as array,
linked list, tree, hash table, ...
There are two views of an abstract data type in a procedural language like C. One is
the view that the rest of the program needs to see: the names of the routines for
operations on the data structure, and of the instances of that data type. The other is the
view of how the data type and its operations are implemented. C makes it relatively
simple to hide the implementation view from the rest of the program.


STACKS & QUEUES

Stacks and Queues are very useful in numerous applications. For eg. Stacks
are used in computers in parsing an expression by recursion; in memory management
in operating system; etc. Queues find their use in CPU scheduling in printer spooling,
in message queuing in computer network etc.

STACKS:
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 171

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

Stack is an ordered collection of data in which data is inserted and deleted at
one end (same end). In stack the most recent elements are inserted first. For eg. plates
are pushed on to the top and popped off the top. Such a processing strategy is referred
to as Last-in-First-out or LIFO. A Stack is a data structure which operates on a LIFO
basis, it is used to provide temporary storage space for values. Stack is most
commonly used as a place to store local variables, parameters and return addresses.
When a function is called the use of stack is critical where recursive functions, that is
function that call themselves are defined.
Stack uses a single pointer top to keep track of the information in the stack.

Basic operation is a stack are.
1. Insert (push) an item onto stack.
2. Remove (pop) an item from the stack.

A stack pointer keep track of the current position on the stack. When an element is
placed on the stack, it is said to be pushed on the stack when an object is removed
from the stack, it is said to be popped from the stack. Stack Overflow occurs when
one tries to push more information on a stack, and Underflow occurs when we try to
pop an item off a stack which is empty.

REPRESENTATION OF STACK:

Two standard methods of representing a stack are in terms of an array and a
pointer linked list which is a away of representation using pointer.
The figure below illustrates an array implementation of a stack of 5 elements
B, A, M, K, S.



The Stack pointer is pointing to the top of the stack (called the top of the
stalk). The size of the array is fixed at the time of its declaration itself. But, as the
definition shows, stacks are dynamic data structures. They can grow and shrink during
the operation. However, stack can be an implemented using arrays by specifying a
maximum size. We require two things to represent stacks. First one is array to hold
the item and second an integer variable to hold the index of the top element
conveniently in C, we can declare stack as a structure to represent these two

#define max 50
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 172

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
struct stack
{
int top:
I int items [max]:
};

Now the stack s can be declared as struct stack S;
Note that the type of array elements in the above declaration is integer, but
actually it can be of any other type. Since array subscripts starts from 0, the 50 stack
elements in the above example reside in the location S.item[0] through S.items[49].
The top element can be accessed as S.item[top].

Basic Operations on a Stack:


Push:

Add an item to a stack moving the stack pointer to accommodate a new item.
Push always places the element on the top of the stack
.
Pop:

Removes the most recently pushed item from the stack, moving the stack
pointer top. Pop always removes top most element from stack.

Since a stack can contain only a finite number of elements, an error called a
stack overflow occurs when the stack is full and a push operation is performed.
Similarly, an error called a stack underflow occurs when the stack is empty and a pop
operation is performed.
These two conditions need to be checked before doing the respective
operations.

Pushing Items on to the Stack:

Assume that the array element begins at 1 and the maximum elements of the
stack are MAX. The stack pointer, say top, is considered to be pointing to the top
elements of the stack. A push operation thus involves adjusting the stack pointer (top)
to point to next tree slot and then copying data into that slot of the stack. Initially top
is initialized to zero.

ALGORITHM: push an element onto a stack

Procedure push(s, MAX, Top, ITEM)
/* s is array with size MAX represents the stack. Top is a pointer to the top element of
stack and ITEM is the item to be inserted into the stack*/
1. if top>= MAX the then
print stack overflow
return
2. top top +1
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 173

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
3. s[top] ITEM
4. return

In the second step of algorithm the stack pointer is adjusted to point to the next
free location in the stack, i.e. by incrementing the pointer top. The new element,
ITEM, is inserted into the top of the stack in step 3.
Removing items from the Stack:

To remove an item, first extract the data from the top position in the stack and
then decrement (subtract 1 from) the Stack pointer, top.

ALGORITHM: pop an element from stack

Function pop (s, top)
1. if top =0 then
print stack underflow
return.
2. K s[top]
3. top top1
4. return (k)

INFIX, PREFIX, POSTFIX NOTATIONS FOR EXPRESSIONS:

In general, simple arithmetic expression can be represented in three ways :
infix, prefix and postfix.
Consider the expression A+B.
Here A and B are operands and + is a binary operator. An operator is a binary
operator if it is associated with two operands.
The 3 notations can be shown as
A+B infix
+AB prefix
AB+ postfix (or suffix or reverse polish)

In infix notation the operator symbol is between the two operands. In prefix,
the operator precedes both operands. Here the prefixes pre- and post- indicate the
relative position of the operator with respect to its own operands.

Consider the following two infix expressions:
A+(B*C) and (A+B)*C
We will see how to convert the expression into other two notations
(Brackets { } are used to indicate the partial conversion)

Infix to prefix:

Original expression Intermediate expression Expression after conversion
A +(B*C) A + {*B C} +A*BC
(A+B)*C {+AB}*C *+ ABC

Prefix to postfix:
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 174

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

Original expression Intermediate expression Expression after conversion
A + (B*C) A + {BC*} ABC * +
(A+B)* {AB+}*C AB + C*


We represent the exponential symbol as.
.
. If parenthesis are not used then we
can evaluate considering the operationprecedence rules.
The infix operator precedence is as follows:
1. Parenthesis ()
2. Exponentiation
.
(Right to left)
3. Multiplication *, division / (left to Right)
4. Addition +, Subtraction (left to Right)

Some example expressions in three notations.

Infix Prefix Post fix
(A+B)*C/D * +AB/CD AB+CD/*
A + (B*C)/D + /A *B C D ABC*D/+
C /D*E * /CDE CD /E*
A+B*C +(D*E+F)*G + +A*BC*+*DEFG ABC* + DE*F+G*+

Observe the parenthesis are never required to evaluate any expression represented
on prefix or postfix notations. This is because the order in which the operations are to
be performed is specified by the positions of operands and operators in the expression.
So, the evaluation of postfix (or prefix) expression are very easy. In computers,
usually the expressions written in infix notations are evaluated by first converting into
its postfix expressions and then evaluate the postfix expression. Stacks are useful for
the conversions and evaluations steps.

CONVERSION OF EXPRESSION FROM INFIX TO POSTFIX:

ALGORITHM: Conversion of Infix Expression to Postfix

1. Push to the end of X, where X is an arithmetic expression.
2. Check expression from left to right and follow the steps 3 to 6 for every element of
X until the stack is vacant.
3. In case an operand is found, add it to R, where R is the equivalent postfix
expression.
4. In case left ( paranthesis is found push it onto the stack.
5. In case an operator is found, follow the following steps
a) Continually pop from the stack and add each operator to R at the top of the
stack. The pushed item should have the same or higher precedence than the
former operator encountered.
b) Append operator (recently encountered) onto the stack.
6. In case ) right paranthesis is found, then follow the following steps.
a) Continually pop from the stack and append every operator to R until left
paranthesis is found.
b) Eliminate the left paranthesis.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 175

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

EVALUATION OF POSTFIX EXPRESSION:

Evaluation of postfix(i.e., Reverse polish) expression. An algebraic expression in
postfix notation is evaluated as follows
The expression is scanned from left to right one at a time
If a number is encountered, it is pushed onto the stack
If an operator is encountered, it is applied to the top two operands on the stack.
After removing the operands used, the result is pushed on to the stacks.(Note
that the operator is not pushed onto the stack)

*The above steps are repeated until the end of expression is reached. Now, the top
element (of course, stack contains only one element at this stage) of a stack is popped
which is the result of the expressions.

RECURSION:

Many examples of the use of recursion may be found. This technique is useful
for the definition of mathematical functions and for the definition of data structures;
one of the simplest examples of a recursive definition is that for the factorial function.
Factorial (n) = 1 if n=0
= n* Factorial (n-1) otherwise

QUEUES:

A queue is an ordered collection of elements, where the elements can be
inserted at one end and deleted from another end. It works on the principle called
FirstInFirstOut (FIFO).
The information we retrieve from a queue comes in the same order that it was
placed on the queue. The examples of queues are checkout line at supermarket cash
register, line of cars waiting to proceed in some fixed direction at an intersection of
streets. The queue can be implemented using arrays and linked lists.

OPERATIONS ON QUEUES:

Insertion: The operation of adding new items on the queue occurs only at one
end of the queue called the rear end.

Deletion: The operation of removing items of the queue occurs at the other end
called the front end.

The following is an algorithm for inserting an element into the queue.

The variable FRONT holds the index of the front item and REAR variable
holds the index of the last item. Array elements begin at 1 and the maximum elements
of the Queue is MAX. Q is the Queue. ITEM is the element to be inserted.

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 176

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
ALGORITHM: Inserting an element into Queue

Queue_insert(ITEM)
If REAR > = MAX then write Queue Overflow
Return
REAR REAR +1
Q[REAR] ITEM
IF FRONT ==0 THEN
FRONT 1
Return

The following is the algorithm for detecting an element from the queue.

ALGORITHM: Deleting an elements from the Queue

Queue_delete( )
If FRONT =0 then
Write(Queue under flow).
Return
K Q[FRONT]
If FRONT = REAR then
Begin
FRONT 0
REAR 0
End
Else
FRONT FRONT +1
Return K

CIRCULAR QUEUE:

When the items from a queue get deleted, the space for that item is never used.
Those queue positions continue to be empty. This can be solved by circular queue.
In a circular queue, the items are arranged in the form of a circle. The circular
queue does not have a beginning or end.

DE-QUEUE:

It is called as double ended queue. In dequeue the elements can be inserted
and deleted from both the ends of a queue.


PRIORITY QUEUE:

This queue will not operate strictly on FCFS (first come first serve) bases, but
on some complex priority scheme.
A priority queue is a queue that contains items that have some predefined
ordering. Unlike the usual removal of the first item, when an item is removed from a
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 177

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
priority queue, some priority is associated with that, this priority determines the order
in which it exits the queue.

INTRODUCTION TO LISTS:

Arrays can be used to represent the simple data in which it is sequential. These
representations had the property that successive nodes of the data object were stored a
fixed distance apart.
If the element a
ij
of a table was stored at location L
ij
then a
ij+1
was at the
location L
ij+c
for some constant c.
If the i
th
node in a queue was at a location L
i
, then i+1
th
node was at location
L
i
+c mod n for circular representation.
If the top element of a stack was at location L
i
, then the element beneath it was
at L
i
c etc.
But when a sequential mapping is used for ordered lists, insertions and
deletions of arbitrary elements becomes expensive.
To make these operations easier to handle, we use linked representations.
Unlike a sequential representation where successive items of a list are located a fixed
distance apart, in a linked representation these items may be placed anywhere in
memory. That means, in a sequential representation the order of elements is the same
as in the ordered lists, while in the linked representation these 2 sequences need not be
the same. To access elements in the list in the correct order, with each element we
store the addresses or location of the next element in that list. So in linked
representation data item and pointer to the next element is grouped into a single field
that is called node.
Node, is a collection of data, and links.

Difference between sequential and linked representation:

SEQUENTIAL
REPRESENTATION`
LINKED REPRESENTATION
List Size is fixed List Size is not fixed
Elements are stored in
contiguous locations in memory.
Elements are not stored contiguously, but
anywhere in the memory.
Each element contains only
information.
Each element contains data and pointer to
next element.
Insertions and deletions are
difficult to perform.
Insertions and deletions are easy to perform.

Wastage of memory, if unused. No wastage of memory.
No extra memory required for
the elements.
Extra memory for pointer field.




SINGLE LINKED LIST:

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 178

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
Single Linked List is a collection of nodes. Each node contains 2 fields: I)
info where the information is stored and ii) link which points to the next node in the
list.

The node is like this:



Node
Info (or) data Link (or) next

The operations that can be performed on single linked lists includes: insertion,
deletion and traversing the list.

Inserting a node in a single linked list:

Insertion can be done in 3 ways:
1.Inserting an element in the beginning of the list.
2.Inserting in the middle and
3.Inserting at end.

The algorithm for inserting an element in the beginning of a list:

Procedure insertbeg(x, first)
/* x is an element first is the Pointer to the first element in a SLL */

begin
if avail = NULL then
Write( Availability Stack underflow)
return (first)
else
new avail;
avail link(avail)
info(new) x
link(new) first
return (new);
end.

In the algorithm, first, the memory for a new node is available or not is
checked out. Here avail is a pointer to the available memory.

If it is NULL then there is no memory. Otherwise a new node is created from
available memory and it is stored in new. The new contains the address of the new
node and avail moves forward to point to next available memory location. In the info
field of new, x is stored and the link field of new points to the first element address of
the list. Now, new becomes the pointer to the whole list.
This can be shown as:

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 179

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

(a)


(b)

First is having value of 100, means it is Pointing the 100
th
memory location.
The node at 100
th
location is having info as 10 and containing the address 200 of the
next node. The second node at 200
th
location, contains 20 and address 300 of the
next node. At,300
th
memory location, the node contains info as 30 and its link field is
NULL. That means it is no more having any nodes. That is, the list is having 3 nodes
with a starting address of 100.

Now, we created another node new that is having the address of 50 and its info
is 40 and its link field is NULL.

After the call to insertbeg( ) function the list will look like.



The insertbeg( ) function, inserts a node by storing the address of the first node
of list in the link field of new and making the new address as the pointer to the list.

The algorithm for inserting an element at the end of the list:

Procedure insertend(x, first)
begin
if avail = null then /* Checking for memory availability */
write ( Availability Stack underflow);
return(first);
else /* Obtaining the next free node */
new avail; /* Removing free node from available memory */
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 180

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
avail link(avail)
info(new) x /* Initializing the fields of new node */
link(new) NULL
if first = NULL then /* Is the list empty? */
return(new);
Save first /* Searching the last node */
Repeat while link (Save) = NULL
Save link(Save) /* Setting the link field of last node to new */
Link (Save) new
return (first)
end;

The Pictorial Representation:


(a)



(b)

(c)


COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 181

VIDYA VIKAS INSTITUTE OF TECHNOLOGY


(d)

first (100) address is stored in Save to go through the end of the list, after reaching to
the last node, set the address of new node in the link field of last node.

Inserting in the middle:

In this process, the address of first is stored in Save to go to the particular node
at which the insertion is to be done. After reaching the particular node, set the link to
point to new node, and set the link of new node to connect the remaining nodes.

ALGORITHM: The algorithm for inserting an element in the middle of a list:

Procedure insertmid(x, first)
begin
if avail = NULL then
write ( Availability Stack Underflow);
return (first)
else /* Obtain the address of next free node */
new avail
avail link(avail) /* Removing free node */
info(new) x /* Copying Information into new node */
if first = NULL then /* Checking whether the list is empty */
link(new) NULL /* list is empty*/
return(new) /* if the new data precedes all other in the list */
if info(new) s info(first) then
link(new) first
return(new) /* initialise temporary Pointer */
Save first
Repeat while link(Save) = NULL and
Info(link(Save)) s info(new)
Save link(Save) /* Search for predecessor of new data */
link(new) link(Save) /* Setting the links of new and its
Predecessor*/
link(Save) new
return(first)
end



COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 182

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

(a)



(b)



(c)




(d)

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 183

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

(e)

Deleting a node in a single linked list:

Deletion can be done in 3 ways:
1. Deleting an element in the beginning of the list.
2. Deleting in the middle and
3. Deleting at the end.

The algorithms for deleting an element in the list:

Procedure:

If the linked list is empty then write underflow and return
Repeat Step 3 while the end of the list has not been reached and the node has
not been found.
Obtain the next node in the list and record its predecessor node.
If the end of the list has been reached then write node not found and return.
delete the node from the list.
Return the node to the availability area.

Algorithm:

Procedure deletelement(x, first)
begin
if first = NULL then /* Checking whether the list is empty */
write( Underflow);
return
temp first /* Initializing search for x */
while((temp = x ) and
(link(temp) = NULL))
begin
pred temp
temp link(temp)
end
if temp = x then /* if the node not found */
write(node not found)
return
if (x = first) then / is x first node */
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 184

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
first link(first) /* delete the node at x */
else link(pred) link(x)
link(x) avail /* Return node to availability area */
avail x
return:
end.


In the algorithm, it first checks whether the list is empty, if it is empty it prints
underflow message. Otherwise, it initializes a temporary pointer to first. Until the
Predecessor of x node found, the temporary pointer is moved forward. If it reaches the
end of the list, without finding the node of address x, it flashes an error message,
stating node not found. If x is the first address, then first node is deleted and now
first points to second node. Otherwise it sets the links so that it deletes the node of
address x.

The original list is:


1. If x = 100 (First node)


(a)


(b)
The node which is 100
th
memory address will be added to free space

(ii) if x = 200

COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 185

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

(a)

(b)


(c)

(iii) if x = 300 (Last node)


(a)



COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 186

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
(b)

Traversing the List:

This includes, visiting the node and printing the data of that node one at a time and
moving forward until it reaches end of the list. (i.e., link becomes NULL)

Procedure(first)
begin
for (temp = first; temp!= NULL; temp = temp link)
write (temp info)
end.

APPLICATIONS LINKED LISTS:

The main Applications of Linked Lists are
It means in addition/subtraction /multipication.. of two polynimials.
Eg:p1=2x^2+3x+7 and p2=3x^3+5x+2
p1+p2=3x^3+2x^2+8x+9
* In Dynamic Memory Management
In allocation and releasing memory at runtime.
*In Symbol Tables
in Balancing paranthesis
* Representing Sparse Matrix








COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 187

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

























COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 188

VIDYA VIKAS INSTITUTE OF TECHNOLOGY












MULTIPLE CHOICE QUESTIONS
















COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 189

VIDYA VIKAS INSTITUTE OF TECHNOLOGY










































COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 190

VIDYA VIKAS INSTITUTE OF TECHNOLOGY




UNIT-I
1. Pseudo code is
(a) language independent code (b) refined version of program
(c) code developed using the syntax of a specific language (d) outcome of
compilation process
2. The process of repeating a group of statements in an algorithm is known as
(a) sequence (b) iteration (c) flow (d) selection
3. The process of removing a bug is known as
(a) running (b) executing (c) debugging (d) compilation
4. Pictorial representation of an algorithms is known as
(a) Flowchart (b) Diagram (c) Graphchart (d) picture
5. What symbol is used to represent the connector
(a) parellogram (b) rectangle with rounded end (c) circle (d)
rectangle
6. What symbol is used to represent input/output operations in a flow chart.
(a) Rectangles (b) Parellograms (c) circles (d) Rectangle with
rounded end
7. Which of the following is used to perform computations on the entered data?
(a) Memory (b) Processor (c) input devices (d) Output devices
8.which of the following is not an input device?
(a) plotter (b) Scanner (c) Keyboard (d) Mouse
9. which of the following is not an output device?
(a) plotter (b) Scanner (c) printer (d) Speaker
10. which of the following is not a translator program?
(a) Linker (b) assembler (c) Compiler (d) Interpreter
11. which of the following is used as a primary memory of the computer?
(a) Magnetic storage device (b) RAM (c) Optical storage device
(d) magneto-optical storage device
12. which of the following is known as the languange of the computer?
(a) Programming languange (b) High level languange
(c) Machine languange (d) Assembly languange
13. which type of operating system allows more than one program to run at the same
time in a computer system?
(a) Multi-threading operating system (b) iteractive operating system
(c) Multi-user operating system (d) Multi-tasking operating system
14. which of the following is used as a secondary memory of the computer?
(a) Magnetic storage device (b) RAM (c) Cache memory (d) ROM
15. which of the following converts assembly languange into machine languange?
(a) Interpreter (b) Computer (c) Algorithm (d) Assembler
16. the step-by-step description of a process is called as
(a) Algorithm (b) Flowchart (c) program (d) Pseudocode
16. what symbol is used to represent the start/stop?
(a) circle (b) rectangle with rounded end (c) parallelogram (d)
rectangle
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 191

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
17. the symbol for decision making statement is
(a) diamond box (b) circle (c) rectangle (d)
parallelogram



UNIT-II
1. What type of errors are checked during compilation
(a) logical errors (b) divide by zero error (c) run - time errors (d)
syntax errors
2. The purpose of main function is
(a) to stop program execution (b) to stop algorithm (c) to start algorithm (d) to start
program execution
3. What is the valid identifier in the following
(a) 1fdasgf (b) @hgd12 (c) fahs%* (d) q1234
4. What is range of char data value?
(a) -64 to 64 (b) -128 to 127 (c) 0 to 255 (d) -127 to
128
5. The minimum number of temporary variable needed to swap the contents of two
variable is
(a) 3 (b) 1 (c) 0 (d) 2
6. What is output of following program ?
main( )
{
int x;
x= 4 + 2 % 8;
printf(%d,x);
}
(a) 6 (b) 4.25 (c) 4 (d) -6
7. When && operator is used with two conditions, conditions need to be satisfied for
the expression to
be true.
(a) neither (b) only first (c) any one (d) both
8. Bitwise operators cannot be performed on
(a) float (b) long int (c) int (d) char
9. In the expression b=6.6/a+(2*a+(3*c)/a*d)/(2/n); which operation will be
performed first?
(a) 2*a (b) 2/n (c) 3*c (d) 6.6/a
10. What is the output of printf(%d,printf(tim));
(a) garbage (b) results in a syntax error
(c) printf tim and terminates abruptly (d) tim3
11. What is output of the following program?
main( )
{int x=15,y;
y=(x >5)? 3 : 4;
printf(%d,y);
}
(a) 2 (b) 4 (c) 3 (d) 1
12. Identify the loop construct:
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 192

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
(a) if-else (b) goto (c) while (d) switch-
case
13. Which of the following is a correct way of defining a symbolic constant pie in C
(a) # define pie = 22/7 (b) #define pie 22/7
(c) #define pie= 3.142 (d) # Define pie 22/7
14. The function getchar( ) is used to read
(a) a boolean value (b) a character (c) a string (d) a word
15. Which of the following is a valid numeric constant
(a) 15 750 (b) 65432 (c) $1000 (d) 20,000
16. Which of the following is a scalar data type used in C
(a) double (b) union (c) structure (d) array
17. Pick the operators that associates from right to left
(a) + (b) % (c) = (d) -
18. The operator % yields
(a) Fractional part (b) remainder after integer division
(c) quotient value (d) Percentage value
19. In an expression involving ||
||
operator the evaluation
(a) will be stopped if one of its components evaluates to true (b) takes place
from left to right
(c) takes place from right to left (d) will be stopped if one of its
components evaluates to false
20. If a=15 then b=a <<2 will results
(a) b=3 (b) b=30 (c) b=7 (d) b=60
21. What is the output of the following program
main( )
{ int a=5, i=1; while( i ++ < a) { printf(%d,a); }
(a) 5,4,3,2,1 (b) 5 5 5 5 5 (c) 4,3,2,1 (d) 1 1 1 1 1
22. switch(ch)
{case a: printf(a);
case b: printf(b);
default: printf(error);
} if ch is assigned to the character a then the output will be
(a) a b (b) a b error (c) a (d) error
23. What would be the final value of x after execution of the following program?
# include (stdio.h)
void main()
{
int x = 1;
do while (x<=10)
{
x++;
} while (x< = 5);
printf (\n x = %d, x);
}
(a) x = 6 (b) x = 2 (c) 10 (d)
x = 11
24. The storage area for register variables
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 193

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
(a) memory (b) processor registers (c) virtual memory (d) cache
25. The ANSI C standard recognizes maximum length of a variable up to
(a) 8 characters (b) unlimited characters (c) 31 characters (d)
15 characters
26. Which of the following is an incorrect variable name.
(a) else (b) name (c) string (d) age
27. What is the size of long double variable
(a) 10 bytes (b) 8 bytes (c) 4 bytes (d) 16 bytes
28. Variables are initialized in C, using
(a) : = (b) > (c) = (d) = =
29. If a is float variable, a=5/2 will return a value
(a) 2.5 (b) 2 (c) 2.0 (d) 3
30. int a=13,b=7,c;
c=a&b what is the value of c
(a) 0000 0000 0000 0101 (b) 0000 0000 0000 0100
(c) 0000 0000 0000 0110 (d) 0000 0000 0001 0101
31. In the following, which is bitwise operator?
(a) > (b) * (c) | (d) <
32. If y is of integer type variable then the two expressions.
3*(y-8)/9 and (y-8)/9*3 yield the same value if
(a) y-8 is an integer multiple of 3 (b) y is an odd number
(c) y is an even number (d) y-8 is an integer multiple of
9
33. What is output of the following program?
main()
{int a;
float b;
a=1/2;
b=1.0/2.0;
printf( a=%d b=%f,a,b);
}
(a) a=0.0 b=0. 5 (b) a=0 b=0. 5 (c) a=0.0 b= 5 (d) a=0.5
b=0. 5
34. In switch (expression) statement, the expression should evaluate to
(a) an integer (b) a void (c) a float (d) a character
35. The minimum number of times the for loop is executed is
(a) 0 (b) cannot be predicted (c) 1 (d) 2
36. Which of the following cannot be used as an identifier.
(a) alphabet followed by digit (b) alphabet (c) Keywords (d) Library
function name
37. Which of the following statements is wrong
(a) con = T * A ; (b) This = T * 20 ; (c) 3+a=b; (d) mes = 123.56
38. main( )
{ int a=5; float b=10,c;
c=b%a;
printf(%f,c);
}output is
(a) gives an error (b) 2.0 (c) 0.00 (d)
0.000000
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 194

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
39. int x=1,y=5;
x=++x + y;
what is the value of x
(a) 8 (b) 6 (c) 5 (d) 7
40. Consider the segment
If(1) printf(yes);
else printf(no);
what will be the output
(a) no (b) Unpredictable (c) yes (d) Error
41. Which of the following statements is false
(a) The initialization and increment parts of a for statement can be empty
(b) The body of do-while statement can be empty
(c) The expression in the condition part of a for statement can be empty
(d) The initialization part of a for statement cannot have more than one
initialization
42. What is the control string for representing string
(a) %c (b) %s (c) %f (d) %d
43. Every executable C program must contain a
(a) printf function (b) scanf, printf and main functions (c) main function (d)
scanf function
44. The individual units of a C program is known as
(a) records (b) tokens (c) units (d)
program
45. How many variables of the same type can be initialized at a time with the same
value
(a) Three (b) One (c) Two (d) any
number of variables
46. Integer division results in
(a) rounding (b) underflow (c) overflow (d) truncation
47. The operator with lowest priority in the list && , + , | | , < is
(a) + (b) | | (c) && (d) <
48. Which of the following shows the correct hierarchy of arithmetic operations in C
(a) ( ), / or *, - or + (b) ( ), &&, *,/,+,- (c) ( ), &&, / , *, +, - (d) ( ),&&,*or / +
or -;
49. The statement printf(%d,7);
(a) prints 0 (b) runtime error (c) prints the value 7 (d) results in
syntax error
50. The keyword else can be used with
(a) for statement (b) if statement (c) switch ( ) statement (d)
do.. while ( ) statement
51. Give the output of the following program:
#include < stdio.h >
main()
{int I=1;
while (I < 5)
{printf(%d, I);
}}
/* End of Main */
(a) Warning for no return type for main ( ) (b) Print the value of I as 1
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 195

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
(c) Infinite loop (d) Prints the value of I as11111
52. What is the result of 5 &&2 ?
(a) 0 (b) 2 (c) 1 (d) 5
53. ++I is a operator.
(a) Pre-decrement (b) Pre-increment (c) Post increment (d) Post decrement
54. The output of the following program is
main( )
{int i=2;
printf(%d %d %d,i++,i,++i);
}
(a) 2 2 4 (b) 2 3 3 (c) 3 3 3 (d) 2 3 4
55. How many while statements are possible in do.... While loop?
(a) any number (b) 2 (c) 3 (d) 1
56. The statements that prints out the character set from A-Z is, where a is an integer
variable
(a) for(a=a; a<=z, a++) printf(%c; a); (b) for(a=A; a<=z, a++)
printf(%c; a);
(c) for(a=A a<=Z, a++) printf(%c; a); (d) for(a=A; a<=z, a++)
printf(%c; a);
57. How would you declare a constant of 5 called MYCONST?
(a) var int MYCONST=5 (b) int myconst = 5;
(c) constant MYCONST = 5; (d) #define MYCONST 5
58. The constant \b0 is used for
(a) tab (b) vertical blank (c) bell (d) backspace
59. The equality relational operator is represent by
(a) := (b) == (c) .EQ. (d) =
60. main( )
{ int a=0; if(a) printf(%d,++a); else printf(%d, a+=2) ; } the output is
(a) 3 (b) 1 (c) 2 (d) 0
61. x=9-12/3+3*2-1, what is the value of x
(a) -10 (b) 10 (c) 4 (d) 2
62. The function echoes the character typed on the screen
(a) getchar() (b) gets() (c) getche() (d) getchr()
63. while(++I <=n);
what is the value of I when the loop completes, if the initial value of I is 1.
(a) n-1 (b) n+2 (c) n+1 (d) n
64. Which of the following is shorthand operator for a=a%b
(a) a%=b (b) a =%b (c) a % b (d) a%b=a
65. Which of the following is the ternary operator in C
(a) ?? (b) ?: (c) :: (d) ?;
66. The effect of shifting a variable to the left by one bit position is
(a) subtract it by 2 (b) add it by 2 (c) multiply it by 2 (d) divide it by 2
67. Consider scanf(%2d, &n); and the input data is 3142 then n will be assigned
(a) 42 (b) 31.42 (c) error (d) 31
68. What is the size of long double variable
(a) 8 bytes (b) 10 bytes (c) 16 bytes (d) 4 bytes
69. In C every variable has
(a) a size and value (b) a type, name, value and size (c) a type and size (d)
a name and type
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 196

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
70. Associativity of arithmetic operators is from
(a) left to right (b) middle to right (c) middle to left (d) right to
left
71. What is the value of !0?
(a) 00 (b) 0 (c) -1 (d) 1
72. What is the output of the following program
main()
{ int i; for( i=1; i<=5; i++) printf(%d,i); }
(a) 4 4 4 4 (b) 5 5 5 5 (c) 1 1 1 1 (d) 1 2 3 4 5
73. C variable cannot start with
(a) an underscore (b) a number (c) an upper case letter (d) a lower
case
74. The operator ++ is called as operator
(a) increment (b) special increment (c) decrement (d) double
addition
75. Among the following operators, whose associatively is right to left
(a) conditional expression (b) arithmetic operators (c) logical
operators (d) bitwise operators
76. for( i = 1;i !=5; i++)
{ printf(%d, i+2);} What is the output ?
(a) 3 4 5 6 7 (b) 3 4 5 (c) 3 5 7 9 11 (d) 1 2 3 4 5
77. Which operator is also referred as ternary operator.
(a) Conditional (b) Addition (c) Exponential (d)
Bit wise
78. A do-while loop is useful when we want that the statements within the loop must
be executed.
(a) none of the above (b) at least once (c) more than once (d) exactly once
79. How many keywords are there in C
(a) 34 (b) 30 (c) 31 (d) 32
80. The declaration of a variable should be done
(a) before using it (b) after using it (c) at the time of using (d)
only in the calling program
81. Which of the following is allowed in a C arithmetic statement
(a) { } (b) [ ] (c) / / (d) ( )
82. What function is appropriate for accepting a string?
(a) getch ( ) (b) gets( ) (c) getche ( ) (d) scanf ( )
83. The purpose of the following fragment
B=S+B
S=B-S;
B=B-S;
Where S,B are two integers is to
(a) negate the contents of S and B (b) swap the contents of S and B
(c) transfer the contents of S to B (d) transfer the contents of B to S
84. main( )
{ float a;
int x = 6; y = 4;
a = x/y;
print (%f,a)
}what is the output
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 197

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
(a) error (b) 1.5 (c) 0.5 (d) 1.00
85. What is output of following Program?
main( )
{int x=10,y=5,p,q ;
p= x> 9 ;
q= x > 3 && y != 3 ;
printf( p=%d q=%d ,p,q) ;
}
(a) p =0 q = 0 (b) p = 0 q = 1 (c) p = 1 q= 0 (d) p = 1 q = 1
86. Hierarchy decides which operator
(a) consumes more CPU time (b) operates on large number (c) is used first (d)
is most important
87. The conditional operators ? : is similar to
(a) nested if (b) if-then-else (c) while (d) do-
while
88. Which of the following statements cannot be used to transfer the control
unconditionally to a different statement
in a C program
(a) continue (b) for (c) break (d) goto
89. C language has been developed by
(a) Martin Richards (b) Ken Thompson (c) Peter Norton (d) Dennis
Ritchie
90. Which of the following is a primary data type?
(a) int (b) enum (c) array (d) typedef
91. Output of printf(%f,3/4) is
(a) 0.00 (b) gives an error (c) 0 (d) 0.75
92. Every C Program Statement must be terminated with a
(a) . (b) # (c) ; (d) !
93. Which of the following is/are syntactically correct?
(a) for(); (b) for(;); (c) for(,); (d) for(;;);

UNIT-III
1. The index or subscript value for an array of size n ranges from
(a) 1 to n-1 (b) 0 to n-1 (c) 1 to n (d) 0 to n
2. If we dont initialize a static array, what will be the elements set to:
(a) 0 (b) a floating point number (c) an undetermined value (d)
character constant
3. Which of the following is not a storage class
(a) external (b) automatic (c) register (d) define
4. int cal sum(int a, int b);
In the above, int at the beginning indicates
(a) name of function (b) both function arguments are integer
(c) return type of function (d) received type of function
5. When a function is recursively called, all automatic variables are
(a) stored in a stack (b) stored in a list (c) stored in queue (d) stored in an
array
6. void means
(a) something not known (b) 0 (c) 1 (d) nothing
7. What is the output of
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 198

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
main()
{
int x, change (int);
x = 20;
change (x);
printf (%d, x);
return 0;
}
change (int x);
{
x = 10;
printf (%d. x);
}
(a) 10 30 (b) 20 20 (c) 10 10 (d) 10 20
8. Which of these complier directives access to the print function
(a) #include (b) #define print (c) include stdio.h; (d) #include
conio.h;
9. The number of elements in array declaration
(a) dynamically identifies based on largest index used in program (b) assume default
size as 0
(c) requires to be specified (d) does not require to be specified
10. Identify the incorrect declaration of arrays from the following
(a) int a[50]; (b) float values[10][20]; (c) double a[50]; (d)
int score[10,15];
11. The array is declared as float a[5]; and the memory address of a[0] is 4056. What
is the memory address of a[3].
(a) 4056 (b) 4056 (c) 4059 (d) 4068
12. Two dimensional array elements are stored
(a) system dependent (b) in row major order (c) complier dependent (d) in
column major order
13. How many values a function can return at a time
(a) only one (b) depends on the system (c) infinite values (d) 2
14. When compared to call by value, the call by reference is in execution
(a) equal (b) fast (c) slow (d) neither slow nor fast
15. Which of the following statement is wrong with respect to a storage class
(a) it specifies the defualt initial value (b) it specifies the life of a
variable
(c) by defualt a storage class is static (d) if specifies where variable is
stored
16. Symbolic constants are defined as
(a) #define s1 s2; (b) #define s1=s2 (c) #define s1 s2 (d) #define s1=s2;
17. One dimensional array is known as
(a) set (b) vector (c) matrix (d) table
18. The storage area for register variables
(a) processor registers (b) cache (c) virtual memory (d)
memory
19. In a program a function can be called
A. one time B. two times C. three times
D. any no.of times
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 199

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
20. A function gets called when the function name is followed by
A. comma( ,) B. Period ( .) C. Colon( :)
D. Semi colon(;)
21. Which is not true among the following
A. Brazil( ) is a user defined function
B. Printf( ) is a Library function
C. A function can be called from another function
D. A function can be defined in another function
22. Array elements can be accessed using
A. Tree B. Pointer C. stack D.
Queue
23. An array is represented in Memory by using a
A.Sequential map B. Parallel map C. element map D. circular map
24. The general form of array declaration is
A. Type array name[type] B. Type variable name[size]
C. Type data name[type] D. Type data name[size]
26. int b[5];
main( )
{ static int a[5];
int I;
for(I=0;I<5;I++)
printf("%d%d",b[I],a[I]);
}output is
A. 0000.5times B. error C. garbage values D. 000.10times
27. The amount of storage required for holding the elements of array depends on
A. size B. Memory C. Type and size D. Type
28.How much memory the compiler reserves for each integer array element
A. 6bytes B.8bytes C.4bytes D2bytes
29. main( )
{ static int a[ ]={ 10,20,30,40,50};
int j;for(j=0;j<5;j++)
{printf(%d,a[j]);
a++;
}
} output is
A. 10 20 30 40 B. 10 20 30 C. 10 20 D.compilier
error
30. Array is used to represent the following
(a) A list of data items of different data type
(b) A list of data items of real data type
(c) A list of data items of same data type
(d) A list of data items of integer data type
31. Register variable are active
(a) outside the function
(b) throughout the program
(c) only in the function where it is defined
(d) surrounding of that function.
32. The function sqrt() is part of header file.
(a) math.h (b) iostream.h (c) conio.h (d) stdio.h
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 200

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
33. What is the output of the following program
# includes
# include
void main()
{int a1[5] ={1};
int b = 0, k = 0;
for (b=0; b<=4; b++)
printf (%d , ++ a1[0]);
}
(a) 11111 (b) 23456 (c) 12345 (d) 12222
34. In a multidimensional array with initialization
(a) no demension must be omitted
(b) the left most dimension may be omitted
(c) both leftmost and right most may be omitted
(d) the right most dimension may be omitted
35. The statement used to send back any value to the calling function is
(a) exit (b) return (c) break (d) continue
36. The statement used to send back any value to the calling function is
(a) continue (b) exit (c) break (d) return
37. A static variable is one
(a) which cant be initialized
(b) which is same as an automatic variable but it is placed at the head of the program
(c) which is initialized once and cant be changed at run time
(d) which retains its value through out the life of the program
38. C does no automatic array bound checking. This is
(a) Disadvantage of C (b) false
(c) Neither advantage nor disadvantage (d) Advantage of C
39. The following program
main( )
{static int a[ ] = { 7, 8, 9 };
printf(%d, a[2] = 2[a] + a[2]);
}
(a) will compile successfully (b) results in segmentation violation
error
(c) result is buss error (d) runtime error
40. What is the output of the following program?
void main()
{ char name[4] =
{R,
A,
V
I };
printf (%s, name);
}
(a) RAVI followed by a garbage value (b) RAVI (c) RAV (d)
only garbage value
41. The library function sqrt operates on a double pression argument and I is an
integer variable, which one of the
following calls would compute sqrt(I)?
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 201

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
(a) sqrt((double)I); (b) (double) (sqrt(I)); (c) sqrt(I); (d) (double) sqrt(I);
42. main()
{printf(welcome to c programming\n);
main();
}output of the program code
(a) Infinite loop (b) Runtime error (c) welcome to c programming
(d) compile time error
43. What will be the output of the following program?
void main()
{
char x[ ]={s, a, NULL };
printf (\n %d, sizeof (x));
}
(a) 2 (b) 3 (c) 0 (d) 1
44. The variables which are declared outside the program are called
(a) global variables (b) formal variables (c) local variables (d) register
variable
45. #include is a directive
(a) processor (b) complier (c) pre-compiler (d) pre-
processor
46. Array elements are stored in
(a) either in row major or column major order (b) in diagonal order
(c) row major order (d) column major order
47. Under which of the following conditions,the size of the array need not be
specified?
(a) when it is a formal parameter (b) when the compiler is smart
(c) when initialization is a part of definition (d) when it is a declaration
48. If actual arguments are more than the formal arguments then
(a) extra actual arguments are discarded
(b) a compilation error
(c) extra actual arguments are initialized to garbage values
(d) extra actual arguments are initialized to zero
49. What is the output of the following program?
main()
{int x , y;
x = 10; y = 100;
change (x,y)
printf (%d, %d, x,y);
} change (
int x, int y);
{int k;
k = a; a = b; b = k;
}
(a) 10, 100 (b) 100, 100 (c) 10, 10 (d) 100, 10
50. An external variable definition can appear in
(a) only two files (b) only three files (c) only one file (d) more
than one file
51. For the array declaration int a[5]; What is the amount of storage required
(a) 20 bytes (b) 5 bytes (c) 10 bytes (d) 5 bits
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 202

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
52. The default return type of a function is
(a) float (b) Integer (c) character (d) double
53. What is the output of the following program
void main()
{int x = 2;
sqr(x);
printf(%d, x);
}sqr(x)
{int y;
y = x * x;
printf (%d, y);
}
(a) 2 2 (b) 4 4 (c) 4 2 (d) 2 4
54. What is the output of the following program
main()
{static int y;
printf (%d\n, y);
}
(a) compilation error (b) run-time error (c) 0 (d) undefined
55. An array which contains two subscripts, to represent each element is called as
(a) two dimensional (b) multidimensional (c) three dimensional (d) one
dimensional
56. main()
{ char name[5];
scanf(%s,name);
printf(%s, name);
}if Program is the given as input, what will be the o/p of the program;
(a) Progr (b) program (c) Prog (d)
Runtime error
57. The parameters of the called function are called
(a) casual parameters (b) actual parameters (c) usual parameters (d) formal
parameters
58. output of the following program is
#include< stdio.h>
main()
{int a,count;
int funct( int count);
for( count=1;count<=5;++count)
{a=funct1(count);
printf(%d,a);
}}
int funct1(int x)
{int y;
y= x*x;
return(y);
}
(a) 1 4 9 16 25 (b) 36 (c) 25 (d) 25 9 16
59. Register variables can hold values
(a) float (b) int (c) complex (d) double
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 203

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
60. The parameter passing mechanism for an array is
(a) Call by value (b) Call by value-result (c) call by name
(d) Call by reference
19. What kind of variable is suitable to count how many times a function is called
(a) register (b) external (c) auto (d) static
61. An array can have dimension(s).
(a) single (b) multiple (c) three (d) double
62. If we dont initialize a static array, what will be the elements set to:
(a) character constant (b) a floating point number (c) 0 (d) an
undetermined value
63. main() is
(a) user defined function (b) friendly function (c) library function (d)
member function
64. If the value of the formal argument is changed in the called function; the
corresponding change in the calling
function, if it is call by value
(a) machine dependent (b) does not reflects (c) unpredictabl e
(d) reflects
65. Which of the following statement is wrong with respect to a storage class
(a) if specifies where variable is stored (b) it specifies the defualt initial
value
(c) it specifies the life of a variable (d) by defualt a storage class is static
66. What is the difference between the 5s in the below expressions.
int num[5];
num[5]=10;
(a) Both specify array size
(b) First is array size, second is particular element
(c) First is particular element , second is array size
(d) First is particular element , second is type
67. Under which of the following conditions,the size of the array need not be
specified?
(a) when it is a formal parameter (b) when it is a declaration
(c) when initialization is a part of definition (d) when the compiler is smart
68. Automatic variable are active
(a) outside the function (b) only in the function where it is
defined
(c) surroundings of that function (d) throughout the program
69. Which of the following is the symbol for preprocessor
(a) <> (b) $ (c) * (d) #
70. Which is a self contained block of code that performs a particular task
A.Stack B. Array C. Pointer D. Function

UNIT-IV
1. A string is an array of
(a) integers (b) floating point numbers (c) characters (d) boolen
values
2. A string in the C language is represented by enclosing a sequence of characters in
(a) flower brackets (b) double quotes (c) parenthesis (d) single
quotes
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 204

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
3. What is wrong with the following program
main() { char m1[9]= message1; char m2[9]=message2; m2=m1;
printf(msg is %s,m2); }
(a) array cannot be initialized as above
(b) array is not a left value and so cannot be assigned to
(c) char array cannot be printed directly using printf
(d) program compiles without error, but prints an unpredictable value
4. The function strrev( ) the actual string in the array
(a) will reverse (b) will not reverse (c) may not reverse (d)
may reverse
5. char x[10]=whatisit;
char *y=whatisit;
Pick the correct answer
(a) The output of puts(x) and puts(y) will be different
(b) The output of puts(x) and puts(y) will be same
(c) The output of puts(y) is implementation dependant
(d) The outputs of pulse(x) and puls(y) compiler dependant
6. The strcat( ) function is used for
(a) Concatenation (b) Multiplication (c) Joining (d)
Addition
7.main( )
{int *j;
{ int i=10; j=&i;}
}
A. 7 B. 10 C. 5 D. compiler
error
8. The general format of realloc function is
A. ptr=realloc(size) B. ptr=realloc(ptr) C. ptr= realloc(ptr,newsize)
D. ptr= realloc(free)
9. Which of the following standard file pointer is used for standard auxiliary device
A. std prn B. std aux C. std io D. std
conio
10. Array elements can be accessed using
A. pointer B. Tree C. stack D. queue
11. Address x[ I ]=where I is of type int
A. Base address + ( I ) B. Base address + (I+ scale
factor of int)
C. Index address + ( I + scale factor of int) D. Index address + ( I )
12. The pointer accessing method is _________ than Array indexing
A. same efficient B. slower C. faster D. less efficient
13. The operators <and> are called
A. in direction B. in out direction C. out direction D. redirection
operators
14. main( )
{int a=5,b,*c;c=&a;b=*c;
printf("\n value of a=%d & b=%d",a,b,)}
A. a=3,b=3 B. a=4,b=4 C. a=6,d=6 D. a=5,d=5
15 func(a,b)
int a,b;
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 205

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
{return(a=(a= =b));
}
main( )
{
int process( ),func( );
printf("The value of process is %d! \n", process(func,3,6));
} process(pf,val!,val2)
int (*pf) ( ); int val1,val2;
{
return((*pf)(val1,val2));
}
the value of process is
A. 3! B. compiler error C.0! D. 1!
16. main()
{char s[6]="HELLO"
printf("%d",s[6]);
}
output is
A. compiler error B. 0 C. 34 D. 45
17. main()
{ int *j;
{ int i=10;j=&i;
}printf("%d",*j);
}
A. 10 B. 20 C. 15 D. 5
18. main( ) { int arr[ ]={'A', 'B', 'C', 'D'}
int I; for( I=0; I<3; I++)
printf("%d",arr[I]);
}
A. 65 66 67 B. A B C D C. 65 66 67 68 D. A B C
19. #include<stdio.h>
main( )
{ char s[ ]={'a', 'b','c',' \n ', 'c', '\0'};
char *p, *str, *str1;
p=&s[3];str=p;str1=s;
printf("%d",++*p+ ++*str1-32);
}
A. b B. a C. Compiler error
D. M
20. Which of the following is used with Printf( ) function for printing the Address of a
variable
A. %d B. %u C. %f D. %c
21. Which of the following allows a program to read from or write to files at
Command prompt
A. in out direction B. in direction C. out direction D.
redirection
22. main( )
{ char *str1="abcd";
char str2[ ]="abcd";
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 206

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
printf("%d%d%d", sizeof(str1),sizeof(str2),sizeof("abcd"));}
A. 2 5 5 B. 5 5 2 C. Compiler error D. 5 2 5
23. The variable can be accessed by a Pointer using the Operators
A. & and - B. & and * C. // and ++ D. &
and +
24. A block of memory is allocated using the function
A. falloc( ) B. dalloc( ) C. malloc( ) D.
calloc( )
25. In which of the following header files the standard file pointers have been defined
A. stdconio.h B. stdpointer.h C. stdstream.h D.
stdio.h
26 Which of the following function places cursur at appropriate position on the screen
A. go to( ) B. goto xy( ) C. go ( ) D. goto
screen( )
27. The process of call a function using pointers to pass the address of varaibles is
known as
A. call by argument B. call by parameter C. call by value D. call
by reference
28. The arguments of calling functions are called
A. parameter arguments B. Function call C. Actual arguments
D. Formal arguments
29. Which of the following data structure used to process multiple elements with the
same data types when number of such elements are know
A. Graph B. Array C. Atack D. Quene
28. Which is not true among the following
A. Pointers decrease the Execution speed
B. Pointers are more efficient the arrays
C. Pointers are more efficient in handling the data tables
D. Pointers reduces the length and complexity of a program
29. Which of the following function takes the total number of data and size each data
A. free B. realloc C. malloc D. calloc
30. A character array always ends with
A. Full stop B. NULL character C. &
D. ?
31. The indirection( * )operator is also called as
A. deference operator B. Star operator C. Inference operator D. bit wise
operator
32. Struct {int I; float J;) *s; if the address stores in S is 2000, what is the value of
s+3?
A. 2009 B. 2000 C. 2006 D. 2012
33. void main( )
{ int const * p=5;
printf("%d",++(*p));}
A. Compiler error B. 10 C. 5
D. 15
34. Pointer to pointer is also called as
A. Pointer function B. Pointer structure C. Pointer direction D. pointer
indirection
35. main( )
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 207

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
{ char *p; p="HELLO";
printf("%c \n ",*&*p);
}
A. HE B. HELLO C. HELL D. H
36. When we pass address to a function, the parameters recieving the address should
be
A. Pointers B. Union C.Functions D. Structures
37. The general format of calloc is
A. ptr=(cast type *)calloc(byte size) B. ptr=calloc(cast type*)bytesize
C. ptr=(cast type*) D. ptr=(cast
type*)calloc(n,elementsize)
38. The first parameter in he command line is always
A. struct name B. Pointer name C. program name D.
function name
39. main( )
{
char *p; p="%d \n";
p++;
p++;
printf(p-2,300);
}
A. 296 B. 300 C. 298 D. compiler
error
40. Dynamic memory allocation in array results in
(a) allocation of memory at compile time (b) allocation of memory at file saving
time
(c) allocation of memory at runtime (d) allocation of memory at
debugging time
41. If the first string and the second string both are identical, then strcmp function
returns
(a) a value of 0 (b) either 1 or 0 (c) a value of 1
(d) any positive integer
42. What is the objective of the string handling function strncmp().
(a) Compares only last n characters in both argument
(b) Compares two string only if length of one string is exactly n
(c) Similar to strcmp() function
(d) Compares only first n characters in both argument
43. Give the output for the following:
# include
main( )
{ char arr[10];
int ctr =0;
printf(Enter a Sting:);.
gets(arr);
while(arr[ctr]!=\0)
{ctr + + ;
}printf(%d,ctr);
}
(a) length of the string only when it is less than 9 characters length
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 208

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
(b) String
(c) String length
(d) length of the string only when its length is 10 characters
45. Literal means
(a) A string constant (b) An alphabet (c) A character (d) A
string
46. What is the use of the strlen( ) function
(a) finds the length of the string (b) string comparison (c) string concatenation
(d) copies one string into another
47. The following function is used to count and return the number of characters in a
given string
(a) strcat() (b) strrev() (c) strcmp() (d) strlen()
48. Consider the following program
main()
{ char str[10]; scanf(%s,str); printf(%s,str); } The error in the above program is
(a) the format control for the string variable is not %s
(b) no error in the program
(c) memery has not been allocated for the variable str
(d) the parameter str to scanf is passed by value, it should be a address
49. What is the use of strcmp( ) function
(a) finds the length of the string (b) string comparison
(c) copies one string into another (d) string concatenation
50. How many memory management functions are there in C
a. 4 b. 3 c. 2 d. 1
51. Which of the following is not a C memory allocation function
a. alloc( ) b. calloc( ) c. free d. malloc()
52. All memory management functions are found in
a. stdlib.c b. stdio.h c. conio.h d. math.h
53. Which of the memory function allocates a contiguous memory
a. malloc( ) b. calloc( ) c. release( ) d. free( )
54. Return type of a malloc( ) function is
a. int b. float c. char d. void
UNIT-V
1. The body of the stucture should end with
A. semicolon( ; ) B. comma( , ) C. colon (:) D. period(.)
2. Example of a self-referential Structure
A. Elements in a stack B. Nodes in a Tree
C. Elements in a quene D. Nodes in a Linked list
3. Which of the following unary operator is used to specify the size of the structure
A. Length( ) B. unary( ) C. sizeof( ) D. struct( )
4. The general formate of sending a copying of entire structure to the function is
A. Structure name(function variable name)
B. Function name (structure variable name)
C. structure name(function )
D. function name(structure)
5. In arrays of structures the members are referred using
A. * B. -> C. && D. ( . )
6. enum colors{BLACK,BLUE,GREEN}
main( )
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 209

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
{ printf("%d..%d..%d",BLACK,BLUE,GREEN);
return(1);}
A. 0,1,2 B. compiler error C. 0,1 D.
black
7. Struct a{int I;
float j;
}; Which of the following syntax is correct to declare a structure variable
A. struct union a; B. union struct a; C. union a t; D.
Struct a t;
8. Which of the following are Parameters supplied to a program when te program is
invoked
A. Command line argument B. parameter argument
C. reference argument D. Actual argumenent
9. Structure elements can be accessed through a pointer to a sructure Using the
operator
A. ( , ) B. & C. * D. ->
10. struct{ int I;
float j; } s; size(s) will be
A. 6 bytes B. 0 bytes C. 2 bytes D. 4
bytes
11. The body of union should end with
A. colon( :) B. Period ( . ) C. Semicolon( ; ) D.
comma( , )
12. If struct member is array, then an individual array element can be accessed by
writting a variable
A. Stucture(member) B. member(datatype)
C. member(structure) D. member(expression)
13. Which of the following is a costruct that allows memory to be shared by different
types of data
A. union B. struct C. Bit field D. typedef
14. Which of the following sign is used to access the structure members
A. -> B. && C. ( . ) D. *
15. In union all members use
A. no location B. same location C. different location D. no
stroage
16. struct aaa{ struct aaa *prev;
int i;
struct aaa*next;};
main( )
{
struct aaa abc,defghi,jkl;
int x=100;
abc.i=0;abc.prev=&jkl;abc.next=&def;
def.i=1 ;def.prev=&abc;def.next=&ghi;
ghi.i=2 ;ghi.prev=&def ;ghi.next=&jkl;
jkl.i=3 ;jkl.prev=&ghi; jkkl.next=&abc;
x=abc.next->next prev->next-> i;
printf("%d",x);}
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 210

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
A.2 B. Compiler error C. 3 D.
4
17. The typedef Statement is used for
A. Declaring user defined data types B. Declaring variant data
types
C. for assigning values to vareiables D. for type casting of
variables
18. Portion of memory to be shared by different types of data is
A. field B. array C. struct D. union
19. Each field in a structure can be accessed and manipulated using
A. variables and members B. variables and operands
C. operands and arguments D. Expressions and operators
20. #include<stdio.h>
main( )
{
struct xx
{ int x=3; char name[ ]="hello";
};
struct xx *s=malloc(sizeof(strct xx));
printf("%d",s->x);
printf("%s"s->,name);
}
A. Compiler error B. hello C. xx D. name
21. The internal Representation of bit field is
A. Human independent B. Machine dependent
C. Human dependent D. Machine independent
22. puts(argv[0])prints
A. argv B. the number of command line
arguments
C. the name of executable code file D. the name of the source code file
23. A type defined Structure starts with the keyword
A. Case B. Void C. typedef D. Struct
24.Self referential structure means
A. Refers to any structure B. Refers to the same structure
C. Refers to different structure D. Refers to pointers
25.#include<stdio.h>
main( )
{
struct xx
{ int x=3; char name[]="hello";};
struct xx *s; printf("%d",s->x);printf("%s",s->name);}
A. he B. hello C.compiler error D.hell
26. Which of the following is not true
A. pointers can be used for addressing the bit field directly
B. bit field provides exact amount of bits reserved for storage value
C. Unions can apper in arrays and structures
D. Unions are used to conserve memory
27. The type def Statement is used for
A. Declaring user defined data types B. declaring variant variables
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 211

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
C. for assigning values to variables D. for type casting of
variables
28. The keyword is used to define enumerated data type
(a) array (b) enum (c) typedef (d) struct
UNIT-VI
1. Which of the following function is used for storing information in a disk file
A. fprintf( ) B. fscanf( ) C. scanf( ) D. printf( )
2. The general format of feof function is
A. feof(fp,"controlstring"); B. feof("control string",list);
C. feof(fp,list); D. feof(fp);
3. Which of the following sets the file postion marker to the starting of the file
A. fseek(ptr) B. fseek(ptr,seek_cur);
C.fseek(ptr,0,SEEK_SET); D. fseek(ptr,0,SEEK_CUR);
4.The general format of fprintf( ) function is
A. fprintf(fp,list) B. fprintf(control string,list)
C. fprintf(fp,controlstring,list) D. fprintf(fp, "controlstring")
5.Which of the following function are used to detect I/o errors in the files
A. feof& ferror B. f i/0 & fof C. eof & error D. fofe & f i/o
6. Which of the following mode opens a binary file in write mode
A. feof( ) B. putw( ) C. getw( ) D. wb (write)
7. Which of the following is a set of records that can be accessed through the set of
Library Functions
A. File B. Algorithm C. program D. Data
8. The general format of realloc function is
A. ptr=realloc(ptr,newsize) B. ptr=realloc(ptr)
C. ptr=realloc(size) D. ptr=realloc(free)
9. The EOF is Equivalent to
A. 1 B. 2 C. 0 D. -1
10. "a+" is used to
A. read a file B. read and append a file
C. append a file D. Write into a file
11. The general formate of fscanf( ) is
A. fscanf(fp,controlstring,list); B. fscanf(fp,list);
C. fprintf(fp, controlstring, list); D. fscanf(fp,controlstring);
12. The function that is used to detect the end of file is
A. feof( ) B. fgetch( ) C. go ( ) D. goto screen( )
13. main( )
{ FILE *fp;
fp=fopen("test", "r");
}
A. A structure which contains a char pointer to first character in the file
B. The first character in the file
C. The name of the file
D. The last character in the file
14. The fscanf( ) statement reads data from
A. key board B. file C. scanner D. program
15. Which of the following is used to read a character from the keyboard rather than
for a file
A. ch=fputc(std in) B. ch=fget(std in)
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 212

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
C. ch= fput(std in) D. ch= fgetc(std in)
16. Which of the following function is used to remove the specified file from the disk
A. rewind( ) B. unlink( ) C. getw( ) D. fseek( )
17. Which of the following function is used to set the record pointer at the beginning
of the file
A. putc( ) B. getw( ) C. rewind( ) D. gets( )
18.Which of the following operations can be performed on the "TEST.C" if it is
successfully opened using the statement
FILE *fp
fp=fopen("TEST.c","r+");
A. writing B. Appending C. Reading D. appending and
writing
19. The general format of free function is
A. free(ptr) B. free(ptr,size) C. free(size) D. free(new
size)
20. The C library that contains the Prototype statement for the file operation is
A. proto.h B. file.h C. stdio.h D. stdlib.h
21.Which of the following is a string of characters that make up a vanu name for
operating system
A. header name B. period name C. file name D.
extension name
22. Which of the following standard file pointer is used for atandard Auxiliary device
A. std conio B. std aux C. std prn D. std io
23."r+" is used to open a file in
A. read and write mode B. append mode C. write mode D. read
mode
24. The function that reads the next charecter from the standard input stream and
return its value is
A.Getc B.Fgetc C.Readchar D.Getchar
25.Which of the following function is used to close all the files and returns number of
files closed
A. fclose(fp) B. close( ) C.fcloseall( ) D. closeall( )
26. putchar() and getchar() are both
(a) control statement (b) type declaration statements
(c) assignment statements (d) input and output statements
UNIT-VII
1. The process of arranging records in ordered manner is called
(a) sorting (b) searching (c) indexing (d) None of the
above
2. The process of finding a particular record is called
(a) sorting (b) searching (c) indexing (d) None of the
above
3. In this type of searching the records must be sorted
(a) linear search (b) binary search (c) selection search (d) none of the
above
4. The time complexity of binary search in average case is
a) O(n) b) O(n
2
) c) O(nlogn) d) O(logn) 5.The
time complexity of bubble sort in best case is
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 213

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
a) O(n) b) O(n
2
) c) O(nlogn) d) O(logn)
6.The time complexity of selection sort is
a) O(n) b) O(n
2
) c) O(nlogn) d) O(logn) 7.The
time complexity of insertion sort is
a) O(n) b) O(n
2
) c) O(nlogn) d) O(logn) 8.The
time complexity of quick sort in best case is
a) O(n) b) O(n
2
) c) O(nlogn) d) O(logn)
9.The time complexity of quick sort in worst case is
a) O(n) b) O(n
2
) c) O(nlogn) d) O(logn)
10.The time complexity of bubble sort in worst case is
a) O(n) b) O(n
2
) c) O(nlogn) d) O(logn) 11.The
time complexity of selection sort in worst case is
a) O(n) b) O(n
2
) c) O(nlogn) d) O(logn) 12.The
time complexity of insertion sort in worst case is
a) O(n) b) O(n
2
) c) O(nlogn) d) O(logn) 13.The
time complexity of quick sort in worst case is
a) O(n) b) O(n
2
) c) O(nlogn) d) O(logn)
14.The time complexity of merge sort in worst case is
a) O(n) b) O(n2) c) O(nlogn) d) O(logn)
15.Quick sort is an application of
a) partition exchange sort b) partition sort
c) greedy method d)divide and conquer
16.Merge sort is an application of
a) greedy method b)divide and conquer c) a&b d) none
17.The space complexity of Quick sort in average case is
a) 0 b)O(n) c) O(nlogn) d) O(logn)
18.Binary search is effective only when the elements are in
a) ascending order b) descending order c) a& b d) jumbled order
19. The running time T(n), where `n' is the input size of a recursive algorithm is given
as
followsT(n)=c+T(n-1),if n>1
d, if n 1
The order of this algorithm is
a. n2 b. n c. n3 d. nn
20. The concept of order(Big O) is important because
a. it can be used to decide the best algorithm that solves a given problem
b. It determines the minimum size of a problem that can be solved in a given system,
in a
given amount of time
c. It is the lower bound of the growth rate of the algorithm
d. It is the average bound of the growth rate of the algorithm
21. The concept of order(Big O) is important because
a. it can not be used to decide the best algorithm that solves a given problem
b. It determines the maximum size of a problem that can be solved in a given
system, in a given amount of time
c. It is the lower bound of the growth rate of the algorithm
d. It is the average bound of the growth rate of the algorithm
23. The time complexity of an algorithm T(n), where n is the input size is given
byT(n)=T(n-
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 214

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
1)+/n, if n>1
=1 otherwise
The order of the algorithm is
a. log n b. n c. n2 d. nn
24. The running time of an algorithm is given byT(n)=T(n-1)+T(n-2)-T(n-3), if n>3
= n otherwise
The order of this algorithm is
a. n b. log n c. nn d. n2
25. If n=4,then the value of O(log n) is
a. 1 b. 2 c. 4 d. 8
26. If n=4,then the value of O( n2) is
a. 4 b. 16 c. 64 d. 512
27. The average time complexity of insertion sort is
a. O(n
2
) b. O(n) c. O(1) d. O(log n)
28. The running time of an algorithm is given byT(n)=T(n-1)+T(n-2)-T(n-3), if n>3
= n otherwise. What should be the relation between T(1),T(2) and T(3) so that its
order is constant.
a. T(1)=T(2)=T(3) b. T(1)+T(3)=2T(2)
c. T(1)-T(3)=T(2) d. T(1)+T(2)=T(3)
29. The order of the algorithm that finds a given Boolean function of `n' variables ,
produces a is
a. constant b. linear c. non-linear d. exponential
30. If n= 8, then the value of O(1) is
a. 1 b. 2 c. 4 d. 8
31. You are asked 15 randomly generated numbers. You should prefer
a. bubble sort b. quick sort c. merge sort d. heap sort
32. Which of the following sorting algorithms does not have a worst case running
time complexity of O(n
2
)?
a. Insertion sort b. Merge sort c. Quick sort d. Bubble sort
33. There are 4 different algorithms A1,A2,A3,A4 to solve a given problem with the
order log(n),log(log(n)),nlog(n),n/log(n) respectively. Which is the best algorithm?
a. A1 b. A2 c. A3 d. A4
34. You want to check whether a given set of items is sorted. Which of the following
sorting methods will be the most efficient if it is already in sorted order?
a. bubble sort b. selection sort c. insertion sort d. merge
sort
35. The way a card game player arranges his cards as he picks them up one by one ,
is an example of
a. bubble sort b. selection sort c. insertion sort d. merge
sort
36. Which of the following sorting methods sorts a given set of items that is already
in sorted order or in reverse sorted order with equal speed?
a. Heap sort b. Quick sort c. Insertion sort d.
Selection sort
37. Which of the following sorting methods will be the best if number of swapping
done, is the only measure of efficiency?
a. bubble sort b. insertion sort c. selection sort d. heap
sort
38. As part of the maintenance work, you are entrusted with the work of
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 215

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
rearranging the library books in a shelf in proper order, at the end of each day. The
ideal choice will be
a. bubble sort b. insertion sort c. selection sort d. heap
sort
39. Sorting is not useful for
a. report generation b. minimizing the storage needed
c. making searching easier and efficient d. responding to queries easily
40. A machine took 200 sec to sort 200 names, using bubble sort. In 800 sec. it can
approximately sort _ _ _ _ _ _ _ _ _ names
a. 400 b. 800 c. 750 d. 1600
41. A machine needs a minimum of 100 sec. to sort 1000 names by quick sort. The
minimum time needed to sort 100 names will be approximately
a. 50.2 sec b. 6.7 sec c. 72.7 sec. d. 11.2 sec.
42. A sorting method with _ _ _ _ _ _ _ _ is the most efficient method
a. O(log n) b. O(n) c. O(1) d. O(n2)
43. The average successful search time for sequential search on 'n' items is
a. n/2 b. (n-1)/2 c. (n+1)/2 d. log(n)+1
44. The order of the binary search algorithm is
a. n b. n
2
c. nlog(n) d. log(n)
45. Which of the following algorithm design technique is used in the quick sort
algorithm?
a. Dynamic programming b. Backtracking
c. Divide and conquer d. Greedy method
46. The average successful search time taken by binary search on a sorted order
array of 10 items is
a. 2.6 b. 2.7 c. 2.8 d. 2.9
47. The number of swapping needed to sort the numbers 8,22,7,9,31,19,5,13 in an
ascending order, using bubble sort is
a. 11 b. 12 c. 13 d. 14
48. Given two sorted list of size 'm' and 'n' respectively. The number of comparisons
needed by the merge sort algorithm will be
a. m x n b. maximum of m,n c. minimum of m,n d. m+n-1
49. For merging two sorted lists of sizes m and n into a sorted list of size m+n,
requires _ _ _ _ _ _ _ _ no.of comparisons
a. O(m) b. O(n) c. O(m+n) d.
O(log(m)+log(n))
50. The average number of comparisons performed by the merge sort algorithm , in
merging two sorted lists of length 2 is
a. 8/3 b. 8/5 c. 11/7 d. 1/16
51. Merge sort uses
a. divide and conquer strategy b. backtracking approach
c. heuristic approach d. greedy approach
UNIT-VIII
1.Towers of Hanoi is an application of
a) stack b) queue c) linked list d)
dequeue
2.The data structure used in railway reservation is
a) stacks b) queues c)priority queues d) binary tree
3. The recursive functions are evaluated using
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 216

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
a) stacks b) queues c)priority queues d) binary tree
4.Which of the following is not a linear data structure
a) stacks b) queues c)linked list d) binary tree
5.In evaluation of postfix expression the data structure used is
a) stacks b) queues c)arrays d)
binary tree
6.Linked list uses ____________ type of memory allocation
a) static b)random c)dynamic d)compile time
7.Linked lists uses ____________ type of structures.
a) nested structures b) self referential structures
c) simple structures d)unions
8. The linked list field(s) are
a. data b. pointer c. pointer to next node d. data and pointer to
next node
9. The linked list structure is defined as
a. struct node
{
int item;
struct node *next;
};
b. node
{
int item;
struct node *next;
};
c. struct node
{
int item;
node *node;
};
d. node
{
Int item;
node next;
};
10. Each item in the list contains a link to structure containing the _ _ _ _ _ _ _
item
a. previous b. next c. present d. last
11. A list refers to a set of items organized _ _ _ _ _
a. sequentially b. exponentially c. non-sequentially d. factorially
12. Each structure of a linked list consists _ _ _ _ _ _ _ no. of fields
a. 2 b. 3 c. 4 d. 1
13. Linked lists are not suitable for data structures of which one of the following
problem?
a. insertion sort b. Binary search c. radix sort d. polynomial
manipulation problem
14. An item that is read as input can be either pushed to a stack and latter popped and
printed, or printed directly. Which of the following will be the output if the input is
the
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 217

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
sequence of items-1,2,3,4,5?
a. 3,4,5,1,2 b. 3,4,5,2,1 c. 1,5,2,3,4 d. 5,4,3,1,2
15. No.of pointers to be manipulated in a linked list to delete an item in the middle _ _
_ _
_ _ _
a. Zero b. One c. Two d. Three
16. No.of pointers to be manipulated in a linked list to delete first item
a. Zero b. One c. Two d. Three
17. Stack is useful for _ _ _ _ _ _ _
a. radix sort b. breadth first search c. recursion d. quick sort
18. The end of the list is marked as
a. node.next=0
b. (node.last = 0)
c. node.next= &node;
d. node.previous=0;
19. No.of pointers to be manipulated in a linked list to insert an item in the middle _ _
_ _
_ _ _ _
a. Two b. Three c. One d. Zero
20. Single linked list uses _ _ _ _ _ _ no. of pointers
a. Zero b. one c. Two d. Three
21. LIFO is
a. stack b. queue c. linked list d. tree
22. A stack is has the entries a,b,c,(with a on top). Stack B is empty. An entry popped
out
of stack A can be printed immediately or pushed to stack B.An entry popped out of
stack B can only be printed. In this arrangement, which of the following permutations
a,b,c is not possible?
a. b a c b. b c a c. c a b d. a b c
23. Which of the following programming languages features require a stack-base
allocation
a. pointer b. Block-structure c. recursion d. dynamic
scoping
24. Push down stack or push down list is
a. stack b. queue c. linked list d. dequeue
25. Stacks can not be used to
a. evaluate an arithmetic expression in postfix form
b. implement recursion
c. convert a given arithmetic expression in infix form to is equivalent postfix form
d. allocates resources (like CPU) by the operating system
26. Which of the following is essential for converting an infix expression to postfix
form
efficiently?
a. An operator stack b. An operand stack
c. An operator stack and an operand stack d. A parse tree
27. Linear linked data structure is
a. tree b. graph c. stack d. binary tree
28. A queue of characters currently contained a,b,c,d. What would be the contents of
queue after the following operationDELETE, ADD W, ADD X, DELETE, ADD Y
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 218

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
a. A,B,C,W,Y b. C,D,W,X,Y c. W,Y,X,C,D d. A,B,C,D,W
29. For storing the sorted data on which often insert and deletion operations are
performed, the following data structure is better
a. Array b. queue c. linked-list d. doubly linked-
list
30. A circular queue of size N will sign queue full when the number of elements in the
queue is
a. N-1 b. N c. N+1 d. N-2
31. The postfix equivalent of the prefix * + a b - c d is
a. ab + cd - * b. ab cd + - * c. ab + cd * - d. ab + - cd *
32. The postfix expression for the infix expressionA + B* (C+D) / F + D*E is:
a. AB + CD + F / D + E* b. ABCD + * F / + DE*
c. A*B + CD / F*DE ++ d. A+ BCD / F* DE ++
33. A telephone system which places cells to a particular number on hold can best
represented by
a. queue b. stack c. linked-list d. variable
34. If front=rear ,then the queue is
a. full b. empty c. unknown value d. 1/2 full
35. Reverse polish expression is
a. Infix b. postfix c. prefix d. post & prefix
36. A list of integers is read in, one at a time, and a binary search tree is constructed.
Next
the tree is traversed and the integers are printed. Which traversed would result in a
printout which duplicates the original order of the list of integers?
a. pre-order b. post-order c. in-order d. in-fix order
37. polish expression is
a. infix b. postfix c. prefix d. post & prefix
38. To convert an Infix expression into postfix we require
a. stack b. queue c. linked list d. dequeue
39. A stack is most suitable to evaluate _ _ _ _ _ _ _ expression
a. postfix b. prefix c. infix d. post & infix
40. The circular linked list have
a. no beginning b. no ending
c. beginning but no ending d. no beginning and no ending
41. To insert a node at the beginning of the doubly linked list _ _ _ _ _ _ _ _ no. of
pointers to be manipulated
a. 1 b. 2 c. 3 d. 4
42. Doubly linked list uses _ _ _ _ _ _ _ _ no.of pointers
a. Zero b. One c. Two d. Three
43. To insert a node at the beginning of the single linked list _ _ _ _ _ _ _ no. of
pointers
to be manipulated
a. 1 b. 2 c. 3 d. 0
44. To insert a node at middle of the single linked list _ _ _ _ _ _ _ _ _ _ no. of
pointers to
be manipulated
a. 1 b. 2 c. 3 d. 4
45. To insert a node at the end of the doubly linked list _ _ _ _ _ _ _ no. of pointers to
be
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 219

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
manipulated
a. 1 b. 2 c. 3 d. 4
46. To insert a node at the end of the single linked list _ _ _ _ _ _ _ _ no. of pointers to
be
manipulated
a. 1 b. 2 c. 3 d. 4
47. To delete the first node in single linked list _ _ _ _ _ _ _ _ no. of pointers to be
manipulated
a. 1 b. 2 c. 3 d. 4
48. To delete the last node in single linked list _ _ _ _ _ _ _ no. of pointers to be
manipulated
a. 1 b. 2 c. 3 d. 0
49. To delete the middle node in single linked list _ _ _ _ _ _ _ no. of pointers to be
manipulated
a. 1 b. 2 c. 3 d. 4
50. To delete an item in the middle of a circular doubly linked list, _ _ _ _ _ _ _ _
no.of
points to be manipulated
a. 2 b. 4 c. 6 d. 8
51. If storage class is missing in the array definition, by default it will be taken to be
a. automatic b. external c. static d. either
automatic or external depending on the place of occurrence
52. To delete the last node in doubly linked list _ _ _ _ _ _ _ _ no. of pointers to be
manipulated
a. 1 b. 2 c. 3 d. 4
53. To delete the middle node in doubly linked list _ _ _ _ _ _ _ _ _ no. of pointers to
be
Manipulated
a. 1 b. 2 c. 3 d. 4
54. To insert an item in a circular doubly linked list, _ _ _ _ _ _ _ no.of points to be
manipulated
a. 1 b. 2 c. 3 d. 4
55. To insert a node at middle of the doubly linked list _ _ _ _ _ _ _ no. of pointers to
be
manipulated
a. 1 b. 2 c. 3 d. 4
56. To delete the first node in doubly linked list _ _ _ _ _ _ _ _ no. of pointers to be
manipulated
a. 1 b. 2 c. 3 d. 4
57. To insert an item in a circular single linked list _ _ _ _ _ _ _ _ _ no.of points to be
manipulated
a. 2 b. 3 c. 4 d. 1
58. To delete an item in a circular doubly linked list, _ _ _ _ _ _ _ _ no.of points to be
manipulated
a. 1 b. 2 c. 3 d. 4
59. Stack is useful for
a. radix sort b. breadth first search c. heap sort d. depth
first search
60. A general linear list is a list in which operations, such as retrievals, insertions,
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 220

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
changes, and deletions can be done _ _ _ _ _ _ _ _ _
a. any where in the list b. only at the beginning
c. only at the end d. only at the middle
61. A(n) _ _ _ _ _ _ _ is a collection of elements and relationship Among them.
a. abstract data type b. array c. data structure d. standard
type
62. Data that consists of a single, non decomposable entity are known as _ _ _ _ _ _
a. atomic data b. array c. data structure d. standard
type
63. If the sequence of operations push(1),push(2) ,pop, push(1),push(2),pop, pop,
pop, push(2),pop, are performed on a stack, the sequence of popped out values are
a. 2,2,1,1,2 b. 2,2,1,2,2 c. 2,1,2,2,1 d. 2,1,2,2,2
64. To delete an element from a queue we use the _ _ _ _ _ operation
a. pop b. push c. enqueue d. dequeue
65. To add an element to a queue we use the _ _ _ _ _ operation
a. pop b. push c. enqueue d. dequeue
66. A queue is a _ _ _ _ _ _ structure
a. first in-last out b. lasting-first-out
c. first in-first out d. last in-last out
67. A queue is a list in which insertion can be done _ _ _ _
a. any where in the list b. only at the beginning
c. only at the end d. only at the middle
68. A _ _ _ _ _ _ is a first in - last out(FIFO) data structure in which insertions are
restricted to one end, called the rear, and deletions are restricted to another end
,called the front
a. Stack b. queue c. tree d. binary tree
69. The pointer(s) in a queue points to
a. start of the queue b. end of the queue
c. middle of the queue d. both start and end of the queue
70. The disadvantage of the queue is
a. when the item is deleted, the space for that item is not claimed
b. when the item is deleted, the space for that item is claimed
c. a non destructive
d. increases the memory space
71. A queue is a list in which deletion can be done _ _ _ _
a. any where in the list b. only at the beginning
c. only at the end d. only at the middle
72. Read() operation in queue is
a. non-destructive b. additive c. push() d. destructive
73. In which of the data structure, space for the item is not claimed ,when an item is
deleted
a. queue b. circular queue c. stack d. linked list
74. As the items from a queue get deleted, the space for item is not reclaimed in
queue. This problem is solved by
a. circular queue b. stack c. linked list d. doubly linked
list
75. Which of the following operation is used to add an item in a queue
a. write() b. read() c. pop() d. push()
76. _ _ _ _ no.of pointers are required to implement read and write operations in a
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 221

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
queue
a. two b. three c. four d. five
77. FIFO is
a. stack b. queue c. linked list d. tree
78. Which of the following operation is used to an item in a queue
a. write() b. read() c. pop() d. push()
79. The concatenation of two lists is to be performed in O(1) time. Which of the
following implementations of a list could be used?
a. Singly linked list b. Doubly linked list
c. Circularly doubly linked list d. Array implementation of list
80. The initial condition of a queue is
a. front=rear=-1 b. front=rear c. front=rear=n d. front=rear=1
81. Queue can be used to implement
a. radix sort b. quick sort c. recursion d. depth first
search

























COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 222

VIDYA VIKAS INSTITUTE OF TECHNOLOGY



























COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 223

VIDYA VIKAS INSTITUTE OF TECHNOLOGY




IMPORTANT QUESTIONS UNIT WISE


































COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 224

VIDYA VIKAS INSTITUTE OF TECHNOLOGY

































UNIT I

1. Explain and specify the interactions between various components that support the
basic functionality of a computer?
2. Discuss in detail the program execution steps?
3. What is an algorithm? Write an algorithm to read five integers and find out if the
values are in ascending order.
4. Draw a flow chart to read ten integer values and print the sum of squares of the values.
5. Explain the functions of the following:
i) Preprocessor
ii) Compiler
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 225

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
iii) Linker.
6. Draw a flowchart to find maximum and minimum of the given three input numbers.
7.Define Algorithm? What are the characteristics that any algorithm should satisfy?
8. Draw a flowchart for finding maximum of given three integers?
10. Differentiate between compiler and interpreter?
11. Differentiate between application software and system software?
12. Briefly discuss various computing environments with neat diagrams?
13. List the activities involved in each phase of waterfall system development life
cycle model?
14.What are the different types of errors one can encounter during the program
execution?
15. Write an algorithm to read ten positive integers and find out how many are perfect
squares (such as 49, 81). You may assume that the input values read are in the range 1 to
10000.
16.List the various steps in software development.
17. A utility company charges its customers based on their monthly utilization in terms of
units as follows:
Description charge
First 100 units Rs.10 per unit
Next 200 units Rs. 9 per unit
Next 200 units Rs.8 per unit
Next units Rs.7 per unit
Write flowchart that reads monthly units of a customer and output the charge amount.
18. List and explain the functions of various parts of computer hardware.


UNIT II

1. List the basic data types, their sizes and range of values supported by C
language?
2. Describe the purpose of commonly used conversion characters in scanf()
function?
3. Explain the only ternary operator available in C with illustrative example?
4 What do you mean by operator precedence and associativity? How one can
override the precedence defined by C language? Give illustrative examples?
5.Explain the structure of a C program?
6. Differentiate between if-else-if ladder and switch statement?
7. What is the implicit type conversion hierarchy that is applied while evaluating
expressions?
8. List and give examples for different bitwise operators available in C?
9. Write minimal C expressions for the following:
i) 2x
4
+ 3x
3
- 4x
2
+ 7x -10
ii) Digit at the 10's place of the given positive integer x (for example, digit at the
10's place in 3458 is 5)
iii) True if the given positive integer x is odd, false otherwise
iv) Add x to y, and then decrement x
v) True if 5 <= a <= 10, false otherwise
vi) Fourth bit from the right if the number x is treated in binary representation.
10. Write a complete C Program to print all the prime numbers between 1 and n. Where
n is the value supplied by the user.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 226

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
11. What is an identifier? What are the naming rules for identifiers in C?
12. List different categories of C operators based on their functionality? Give
examples?
13. Write a complete C program that reads a value in the range 1 to 12 and print the name
of that month and the next month: Print error for any other input value. (For example,
print May followed by June if the input is 5. Note that December is followed by
January). [6+9]
14. Write a complete C Program to read ten integers and find:
(i) The number of even integers and their sum, and
(ii) The number of odd integers and their sum.
15. Write C-program for determining whether the given integer at input is perfect number
or not. A number is said to be perfect number if the sum of factors is equal to number
itself. For example, the factors of 6 are 1, 2, 3 whose sum 1+2+3=6.
16. Write minimal C- expressions for the following:
i) 6b
4
+3b
3
-5b
2
+6b+15
ii) 2234abccab
iii) Increment x and then add to z
iv) Maximum of the values of 3 variables a, b and c
v) True if the value of character variable c is in uppercase, otherwise false
vi) Rightmost octal digit in the value of integer variable x
17. What is the difference between the following C-words?
i) 5 and 5 ii) if and ++
18. Write C-program for generation of multiplication table for the given integer input x.
For example, if input is 5, the program need to output
5 X 1 = 5
5 X 2 =10
..
5 X10 =50 [6+2+7]
19. Write C-program that reverses the decimal digits of integer value at input. For
example, for input 5379, the program need to output 9735.

UNIT III

1. Differentiate between call by value and call by reference with suitable examples?
2. Write a C program using functions to check whether the given 3x3 matrix is
symmetric or not?
3. What is the need for user-defined functions?
4. What are the different ways in which 1-dimensional arrays can be declared and
initialized?
5. Write a C program using recursion for finding GCD (Greatest Common Divisor)
of two given numbers?
6. Discuss with suitable examples the storage classes available in C?
7. Derive the expression for finding the address of any element of a 1-dimensional
array?
8. Explain different categories of functions in C with simple illustrative examples?
9. Write a C program using functions to calculate the factorial of a given number?
10 Explain how two dimensional arrays can be used to represent matrices.
11. Write C code to perform matrix addition and matrix multiplication.
12. What is recursion? Write a complete C program that reads a positive integer,
calculate the factorial of the number using recursion, and print the result.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 227

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
13. Explain the facilities provided by the C preprocessor with examples.
14. Explain how matrices can be represented using two dimensional arrays. Explain
with code how Transpose of a matrix can be done.
15. Write a complete C program to do the following: Read data to fill a two
dimensional array int table [4] [4]. Then print the sum of each column and sum of
each row.
16. Write a recursive function double power(double x, int n) that returns x
n.
Write an
equivalent iterative version. Compare them.
17. Using arrays and iteration, Write C-language program that outputs minimum
number of currency notes required for the given amount at input. For example, an
amount of Rs.4260 shall output 1000s 4; 100s 2; 50s -1; 10s-1. The currency
denominations are 1000,500,100,50,20,10,5,2 and 1.
18. Consider the following recursive function
int bbb(int n,int r)
{
printf(%d %d\n,n,r);
if (r==0 || n==r)return 1;
else return bbb(n-1,r)+bbb(n-1,r-1);
}
What output is printed for the function call bbb (4,2)? What does the function do?
19. Write a C-program that reads the given n observations at input and computes
average of n observations and find the number of observations above average value.
The input is value of n followed by n observations.
20. Write C-function float max(float a[], int n) that returns the maximum value of the
first n positions ofarray a.

UNIT IV

1.Consider the following C-program.
void testfun(int *a, int b)
{
int x=2;
static int y=5;
y=y+b;
x=x+y;
*a=x+y+b;
b=b+ *a;
}
int main()
{
int a=10,b=5,c=20,*x;
x=&a;
testfun(x,b);
printf(%d %d %d %d\n,a,b,c,*x);
testfun(x,c);
printf(%d %d %d %d\n,a,b,c,*x);
}
Trace the above program execution (changed variable values and bindings of each
statement during execution). What is the output of above program?
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 228

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
2. Consider the following C- program segment.
char*months[12]={JANUARY,FEBRAURY,MARCH,APRIL,
MAY,JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMB
ER,DECEMBER};
char **a= months;
char **b = a++;
What are the values of the following expressions? Justify your answer.
i) **a ii) *(*(a+5)+3)
iii) *(a+7) iv) *(*(a+9)+6)==*(*a+11)+7)
v) *(++b) vi) *(b++ +3)
3. Write C-function void exchange (int *x, int *y) that exchange the values pointed by
x and y. In addition the function requires counter that count the number of times the
function is invoked.
4 Consider the following C-program segment.
int x[4][4]={{1,2,3,5},{4,5,6,8},{7,8,9,10}};
int **a=x;
int **b=a++;
what are values of the following C-expressions? Justify your answer.
i) **a ii)*(*(a+1)) iii) *(*a+1)+2)
iv)**b+5 v)*(*(b+1)+1)+1 vi)**(a+2)+7
5. Write C-function void insert (char a[], char c, int *n, int i) that inserts character c
at index i in the array by shifting all elements above that position by 1 and
incrementing n.
6. Consider the function maxpos that has two parameters: int maxpos(int arr[], int n)
n is greater than or equal to 1, but less than or equal to the size of the array
arr. Code the function maxpos to return the position of the first maximum
value among the first n elements of the array arr.
7. What are command line arguments? Illustrate their use with a simple C program.
8. Write a complete C program that reads a string and prints if it is a palindrome or
not.
9. Explain about memory allocation functions in C.
10. Write a complete C program that displays the position or index in the string S
where the string T begins. The program displays -1 if S does not contain T. For
example, if S is information processing and T is process, the value displayed is
12. The strings S and T are supplied by the user.
11. Explain the following:
i) Array of pointers
ii) Malloc function.
12. Write the C function int minpos (float x[], int n) that returns the position of the
first minimum value among the first n elements of the given array x.
13. Explain the use of functions strcpy ( ) and strcmp ( )
14. Explain how strings are declared and initialized in C?
15. What are the arithmetic operators that are permitted on pointers?
16. Write a C function to reverse the string passed as an argument that cannot be
altered?
17. Write a C function to find the length of a string passed as an argument?
18. Discuss briefly the following pointers.
I. Pointer pointing to a variable
II. Pointer pointing to a constant
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 229

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
III. Constant pointer pointing to a variable
IV. Constant pointer pointing to constant.
19. Write a C program to swap two integers using functions.
20. Differentiate between a pointer and a variable? How a pointer is declared and
initialized? What do you mean by pointer to another pointer?
21. Write a C function to convert the string passed as an argument to its uppercase
equivalent?

UNIT V

1. Briefly explain the type definition statement in C? Give any two examples
where usage of type definition statement increases the readability of programs?
2. Write a C program to read, write, add, subtract, multiply and divide two
complex numbers? (Represent complex number using structures).
3. Differentiate between structures and unions?
4. What do you mean by bit fields? How bit fields are different from structures?
5. Suppose or oppose the statement In C a structure contains a union inside it.
Give suitable example?
6. How many possible ways one can access the members of a structure using a
structure variable and a pointer to a structure variable? Illustrate with examples.
7. Differentiate between Arrays of structures and structures containing arrays with
suitable examples?
8. What is an enumerated type? How it can be declared? What are the different ways
one can initialize enumerations?
9. Differentiate between self referential and nested structures with suitable
examples?
10. Explain the following with examples:
a) Nested structures b) Array of structures c) Unions.
11. Explain the following with examples:
a) Self referential structures b) Typedef c) Enumerated types.
12. Write C-structures for the College data. College contains the following fields:
College code (2characters), College Name (dynamically allocated string), year of
establishment, number of courses and courses( dynamically allocated structure). A
College can offer 1 to 50 courses. Each course is associated with course name
(String), duration, number of students. The number of students in the college is sum
of number of students in all the courses in the college. Write a function int
collegeeStrength (struct College *c) that returns the number of students in the college
pointed by c.
13. Write C-structures for a country with the following fields: country
Name(dynamically allocated string), currency code(3 letter string), number of states
and states(dynamically allocated structures). A country can have 1 to 100 states. Each
state is associated with name (dynamically allocated string), area, and population. The
area of the country is the sum of the areas of all the states in the country. Similarly the
population of the country is population of all states put together. Write function void
countrystats(struct country *c, int *a, int *b)that computes the area and population of
the country and places at locations pointed by a and b.
14. Write C-structures for line diagram. The Line diagram has the following fields:
diagram Name (dynamically allocated string), no of lines, lines(dynamically allocated
structure). The line diagram can have 1 to 500 lines. Each line contains two end
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 230

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
points, line thickness in pixels and color in the following set (red, black, blue, green,
yellow, orange). Each point contains X-coordinate and Y-coordinate in pixels. Using
this structure, write a function int countlines (struct line_diagram *l, int c) that returns
the number of lines in the given color c.

UNIT VI

1. What is a file? How to open and close different types of files in C?
2. Explain the possible modes of opening files? In all these modes what happens
when the file doesnt exist and the file already exists?
3. Write a C program to copy the contents of a file to another file?
4. Distinguish between getc() and getchar() functions?
5. Explain the general format of fseek() function with illustrative examples?
6. Write a C program to append the contents of a file to another file?
7. Explain syntax with illustrative examples the functions support reading and
writing formatted data to and from files?
8. Write a C program to count characters and lines in a given file?
9. What is the purpose of the ferror() and feof() functions?
10.What are the possible ways to set the file pointer to the beginning of the file?
11. Write a C program to count the number of words in a given file?
12. List and explain the Streams functions for text files along with their prototypes.
13. Explain the different modes that can be provided as a parameter to the fopen( )
function.
14. Write a complete C program for the following: There are two input files named
first.dat and second.dat. The files are to be merged. That is, copy the content of
first.dat and then the content of second.dat to a new file named result.dat.
15. Explain what is a text file and what is a binary file.
16. Write a complete C program for finding the number of words in the given text file.
Assume that the words are separated by blanks or tabs.
17. Write a complete C program to reverse the first n characters in a file. The file
name and the value n are specified on the command line. Incorporate validation of
arguments: that is, the program should check that the number of arguments passed and
also the value of n are meaningful.
18. Write a C-function that takes a binary file of long integers and appends a new long
integer at the end that is sum of all integers in the original file.
19.List and explain different format literals available in printf statement.
20. Write C-language program that reads a C-program file and outputs number of
lines in the program.
21 Differentiate between fprintf and fwrite statements. When do you prefer to use
fwrite instead of fprintf ?
22. Given filename, index and value, Write C-program that reads element of binary
files of long integer array at the given index, add value to it and store back at that
location.

UNIT VII

1. Write an algorithm or C-program for sorting integers in ascending order using
insertion sort.
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 231

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
2. Demonstrate the insertion sort results for each insertion for the following initial
array of elements.
25 6 15 12 8 34 9 18 2
3. Write an algorithm or program for sorting integers using bubble sort.
4. Show the bubble sort results for each pass for the following initial array of
elements.
35 18 7 12 5 23 16 3 1
5. Write an algorithm or C-function for selection sort for sorting an array of integer in
ascending order.
6. Demonstrate the selection sort results for each pass for the following initial array
of elements.
21 6 3 57 13 9 14 18 2
7. Write algorithm/Program for binary search to find the given element within array.
For What data binary search is not applicable?
8. Show the quick sort results for each exchange for the following initial array of
elements
35 54 12 18 23 15 45 38
9. Explain bubble sort with the algorithm or a C program.
10. Write a C program or algorithm to sort an array of integers in ascending order
using insertion sort.
11. Write an algorithm or C program for sorting integers in ascending order using
selection sort.
12. Write a C program for binary search using functions without using recursion?
13. An array contains 8, 13, 17, 26, 44, 56, 88, and 97. Trace the steps using binary
search Algorithm.
I. To find value 88
II. To find the value 20
III. To find the value 8.
14. An Array contains 3, 13, 7, 26, 44, 23, 98, and 57. Trace the steps using merge
sort?
15. Write a C program for selection sort using functions?
16. An Array contains 3, 13, 7, 26, 44, 23, 98, and 57. Trace the steps using quick
sort?






UNIT VIII

1. What is the main disadvantage of Queue over Circular Queue?
2. Write a C Program to demonstrate the operations of a Circular queue using
arrays?
3. Write the steps with illustrative figures involved in the following operations of a
singly linked list without the head node?
I. Insert into an empty List
II. Insert at the first position
III. Insert at the last position
COMPUTER PROGRAMMING AND DATA STRUCTURES

D KOTESWARARAO, Associate Professor ,CSE Dept. Page 232

VIDYA VIKAS INSTITUTE OF TECHNOLOGY
IV. Insert before a given element
V. Insert after a given element.
4. Write the steps with illustrative figures involved in the following operations of a
singly linked list without the head node?
I. Delete the first element
II. Delete the last element
III. Delete before a given element
IV. Delete after a given element.
5. What is a doubly linked list? What is the main advantage over singly linked
list?
6. Trace the output string and the stack contents at every step in converting the
expression A * B / (C D) + E * F - G into postfix expression?
7. Write a C Program to demonstrate the operations of a Stack using arrays?
8. What is a singly linked list? Explain with C code how the insertion, deletion and
searching operations are performed on a singly linked list.
9. Explain what is a queue and operations performed on queue. Provide C code for the
same.
10. Explain the properties of the abstract data structure stack.
11. Explain the algorithm to convert infix expression to postfix expression.
12. What are the operations on Linear Lists? Differentiate between using Arrays and
Linked Lists for implementation of Linear Lists.
13.Write an algorithm for evaluating postfix expression. Demonstrate your algorithm
with stack contents for each operation using the post fix expression 2 3 5 + *
14. Write structures for Linked list implementation of Stack and a function for pop
operation.
15. Write C-structures for implementing queues using Linked Lists. Using these
structures, write C-function for dequeue operation.
16. Using recursive function for factorial, explain the execution of the function call
factorial(5) using stack.

Das könnte Ihnen auch gefallen