Data Structures and C Programming (B.SC Cs and B.C.A - 2 Sem)
Data Structures and C Programming (B.SC Cs and B.C.A - 2 Sem)
#
DATA
STRUCTURES AND
C PROGRAMMING
| A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
[CONTENTS]
LESSON 1 program development styles and basics of c 1
Program Development Methodologies - Programming Style - Stepwise Refinement and
Modularity - Problem Solving Techniques - Algorithm – Flowcharts – Pseudocode – Sequence
and Selection - Recursion vs. Iteration - Overview of Compilers and Interpreters - Structure of a
C Program - Programming Rules - Executing the Program.
LESSON 4 OPERATORS 21
Operators of C - Arithmetic operators - Relational operators - Logical operators – Assignment
operators - Increment and decrement operators - Conditional operator - Bitwise operators -
Special operators.
LESSON 5 EXPRESSIONS 24
Expressions - Arithmetic expressions - Precedence of arithmetic operators - Type conversion
in expressions - Mathematical functions - Managing input and output operations.
LESSON 10 POINTERS 52
Understanding Pointers - Accessing the Address of a Variable - Accessing a Variable
through its Pointer - Pointer Expressions - Pointers and Arrays - Pointers and Character Strings.
| A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
LESSON 12 STRUCTURES 61
Introduction - Structure Definition - Array Vs Structure - Giving Values to Members -
Structure Initialization - Comparison of Structure Variables - Arrays of Structures.
LESSON 14 FILES 70
Introduction - Defining and Opening a File - Closing a File - Input/output operations on Files.
LESSON 18 STACK 84
Introduction – Stack - Representation and terms – Operations – Insertion - Deletion –
Implementations.
LESSON 22 SORTING 98
Introduction – Sorting - Comparison with other method.
| A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
REFERENCES 107
APPENDICES 108
- BHARATHIAR UNIVERSITY B.Sc. COM.SCI DEGREE COURSE SYLLABUS
- MODEL QUESTION PAPERS
- PRACTICAL LIST
| A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Procedural Programming
(a) In the procedural programming languages such as
FORTRAN and COBOL, programs are divided into a
number of segments-called sub-programs. Thus, it focuses
on functions apart from data. Fig. 2 describes a program of
procedural type. It shows different subprograms accessing
the same global data. Here also, the programmer can
observe lack of secrecy.
(b) The control of program is transferred using unsafe
goto statement.
(c) Data is global and all the sub-programs share the
same data.
(d) These languages are used for developing medium-
sized applications.
1 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Structured Programming
BASIC is widely believed to be an unstructured language. Modularity is not supported by
BASIC. It becomes difficult to debug a lengthy program written in BASIC. One should organize the
programs in modules and should write programs that are easy for others to read. Modular programming
concept is used in structured programming. A big program is to be split into modules or subroutines.
Instead of running through a number of lines, divide it into sma1l modules. These modules are easier to
debug.
a) Larger programs are developed in structured programming such as Pascal and C. Here
programs are divided into multiple sub-modules and procedures.
b) Each procedure performs different tasks.
c) Each module has its own set of local variables and program code as shown in Fig. 3. Here,
the different modules are shown accessing the global data.
d) User-defined data types are introduced.
Programming Style.
The program development styles are of two types:
1) Top-down design method
2) Bottom-up design method
1) Top-down design method: In the top-down design method, designing the system is initiated from
the top. The solution of the problem can be divided into smaller blocks. Initial view of solution is
not clear just like when an aeroplane descends from a great height the view to the ground is not
clear but when the plane approaches the ground things get clear and everything can be seen clearly
with our naked eyes. In a similar way, design is carried out. The strategy of designing a system is
to divide the task into many sub-tasks. We make a group that comprises task and sub-task. Each
sub-task can be performed in a function. The function performs a well-defined job or task.
There are various drawbacks of the top-down approach. Here in the design strategy
2 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
importance is given to functions rather than data. For example, in turbo C, we cannot give data
after clrscr (). If data is declared after clrscr (), error will be shown by the compiler.
2) Bottom-up design method: Here the design of a problem starts from the bottom and it goes up
to the top. Some designers prefer this approach. They attempt to find the last blocks of design and
implement them first. By building various blocks from the bottom they ascend towards the top,
assemble all parts designed as planned, and make the final product. Most of the professional
designers do not prefer this approach because it makes the design complex and difficult to
implement.
Stepwise Refinement and Modularity
A lengthy program can be divided into small programs. This step enables one to follow the
programs easily. It makes it easy to solve a program and bugs in it can be traced easily. The computer
itself cannot do anything. It follows only the instructions given by the programmer. Even if the
subprograms are difficult to understand after dividing the main, sub-programs may be further
subdivided into smaller programs. This process can be continued until the programs are practical.
In any organization, the top management cannot look after every activity of the organization.
They must concentrate on some specific aims or undertaking of the company and delegate
responsibilities to subordinates. In addition, middle level managers also share their responsibilities with
their subordinates. At every level, the work is divided and shared with the subordinates. The same
concept is to be applied to computer programming. Even if a project seems to be small and one is
capable of handling it alone, it is better to do the same among a group of programmers. This step helps
in designing the project quickly and quality can be assured. However, it is a good approach to divide
the problem into sub-programs and solve each sub-program in a systematic manner.
The above procedure is called top-down refinement. Large programs can be easily solved by
this method. This approach involves deferment of detailed considerations at the first stage. Even at this
stage attention must be paid to accuracy and inflexibility. The programmer decides the exact way of
division of work between functions. Thus, before working it is essential to know what a particular
function does. Normally it is somewhat difficult to divide the tasks into separate functions. Lot of
thinking has to go at the initial stage. Moreover, some revision is always expected in the function and
scope must be there for improvement. Therefore, a function can be altered in future. To overcome this
confusing situation there are a few guidelines for dividing the program among functions.
These guidelines are as follows:
1) The programmer should explain the use of a function in a few words. If the programmer fails
to do so and writes a lengthy unwanted description, it means that more than enough details are
provided. The detailed descriptions are not to be disclosed and it should not come into view until the
next stage of refinement comes. The programmer must rethink about the dividing of program. Thus, in
short, we can say that each function should perform only one task with full accuracy.
2) We know that a big organization has hierarchical levels of operations. At the top, there are
several ranks of managers controlling the operations. The middle level managers obtain information
from the lower level. However, the entire information is not passed. As it is to upper level managers.
Only the relevant information needed for that manager is sent. In the same fashion, whatever
3 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
instruction or information one gets from higher level managers is not passed as it is to junior level
managers or subordinates but only applicable information is passed on to them. The function we are
going to design should follow the above principle.
Thus, in short, we can say that each function must hide some details. The refinement decides
what a particular function performs. It also decides a function's pre and post conditions, that is, what
data the function takes and what output it will provide. The data used in these functions must be exactly
declared.
4 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Another real life example is accessing the Internet through an Internet Service Provider with
dial up facility. To log on to the Internet. the following steps are to be followed.
1) Choose the Internet Service Provider for accessing the Internet
2) Obtain from service provider a dial up number
3) Acquire IP address of the service provider
4) Acquire login ID and password
5) Run the Internet browsing software
Analyzing algorithm: When one writes an algorithm, it is essential to know how to analyze
the algorithm. Analyzing an algorithm refers to calculating or guessing resources needed for that
algorithm. Resources means computer memory, processing time, logic gates and so on. In all the
above factors, time is most important because the program developed should be faster in
processing. The analysis can also be made by reading the algorithm for logical accuracy, tracing the
algorithm, implementing it, checking with some data and with some mathematical technique to
confirm its accuracy.
Algorithms can also be expressed in a simple method. It will help the user to put it into
operation easily. However, this approach has a few drawbacks. It requires more space and time. It is
very essential to consider factors such as time and space requirements of an algorithm. With
minimum system resources such as CPU time and memory, an efficient algorithm must be
developed.
Rate of growth: In practice, it is not possible to act upon a simple analysis of an algorithm to
conclude the execution time of an algorithm. The execution time is dependent upon the machine
and the way of implementation. Timing analysis depends upon the input required. To accurately
analyze the time it is also very essential to know the exact directives executed by the hardware and
the execution time passed for each statement.
5 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Classification of Algorithms
Algorithm can be classified into three types. The classification of an algorithm is based on
repetitive steps and based on control transfer from one statement to another. Based on repetitive steps,
an algorithm can be classified into two types.
1) Direct algorithm
2) Indirect algorithm
1) Direct algorithm: In this type of algorithm the number of iterations is known in advance. For
example, for displaying numbers from 1 to 10, the loop variable should be initialized from1 to10.
The statement would be as follows:
for (j=1;j<=10;j++)
In the above statement, it is predicted that the loop will iterate for ten times.
2) Indirect algorithm: In this type of algorithm repetitive steps are executed a number of times.
Exactly how many repetitions are to be made is unknown.
For example, finding the first five Armstrong numbers from 1 to n, where n is the fifth Armstrong
number and finding the first three palindrome numbers.
Based on control transfer the algorithms are classified into the following three types.
a) Deterministic
b) Non-deterministic
c)Random
6 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Example finding shortest paths from a given source to all destinations in the network.
Flowcharts
A flowchart is a visual representation of the sequence of steps for solving a problem. It
enlightens what comes first, second, third, and so on. A completed flowchart enables you to organize
your problem into a plan of actions. Even for designing a product a designer many times has to draw a
flowchart. It is a working map of the final product. This is an easy way to solve the complex
designing problems. The reader follows the process quickly from the flowchart instead of going
through the text.
A flowchart is an alternative technique for solving a problem. Instead of descriptive steps, we
use pictorial representation for every step. It shows a sequence of operations. A flowchart is a set of
symbols, which indicates various operations in the program. For every process, there is a
corresponding symbol in the flowchart. Once an algorithm is written, its pictorial representation.
It can be done using flowchart symbols. In other words, a pictorial representation of a textual
algorithm is done using a flowchart. We give below some commonly used symbols in flowcharts.
Start and end: The start and end symbols indicate both the beginning and the end of the flowchart.
This symbol looks like a flat oval or is egg shaped. Fig.5 shows the symbol of Start/Stop; only one
flow line is combined with this kind of symbol. We write START, STOP or END in the symbols of
this kind. Usually this symbol is used twice in a flowchart, that is, at the beginning and at the end.
Decision or test symbol: The decision symbol is diamond shaped. This symbol is used to take one of
the decisions. Depending on the condition the decision block selects one of the alternatives. While
solving a problem, one can take a single, two or multiple alternatives depending upon the situation. All
these alternatives are illustrated in this section. A decision symbol with a single alternative is shown in
Fig.5. In case the condition is satisfied /TRUE a set of statement(s) will be executed otherwise for false
the control transfers to exit.
Single alternative decision: Here more than one flow line can be used depending upon the condition.
It is usually in the form of a 'yes' or 'no' question, with branching flow lines depending upon the
answer. With a single alternative, the flow diagram will be as per Fig.6.
Two alternative decisions: In Fig.7 two alternative paths have been shown. On satisfying the
condition statement(s) pertaining to 1 action will be executed, otherwise the other statement(s) for
action 2 will be executed. Multiple alternative decisions: In Fig.8 multiple decision blocks are shown.
Every decision block has two branches. In case the condition is satisfied, execution of statements of
appropriate blocks take place, otherwise next condition will be verified. If condition 1 is satisfied then
block 1 statements are executed. In the same way, other decision blocks are executed.
Connector symbol: A connector symbol has to be shown in the form of a circle. It is used to establish
7 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
the connection, whenever it is impossible to directly join two parts in a flowchart. Quite often, two
parts of the flowcharts may be on two separate pages. In such a case, connector can be used for joining
the two parts. Only one flow line is shown with this symbol. Only connector names are written inside
the symbol, that is, alphabets or numbers. Fig.9 shows the connector symbol.
8 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
compiler reads the values of X, Y and in the second figure the result is displayed on the monitor or the
printer.
Delay symbol: Symbol of delay is just like 'AND' gate. It is used for adding delay to the
process. It is associated with two lines: One is incoming and the other is outgoing, as shown in Fig. 13.
Manual input symbol: This is used for assigning the variable values through the keyboard,
where as in data symbol the values are assigned directly without manual intervention. Fig.14 represents
the symbol of manual input.
In addition, the following symbols (Fig.15) can be used in the
flowchart and they are parts of flowcharts.
9 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Pseudocode
In Pseudocode English-like words are used to represent the various logical steps. It is a prefix
representation. Here solution of each step is described logically: The pseudocode is just the raw idea
about the problem. By using this tip, one can try to solve the problem. The meaning of pseudocode is
'false code.' The syntax rule of any programming language cannot be applie4 to pseudocode.
Example (a): Assume a and b are two numbers and Algorithm Pseudocode
find the larger out of them. In such a case,
comparison is made between them. Input a and b. Get numbers a & b
Few skilled programmers prefer to write pseudocode Is a>b. Compare a & b
for drawing the flowchart. This is because using If yes a is larger than if a is large max=a
pseudocode is analogous to writing the final code in b. if b is large max=b
the programming language. Few programmers prefer If no b is larger than a. larger number is
to write the steps in algorithm. Print the larger max
Few programmers favor flowchart to represent number.
the logical flow because with visualization things are
clear for writing program statements.
For beginners a flowchart is a straightforward tool for writing a program.
Example (b): Example illustrates how the pseudocode is used to draw a flowchart.
1) Accept number
2) Calculate square of the number
3) Display number
All the steps of the program are written down in steps. Some programs follow pseudocode to draw
flowcharts. Using pseudocode, final program can be written. Majority of programs have common tasks
such as input, processing and output. These are fundamental tasks of any program. Using pseudocode a
flowchart can be drawn as per the following steps. For the statement, that is, 'Accept number' the
flowchart symbol is as per Fig.19.
1.8 Sequence and Selection
The steps in an algorithm can be divided into three categories.
1) Sequence: The steps described in the algorithm are performed
successively one by one without skipping any step. The sequence
of steps defined in the algorithm should be simple and easy to
understand. Each instruction of such an algorithm is executed,
because no selection procedure or conditional branching exists in a
sequence algorithm. Fig.20
represents the sequence of Dial the phone
steps for a telephonic Phone rings at the called party
conversation. Consider an
example described in the Caller waits for the response
topic 'Algorithm'. Called party picks up the phone
1) Dial the phone number
2) Phone rings at the called Conversation begins between
party them
3) Caller waits for the Release of connection
response
Fig. 20 Sequence algorithm
10 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Recursion Iteration
Recursion is the term given to the mechanism of The block of statements executed repeatedly
defining a set or procedure in terms of itself. using loops.
A conditional statement is required in the body of the The iteration control statements itself contain
function for stopping the function execution. statement for stopping the iteration. At every
execution, the condition is checked.
At some places, use of recursion generates extra All problems can be solved with iteration.
overhead. Hence, better to skip when easy solution is
available with iteration.
Recursion is expensive in terms of speed and memory. Iteration does not create any overhead. All the
programming languages support iteration.
11 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Structure of a C PROGRAM
Every C program contains a number of several building blocks known as functions. Each
function performs a task independently. A function is a subroutine that may consist of one or more
statements. A C program comprises different sections which are shown in Fig. 22.
a) Include header file section: A C program depends upon some header files for function
definitions that are used in the program. Each header file, by default, has an extension '.h'. The file
Should be included using '# include' directive as given below.
Example # include <stdio.h> or # include "stdio.h."
Include header file section In this example <stdio.h> file is included, that is, all the
definitions and prototypes of functions defined in this file are
Global declaration section available in the current program. This file is also compiled with
/* comments */ the original program.
b) Global declaration: This section declares some variables that
main() function name are used in more than one function. These variables are known as
{ global variables. This section must be declared outside of all the
functions.
/* comments */
c) Function main ( ): Every program written in c language must
declaration part contain main () function. Empty parenthesis after main is
executable part necessary. The function main () is a starting point of every C
program. The execution of the program always begins with the
} function main ( ). Except the main () function, other sections may
user-defined functions not be necessary. The program execution starts from the opening
brace ( { ) and ends with the closing brace( } ). Between these two
{ braces, the programmer should declare declaration
} and executable parts.
d) Declaration part: The declaration part declares the entire
fig. 26. Structure of a C
variables that are used in the executable part. Initializations of
program
variables are also done in this section. Initialization means
providing initial value to the variables.
e) Executable part: This part contains the statements following the declaration of the variables.
This part contains a set of statements or a single statement. These statements are enclosed between
braces.
f) User-defined function: The functions defined by the user are called user-defined functions.
These functions are generally defined after the main () function. They can also be defined before
main( ) function. This portion is not compulsory.
g) Comments: Comments are not necessary in the program. However, to understand the flow
of a program, the programmer can include comments in the program. Comments are to be inserted by
the programmer. These are useful for documentation. The clarity of the program can be followed if it is
properly documented. Comments are nothing but some kind of statements which are to be placed
between the delimiters /* & */. The compiler does not execute comments. Thus, we can say that
comments are not the part of executable programs.
The user can frequently use any number of comments that can be placed anywhere in the
12 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
program. Please note that comment statements can be nested. The user should select the OPTION
MENU of the editor and select the COMPILER-SOURCE -NESTED COMMENTS ON /OFF. The
comments can be inserted with a single statement or in nested statements.
Example
/* This is single comment */
/* This is an example of /* nested comments */*/
/* This is an example of
comments with multiple lines */ /* It can be nested * /
Programming Rules
The programmer, while writing a program, should follow the following rules.
1) All statements should be written in lowercase letters. Uppercase letters are only used for
symbolic constants.
2) Blank spaces may be inserted between the words. This improves the readability of the
statements. However, this is not used while declaring a variable, keyword, constant and functions.
3) It is not necessary to fix the position of a statement in the program, that is, the programmer
can write the statement anywhere between the two braces following the declaration part. The user can
also write one or more statements in one line separating them with a semicolon (;). Hence, it is often
called a free-form language.
The following statements are valid.
a=b+c;
d=b*c;
or
a=b+c;d=b*c;
4) The opening and closing braces should be balanced, that is, for example, if opening braces
are four then closing braces should also be four.
13 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
INTRODUCTION
A programming language is designed to help certain kinds of data process consisting of
numbers, characters and strings to provide useful output known as information. The task of processing
of data is accomplished by executing a sequence of precise instructions called program.
CHARACTER SET
C characters are grouped into the following
categories.
1. Letters
2. Digits
3. Special Characters
4. White Spaces
White Spaces
• Blank Space
• Horizontal Tab
• Carriage Return
• New Line
• Form Feed
Delimiters
Language pattern of C uses special kinds of
symbols, which are called as delimiters. They are
given as Table
14 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
C TOKENS
In C programs, the smallest individual units are known as tokens.
CONSTANTS
Constants in C refer to fixed values that do not change during the execution of a
program.
15 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Integer Constants
An integer constant refers to a sequence of digits, There are three types integers, namely,
decimal, octal, and hexa decimal.
Decimal Constant
Eg:123,-321 etc.,
Note: Embedded spaces, commas and non-digit characters are not permitted between digits.
Eg: 1) 15 750 2)$1000
Octal Constant
An octal integer constant consists of any combination of digits from the set 0 through 7, with a
leading 0.
Eg: 1) 037 2) 0435
Hexadecimal Constant
A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer. They may also
include alphabets A through F or a through f.
Eg: 1) 0X2 2) 0x9F 3) 0Xbcd
Real Constants
Certain quantities that vary continuously, such as distances, heights etc., are represented by
numbers containing functional parts like 17.548.Such numbers are called real(or floating point)
constants.
Eg:0.0083,-0.75 etc.,
A real number may also be expressed in exponential or scientific notation.
Eg:215.65 may be written as 2.1565e2
16 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
VARIABLES
Definition:
A variable is a data name that may be used to store a data value. A variable may take different
values at different times of execution and may be chosen by the programmer in a meaningful way. It
may consist of letters, digits and underscore character.
Eg: 1) Average
2) Height
Rules for defining variables
v They must begin with a letter. Some systems permit underscore as the first character.
v ANSI standard recognizes a length of 31 characters. However, the length should not be
normally more than eight characters.
v Uppercase and lowercase are significant.
v The variable name should not be a keyword.
v White space is not allowed.
17 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Integer Types
Type Size (bits) Range
int or signed int 16 -32,768 to 32767
unsigned int 16 0 to 65535
short int 8 -128 to 127
unsigned short int 8 0 to 255
long int 32 -2,147,483,648 to 2,147,483,647
unsigned long int 32 0 to 4,294,967,295
18 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Character Types
Type Size (bits) Range
char 8 -128 to 127
unsigned char 8 0 to 255
DECLARATION OF VARIABLES
The syntax is
Data-type v1,v2…..vn;
Eg: 1.int count;
2.double ratio, total;
User-defined type declaration
C allows user to define an identifier that would represent an existing int data type.
The general form is typedef type identifier;
Eg: 1) typedef int units;
2) typedef float marks;
Another user defined data types is enumerated data type which can be used to declare variables that can
have one of the values enclosed within the braces.
enum identifier {value1,value2,……valuen};
19 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
20 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Lesson 4 OPERATORS
Outline
Operators of C - Arithmetic operators - Relational operators - Logical operators -
Assignment operators - Increment and decrement operators - Conditional operator -
Bitwise operators - Special operators
OPERATORS OF C
C supports a rich set of operators. Operators are used in programs to manipulate data and
variables. They usually form a part of the mathematical of logical expressions.
C operators are classified into a number of categories. They include:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and Decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
ARITHMETIC OPERATORS
The operators are
+ (Addition)
- (Subtraction)
* (Multiplication)
/ (Division)
% (Modulo division)
Eg: 1) a-b 2) a+b 3) a*b 4) p%q
The modulo division produces the remainder of an integer division. The modulo division operator
cannot be used on floating point data.
Note: C does not have any operator for exponentiation.
Integer Arithmetic
When both the operands in a single arithmetic expression are integers, the expression is called
an integer expression , and the operation is called integer arithmetic. During modulo division the sign
of the result is always the sign of the first operand. That is
-14 % 3 = -2
-14 % -3 = -2
14 % -3 = 2
Real Arithmetic
An arithmetic operation involving only real operands is called real arithmetic. If x and y are
floats then we will have:
21 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
RELATIONAL OPERATORS
Comparisons can be done with the help of relational operators. The expression containing a
relational operator is termed as a relational expression. The value of a relational expression is either
one or zero.
1) < (is less than)
2) <= (is less than or equal to)
3) > (is greater than)
4) >= (is greater than or equal to)
5) = = (is equal to)
6) != (is not equal to)
LOGICAL OPERATORS
C has the following three logical operators.
&& (logical AND)
|| (logical OR)
! (logical NOT)
Eg: 1) if(age>55 && sal<1000)
2) if(number<0 || number>100)
ASSIGNMENT OPERATORS
The usual assignment operator is ‘=’.In addition, C has a set of ‘shorthand’ assignment
operators of the form, v op = exp;
Eg:1.x += y+1;
This is same as the statement
x=x+(y+1);
Shorthand Assignment Operators
22 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
CONDITIONAL OPERATOR
A ternary operator pair “?:” is available in C to construct conditional expression of the form:
exp1 ? exp2 : exp3;
Here exp1 is evaluated first. If it is true then the expression exp2 is evaluated and becomes the value of
the expression. If exp1 is false then exp3 is evaluated and its value becomes the value of the expression.
Eg: 1) if(a>b)
x = a;
else
x = b;
BITWISE OPERATORS
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift left
>> Shift right
~ One’s complement
SPECIAL OPERATORS
C supports some special operators such as
Ø Comma operator Ø Size of operator Ø Pointer operators(& and *) and
Ø Member selection operators(. And →)
The Comma Operator
The comma operator can be used to link the related expressions together. A commalinked list of
expressions are evaluated left to right and the value of right-most expression is the value of the
combined expression.
Eg: value = (x = 10, y = 5, x + y);
This statement first assigns the value 10 to x, then assigns 5 to y, and finally assigns15 (i.e,
10+5) to value.
The Size of Operator
The size of is a compiler time operator and, when used with an operand, it returns the number of
bytes the operand occupies.
Eg: 1) m = sizeof(sum);
2) n = sizeof(long int)
3) k = sizeof(235L)
23 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Lesson 5 EXPRESSIONS
Outline
Expressions - Arithmetic expressions - Precedence of arithmetic operators -
Type conversion in expressions - Mathematical functions - Managing input and output operations
EXPRESSIONS
The combination of operators and operands is said to be an expression.
ARITHMETIC EXPRESSIONS
An arithmetic expression is a combination of variables, constants, and operators arranged as per
the syntax of the language.
Eg 1) a = x + y;
EVALUATION OF EXPRESSIONS
Expressions are evaluated using an assignment statement of the form variable = expression;
Eg: 1) x = a * b – c; 2) y = b / c * a;
Program
/*Evaluation of expressions*/
main()
{
float a, b, c, y, x, 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 = %f \n”,x);
printf(“y = %f \n”,y);
printf(“z = %f \n”,z);
}
OUTPUT
x = 10.000000
y = 7.000000
z = 4.000000
24 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
25 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
v Else, If one of the operands is unsigned long int, the other will be converted to unsigned
long int and the result will be in unsigned long int.
v Else, if one of the operands is long int and other is unsigned int, then:
(a) if unsigned int can be converted to long int, the unsigned int operand will be converted as
such and the result will be long int.
(b) else, both the operands will be converted to unsigned long int and the result will be unsigned
long int.
v Else, If one of the operands is long int, the other will be converted to long int and the result
will be in long int.
v Else, If one of the operands is unsigned int, the other will be converted to unsigned int and
the result will be in unsigned int.
Casting a Value
C performs type conversion automatically. However, there are instances when we want to force
a type conversion in a way that is different from the automatic conversion.
Eg: 1) ratio = female_number / male_number
Since female_number and male_number are declared as integers the ratio would represent a wrong
figure. Hence it should be converted to float.
ratio = (float) female_number / male_number
The general form of a cast is: (type-name)expression
MATHEMATICAL FUNCTIONS
Mathematical functions such as sqrt, cos, log etc., are the most frequently used ones. To use the
mathematical functions in a C program, we should include the line #include<math.h> in the beginning
of the program.
Function Meaning
Trignometric
acos(x) Arc cosine of x
asin(x) Arc sine of x
atan(x) Arc tangent of x
atan2(x,y) Arc tangent of x/y
cos(x) cosine of x
sin(x) sine of x
tan(x) tangent of x
Hyperbolic
cosh(x) Hyperbolic cosine of x
sinh(x) Hyperbolic sine of x
tanh(x) Hyperbolic tangent of x
Other functions
ceil(x) x rounded up to the nearest integer
exp(x) e to the power x
fabs(x) absolute value of x
floor(x) x rounded down to the nearest integer
26 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
READING A CHARACTER
Reading a single character can be done by using the function getchar. The getchar takes the
following form:
variable_name = getchar();
Eg: char name;
name=getchar();
Program
/*Reading a character from terminal*/
#include<stdio.h>
main()
{
char ans;
printf(“Would you like to know my name? \n”);
printf(“Type Y for yes and N for no”);
ans=getchar();
if(ans ==’Y’ || ans = =’y’)
printf(“\n\n My name is India \n”);
else
printf(“\n\n You are good for nothing \n”);
}
OUTPUT
Would you like to know my name?
Type Y for yes and N for no:Y
My name is India
Would you like to know my name?
Type Y for yes and N for no:n
You are good for nothing
27 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
WRITING A CHARACTER
Like getchar, there is an analogous function putchar for writing characters one at a time to the
terminal. It takes the form as shown below:
putchar (variable_name);
Eg: 1) answer=’y’;
putchar(answer);
will display the character y on the screen.
The statement
putchar(‘\n’);
would cause the cursor on the screen to move to the beginning of the next line.
Program
/*A program to read a character from keyboard and then prints it in
reverse case*/
/*This program uses three new functions:islower,toupper,and tolower.
#include<stdio.h>
#include<ctype.h>
main()
{
char alphabet;
printf(“Enter an alphabet”);
putchar(‘\n’);
alphabet = ghetchar();
if(islower(alphabet))
putchar(toupper(alphabet));
else
putchar(tolower(alphabet));
}
OUTPUT
Enter An alphabet
a
A
Enter An alphabet
Q
q
Enter An alphabet
z
Z
28 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
FORMATTED INPUT
Formatted input refers to an input data that has been arranged in a particular format. The
formatted data can be read with the help of scanf function. The general form of scanf is
scanf(“control string”,arg1,arg2….argn);
The control string specifies the field format in which the data is to be entered and the arguments
arg1,arg2...argn specifies the address of locations where the data are stored. Control strings and
arguments are separated by commas.
Control string contains field specification which direct the interpretation of input data.
It may include
v Field(or format)specifications, consisting of conversion character %, a data type character,
and an optional number, specifying the field width.
v Blanks, tabs, or newlines.
29 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Code Meaning
%c Read a single character
%d Read a decimal integer
%e Read a floating point value
%f Read a floating point value
%g Read a floating point value
%h Read a short integer
%i Read a decimal, hexadecimal, or octal integer
%o Read an octal integer
%s Read a string
%u Read an unsigned decimal integer
%x Read a hexa decimal integer
%[..] Read a string of word(s)
30 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
v The reading will be terminated, when scanf encounters an ‘invalid mismatch’ of data or a
character that is not valid for the value being read.
v When searching for a value, scanf ignores line boundaries and simply looks for the next
appropriate character.
v Any unread data items in a line will be considered as a part of the data input line to the next
scanf call.
v When the field width specifier w is used, it should be large enough to contain the input data
size.
FORMATTED OUTPUT
The printf statement provides certain features that can be effectively exploited to control the
alignment and spacing of print-outs on the terminals.The general form of printf statement is
printf(“control string”,arg1, arg2…argn);
Control string consists of three types of items:
1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.
3. Escape sequence characters such as \n, \t and \b
Output of Integer Numbers
The format specification for printing an integer number is
%wd
Output of Real Numbers
The output of real numbers may be displayed in decimal notation using the following format
specification:
%w.p f
The integer w indicates the minimum number of positions that are to be used for the display of the
value and the integer p indicates the number of digits to be displayed after the decimal point.
We can also display real numbers in exponential notation by using the specification
%w.p e
Printing of Single Character
A single character can be displayed in a desired position using the format The character will be
displayed right-justified in the field of w columns. We can make the display left-justified by placing a
minus sign before the integer w. The default value for w is 1.
Printing of Strings
The format specification for outputting strings is of the form
%wc
%w.ps
31 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
CONTROL STATEMENTS
C language supports the following statements known as control or decision making statements.
1. if statement
2. switch statement
3. conditional operator statement
4. goto statement
CONDITIONAL STATEMENTS
IF STATEMENT
The if statement is used to control the flow of execution of
statements and is of the form
If(test expression)
It allows the computer to evaluate the expression first and then,
depending on whether the value of the expression is ‘true’ or ‘false’, it
transfers the control to a particular statement.
Eg: if(bank balance is zero)
Borrow money
The if statement may be implemented in different forms
depending on the complexity of conditions to be tested.
1. Simple if statement
2. if…..else statement
3. Nested if…..else statement
4. elseif ladder
SIMPLE IF STATEMENT
The general form of a simple if statement is The ‘statement- E.g.
block’ may be a single statement or a group of statement. If the test if(category = = SPORTS)
expression is true, the statement-block will be executed; otherwise the {
statement-block will be skipped and the execution will jump to the marks = marks +
statement-x. bonus_marks;
If(test exprn) }
{ printf(“%f “,marks);
statement-block;
}
statement-x;
32 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
If(test expression)
{
True-block statement(s)
}
else
{
False-block statement(s)
}
statement-x
If the test
expression is true, then the
true block statements are
executed; otherwise the
false block statement will
be executed.
Eg:
………
………
if(code ==1)
boy = boy + 1;
if(code == 2)
girl =girl + 1;
………
………
NESTING OF
IF…..ELSE STATEMENTS
When a series of decisions are
involved, we may have to use more than one
if….else statements, in nested form as
follows.
33 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Program {
/*Selecting the largest of three values*/ if(C > B)
main() printf(“%f \n”,C);
{ else
float A, B, C; printf(“%f \n”,B);
printf(“Enter three values \n”); }
scanf(“|%f %f %f”,&A, &B, &C); }
printf(“\nLargest value is:”);
if(A > B) OUTPUT
{ if(A > C) Enter three values:
printf(“%f \n”,A); 5 8 24
else Largest value is 24
printf(“%f \n”,C);
}
else
34 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Program
/*Use of else if ladder*/
main()
{
int units, cno;
float charges;
printf(“Enter customer no. and units consumed \n”);
scanf(“%d %d”,&cno, &units );
if(units <= 200)
charges = 0.5 * units;
else if(units <= 400)
charges = 100+ 0.65 * (units – 200)
else if (units <= 600)
charges = 230 + 0.8 * (units – 400)
else
charges = 390 + (units – 600);
printf(“\n \ncustomer no =%d,charges =%.2f \n”,cno,charges);
}
OUTPUT
Enter customer no. and units consumed 101 150
Customer no=101 charges = 75.00
35 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
36 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Note: A label can be anywhere in the program, either before or after the goto label; statement.
Eg:
main()
{
double x, y;
read:
scanf(“%f”,&x);
if(x < 0) goto read;
y = sqrt(x);
printf(“%f %f \n”,x, y);
goto read;
}
37 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
The C language provides for three loop constructs for performing loop operations. They are
Ø The while statement
Ø The do statement Eg:
Ø The for statement sum = 0;
n = 1;
THE WHILE STATEMENT while(n <= 10)
The basic format of the while statement is {
while(test condition) sum = sum + n* n;
{ n = n + 1;
body of the loop }
} printf(“sum = %d
The while is an entry–controlled loop statement. The test- \n”,sum);
condition is evaluated and if the condition is true, then the body of the -----------
loop is executed. After 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.
THE DO STATEMENT
In while loop the body of the loop may not be executed at all if Eg:
the condition is not satisfied at the very first attempt. Such situations can -----------
be handled with the help of the do statement do
do {
{ printf(“Input a
body of the loop number\n”);
} number = getnum();
while(test condition); }
Since the test-condition is evaluated at the bottom of the while(number > 0);
loop, the do…..while construct provides an exit-controlled loop and -----------
therefore the body of the loop is always executed at least once.
38 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
v When the body of the loop is executed, the control is transferred back to the for statement
after evaluating the last statement in the loop. Now, the control variable is either incremented or
decremented as per the condition.
Eg 1)
for(x = 0; x <= 9; x = x + 1) Eg: Nesting of For Loops
{ ----------
printf)”%d”,x); ----------
} for(row = 1; row <= ROWMAX; +
printf(“\n”); +row)
{
The multiple arguments in the increment section for(column = 1; column < =
are possible and separated by commas. COLMAX; ++column)
{
Eg 2) y = row * column;
sum = 0; printf(“%4d”, y);
for(i = 1; i < 20 && sum <100; ++i) }
{ printf(“\n”);
sum =sum + i; }
printf(“%d %d \n”,sum); ----------
} ----------
39 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
JUMPS IN LOOPS
C permits a jump from one statement to
another within a loop as well as the jump out of a
loop.
40 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Declaration of Arrays
The general form of array declaration is
type variable-name[size];
The type specifies the type of element that will be contained in the array, such as int, float, or
char and the size indicates the maximum number of elements that can be stored inside the array.
Eg: 1) float height[50];
2) int group[10];
3)char name[10];
Initialization of Arrays
The general form of initialization of arrays is:
static type array-name[size] = {list of values};
Eg:1) static int number[3] = {0,0};
If the number of values in the list is less than the number of elements, then only that many
elements will be initialized. The remaining elements will be set to zero automatically. Initialization of
arrays in C suffers two drawbacks
v There is no convenient way to initialize only selected elements.
v There is no shortcut method for initializing a large number of array elements
like the one available in FORTRAN.
We can use the word ‘static’ before type declaration. This declares the variable as a
static variable.
41 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Eg :
Program
1) static int counter[] = {1,1,1}; /*Program showing one-dimensional array*/
main()
2) {
……… int i;
……… float x[10],value,total;
for(i =0; i < 100; i = i+1) printf(“Enter 10 real numbers:\n”);
{ for(i =0; i < 10; i++)
if i < 50 {
sum[i] = 0.0; scanf(“%f”,&value);
else x[i] = value;
sum[i] = 1.0; }
} total = 0.0;
………. for(i = 0; i < 10; i++)
………. total = total + x[i] * x[i];
printf(“\n”);
TWO-DIMENSIONAL ARRAYS for(i = 0; i < 10; i++)
Two-dimensional arrays are declared as follows printf(“x[%2d] = %5.2f \n”,i+1,x[i]);
type array-name[row_size][column_size]; printf(“\nTotal = %.2f\n”,total);
Eg: product[i][j] = row * column; }
OUTPUT
MULTIDIMENSIONAL ARRAY Enter 10 real numbers:
C allows arrays of three or more 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 10.10
dimensions. The exact limit is determined by the x[1] = 1.10
compiler. The general form of a multidimensional x[2] = 2.20
array is x[3] = 3.30
type array_name[s1][s2][s3]…s[m]; x[4] = 4.40
Eg: 1. int survey[3][5][12]; x[5] = 5.50
2. float table[5][4][5][3]; x[6] = 6.60
3. x[7] = 7.70
x[8] = 8.80
HANDLING OF CHARACTER STRINGS
x[9] = 9.90
x[10] = 10.10
INTRODUCTION
Total = 446.86
A string is a array of characters. Any
group of characters(except the double quote sign)
defined between double quotation marks is a constant string.
Eg: 1) “Man is obviously made to think”
If we want to include a double quote in a string, then we may use it with the back slash.
Eg: printf(“\”well done!\””);
will output
“well done!”
42 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
43 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Program
/*Reading a series of words using scanf function*/
main()
{
char word1[40],word2[40],word3[40],word4[40];
printf(“Enter text:\n”); Reading a Line of Text
scanf(“%s %s”,word1, word2); It is not possible to use scanf
scanf(“%s”, word3); function to read a line containing more
scanf(“%s”,word4); than one word. This is because the scanf
printf(“\n”); terminates reading as soon as a space is
printf(“word1 = %s \n word2 = %s \n”,word1, encountered in the input. We can use the
word2); getchar function repeatedly to read single
printf(“word3 = %s \n word4 = %s \n”,word3, character from the terminal, using the
word4); function getchar. Thus an entire line of
} text can be read and stored in an array.
OUTPUT
Enter text:
Oxford Road, London M17ED Program
Word1 = Oxford /*Program to read a line of text from terminal*/
Word2 = Road #include<stdio.h>
Word3 = London main()
Word4 = M17ED {
Note: Scanf function terminates its char line[81],character;
input on the first white space it finds. int c;
c = 0;
WRITING STRINGS TO SCREEN printf(“Enter text. Press<Return>at end \n”);
We have used extensively the do
printf function with %s format to print {
strings to the screen. The format %s can character = getchar();
be used to display an array of characters line[c] = character;
that is terminated by the null character. c++;
For eg, the statement }
printf(“%s”, name); while(character != ‘\n’);
can be used to display the entire contents c = c-1;
of the array name. line[c] = ‘\0’;
printf(“\n %s \n”,line);
}
OUTPUT
Enter text. Press<Return>at end
Programming in C is interesting
Programming in C is interesting
44 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
45 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
strcpy( ) Function
This function works almost like a string assignment operator. It takes the form
strcpy(string1,string2);
Program OUTPUT
/*Illustration of string-handling functions*/ Enter two string constants
#include<string.h> ? New York
main() Strings are not equal
{ s1 = New York length = 7 characters
char s1[20],s2[20],s3[20]; s2 = York length = 4 characters
int x, l1, l2, l3; s3 = New York length = 7 characters
printf(“Enter two string constants \n”); Enter two string constants
printf(“?”); ? London London
scanf(“%s %s”, s1, s2); Strings are equal
x = strcmp(s1, s2); s1 = London length = 6 characters
if(x != 0) s2 = London length = 6 characters
printf(“Strings are not equal \n”); s3 = London length = 6 characters
strcat(s1, s2);
else
printf(“Strings are equal \n”);
strcpy(s3,s1);
l1 = strlen(s1);
l2 = strlen(s2);
l3 = strlen(s3);
printf(“\ns1 = %s \t length = %d characters \n”,s1, l1);
printf(“\ns2= %s \t length = %d characters \n”,s2, l2);
printf(“\ns3 = %s \t length = %d characters \n”,s3, l3);
}
46 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
CALLING A FUNCTION
A function can be called by simply using the function name in the
statement. Eg:
main()
When the compiler executes a function call, the control is transferred to {
the function mul(x,y).The function is then executed line by line as described int p;
and the value is returned, when a return statement is encountered. This value is p = mul(10,5);
assigned to p. printf(“%d \n”, p);
}
47 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
CATEGORY OF FUNCTIONS
A function may belong to one of the following categories.
1) Functions with no arguments and no return values.
2) Functions with arguments and no return values.
3) Functions with arguments and return values.
48 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
1. The explicit type-specifier, corresponding to the data type required must be mentioned
in the function header. The general form of the function definition is
type specifier function name(argument list)
argument declaration;
{
function statements;
}
2. The called function must be declared at the start of the body in the calling function.
NESTING OF FUNCTIONS
C permits nesting of functions freely. main can call function1,which calls function2,which calls
function3,…..and so on.
RECURSION
When a function in turn calls another function a process of ‘chaining’ occurs. Recursion is a
special case of this process, where a function calls itself.
Eg:
1) main()
{
printf(“Example for recursion”);
main();
}
49 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
50 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
ANSI C FUNCTIONS
The general form of ANSI C function is
data-type function-name(type1 a1,type2 a2,…..typeN aN)
{
--------
-------- (body of the function)
--------
}
Eg: 1) double funct(int a, int b, double c)
Function Declaration
The general form of function declaration is
data-type function-name(type1 a1,type2 a2,…..typeN aN)
Eg:main()
{
float a, b, x;
float mul(float length,float breadth); /*declaration*/
---------
---------
x = mul(a,b);
}
51 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Lesson 10 POINTERS
Outline
Introduction - Understanding Pointers - Accessing the Address of a Variable -
Accessing a Variable through its Pointer - Pointer Expressions - Pointers and Arrays -
Pointers and Character Strings
INTRODUCTION
Pointers are another important feature of C language. Although they may appear a little
confusing for a beginner, they are powerful tool and handy to use once they are mastered.
There are a number of reasons for using pointers.
1. A pointer enables us to access a variable that is defined outside 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.
5. The use of a pointer array to character strings result in saving of data storage space in
memory.
UNDERSTANDING POINTERS
Whenever we declare a variable, the system allocates, somewhere in the memory, an
appropriate location to hold the value of the variable. Since, every byte has a unique address number,
this location will have its own address number.
Consider the following statement:
int quantity = 179;
This statement instructs the system to find a location
for the integer variable quantity and puts the value 179 in
that location. Assume that the system has chosen the
address location 5000 for quantity. We may represent this as
shown below.
Representation of a variable During execution of the
program, the system always associates the name quantity with the address 5000. To access the value
179 we use either the name quantity or the address 5000. Since memory addresses are simply numbers,
they can be assigned to some variables which can be stored in memory, like any other variable. Such
variables that hold memory addresses are called pointers. A pointer is, therefore, nothing but a
variable that contains an address which is a
location of another variable in memory. Since a
pointer is a variable, its value is also stored in the
memory in another location. Suppose, we assign
the address of quantity to a variable p. The link
between the variables p and quantity can be
visualized as shown below. The address of p is
5048.
52 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Pointer as a variable
Since the value of the variable p is the address of the variable quantity, we may access the value
of quantity by using the value of p and therefore, we say that the variable p ‘points’ to the variable
quantity. Thus, p gets the name ‘pointer’.
53 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Once a pointer variable has been declared, it can be made to point to a variable using an
assignment operator such as
p= &quantity;
Before a pointer is initialized it should not be used.
Ensure that the pointer variables always point to the corresponding type of data.
Example:
float a, b;
int x, *p;
p = &a;
b = *p;
will result in erroneous output because we are trying to assign the address of a float variable to an
integer pointer. When we declare a pointer to be of int type, the system assumes that any address that a
pointer will hold will point to an integer variable.
Assigning an absolute address to a pointer variable is prohibited. The following is wrong.
int *ptr;
….
ptr = 5368;
….
….
A pointer variable can be initialized in its declaration itself. For example, int x, *p = &x;
is perfectly valid. It declares x as an integer variable and p as a pointer variable and then initializes p to
the address of x. The statement
int *p = &x, x;
is not valid.
54 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
55 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
The name x is defined as a constant pointer pointing to the first element x[0] and therefore value of x is
1000, the location where x[0] is stored . That is ,
x = &x[0] =1000
Accessing array elements using the pointer
Pointers can be used to manipulate two-dimensional array as well. An element in a twodimensional
array can be represented by the pointer expression as follows:
*(*(a+i)+j) or *(*(p+i)+j)
The base address of the array a is &a[0][0] and starting at this address, the compiler allocates
contiguous space for all the elements, row-wise. That is, the first element of the second row is placed
immediately after the last element of the first row, and so on.
A program using Pointers to compute the sum of all elements stored in an array is presented below:
56 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
57 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
58 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
which can then be used as an argument in another function. A pointer to a function is declared as
follows:
type (*fptr)( );
This tells the compiler that fptr is a pointer to a function which returns type value. A above program to
illustrate a function pointer as a function argument.
59 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
THE PREPROCESSOR
The Preprocessor, as the name implies, is a program that processes the source code before it
passes through the compiler. It operates under the control of preprocessor command lines or directives.
Preprocessor directives are placed in the source program before the main line. Before the source code
passes through the compiler, it is examined by the preprocessor for any preprocessor directives. If there
are any, appropriate actions (as per the directives) are taken and then the source program is handed over
to the compiler.
Preprocessor directives begin with the symbol # in column one and do not require a semicolon
at the end.
Commonly used Preprocessor directives
Directive Function
#define Defines a macro substitution
#undef Undefines a macro
#include specifies the files to be include
# ifdef Tests for a macro definition
#endif specifies the end of #if
#ifndef Tests whether a macro is not defined
#if Tests a compile time condition
#else specifies alternatives when #if fails
Preprocessor directives can be divided into three categories
1) Macro substitution directives
2) File Inclusion directives
3) Compiler control directives
Macro Substitution directive
The general form is #define identifier string
Examples
1) #define COUNT 100 (simple macro substitution)
2) #define CUBE(x) x*x*x ( macro with arguments)
3) # define M 5
#define N M+1 (nesting of macros)
File Inclusion directive
This is achieved by
#include “filename” or #include <filename>
Examples 1) #include <stdio.h>
2) #include “TEST.C”
Compiler control directives
These are the directives meant for controlling the compiler actions. C preprocessor offers a
feature known as conditional compilation, which can be used to switch off or on a particular line or
group of lines in a program. Mostly #ifdef and #ifndef are used in these directives.
60 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Lesson 12 STRUCTURES
Outline
Introduction - Structure Definition - Array Vs Structure - Giving Values to Members -
Structure Initialization - Comparison of Structure Variables - Arrays of Structures
INTRODUCTION
C supports a constructed data type known as structures, a mechanism for packing data of
different types. A structure is a convenient tool for handling a group of logically related data items. For
example, it can be used to represent a set of attributes, such as student _ name, roll _ number and
marks. The concept of a structure is analogous to that of a ‘record’ in many other languages. More
examples of such structures are:
time : seconds, minutes, hours
data : day, month, year
book : author, title, price, year
city : name, country, population
STRUCTURE DEFINITION
Unlike arrays, structure must be defined first for their format that may be used later to declare
structure variables. Let us use an example to illustrate the process of structure definition and the
creation of structure variables. Consider a book database consisting of
book name, author, number of pages, and price. We can define a structure definition
structure to hold this information as follows: struct tag _ name
struct book _bank {
{ data _ type member1;
char title[20]; data _ type member2;
char author[15]; --------- -----
int pages; --------- -----
float price; };
};
The keyword struct declares a structure to hold the
details of four data fields, namely
title, author, pages, and price. These fields are called structure elements or members. Each member may
belong to different type of data. book _ bank is the name of the structure and is called the structure tag.
The tag name may be used subsequently to declare variables that have the tag’s structure.
In defining a structure, we may note the following syntax:
1. The template is terminated with a semicolon.
2. While the entire definition is considered as a statement, each member is declared
independently for its name and type in a separate statement inside the template.
3. The tag name such as book _ bank can be used to declare structure variables of its type, later
in the program.
61 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
ARRAY VS STRUCTURE
1. An array is a collection of related data elements of same type. Structure can have elements of
different types.
2. An array is derived data type whereas structure is a programmer-defined one.
3. Any array behaves like a built-in data type. All we have to do is to declare an array variable
and use it. But in the case of a structure, first we have to design and declare a data structure
before the variables of that type are declared and used.
62 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
STRUCTURE INITIALIZATION
Like any other data type, a structure variable can be initialized at compile time.
main()
{
struct
{
int weight;
float height;
}
student ={60, 180.75};
………
………
}
This assigns the value 60 to student. weight and 180.75 to student. height. There is a one-to-one
correspondence between the members and their initializing values. A lot of variation is possible in
initializing a structure. The following statements initialize two structure variables. Here, it is essential
to use a tag name.
main()
{
struct st _ record
{
int weight;
float height;
};
struct st_record student1 ={60, 180.75};
struct st_record student2 ={53, 170.60};
………
………
}
C language does not permit the initialization of individual structure member within the
template. The initialization must be done only in the declaration of the actual variables.
Operation Meaning
person1 = person2 Assign person2 to person1.
person1 = =person2 Compare all members of person1 and person2 and return 1 if they
are equal, 0 otherwise.
person1 != person2 Return 1 if all the members are not equal, 0 otherwise.
Note that not all compilers support these operations. For example, Microsoft C version
does not permit any logical operations on structure variables. In such cases, individual member can be
63 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
ARRAYS OF STRUCTURES
We use structure to describe the format of a number of related variables. For example, in
analyzing the marks obtained by a class of students, we may use a template to describe student name
and marks obtained in various subjects and then declare all the students as structure variables. In such
cases, we may declare an array of structure, each elements of the array representing a structure
variable. For example,
struct class student[100];
It defines an array called student, that consists of 100 elements. Each elements is defined
to be of the type struct class. Consider the following declaration:
struct marks
{
int subject1;
int subject2;
int subject3;
};
main()
{
static struct marks student[3] ={ {45, 68, 81}, {75, 53, 69}, {57,36,71}};
This declares the student as an array of three elements students[0], student[1], and
student[2] and initializes their members as follows:
student[0].subject1=45;
student[0].subject2=68;
………….
………….
student[2].subject3=71;
An array of structures is stored inside the memory in the same way as a multi- dimensional
array.
64 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
INTRODUCTION
C permits the use of arrays as structure members. We have already used arrays of characters
inside a structure. Similarly, we can use single or multi-dimensional arrays of type int or float. For
example, the following structure declaration is valid:
struct marks
{
int number;
float subject[3];
student[2];
}
Here, the member subject contains three elements, subject [0], subject [1] and subject [2]. These
elements can be accessed using appropriate subscripts. For example, the name student[1].subject[2];
would refer to the marks obtained in the third subject by the second student.
65 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
int dearness;
int house_rent;
int city;
}
allowance;
}
employee;
An inner structure can have more than one variable. The following form of declaration
is
legal:
struct salary
{
……
struct
{
nt dearness;
…….
}
allowance,
arrears;
}
employee[100];
It is also possible to nest more than one type of structures.
struct personal_record
{
struct name_part name;
struct addr_part address;
struct date date _ of _ birth
……..
……..
};
struct personal_record person 1;
The first member of this structure is name which is of the type struct name_part.
Similarly, other members have their structure types.
66 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
UNIONS
Like structures, a union can be declared using the keyword union as follows:
union item
{
int m;
float x;
char c;
} code;
This declares a variable code of type union item. The compiler allocates a piece of storage that
is large enough to hold the largest variable type in the union. To access a union member, we can use the
same syntax that we use for structure members. That is,
code.m
code.x
code.c
are all valid member variables. During accessing, we should make sure that we are accessing
the member whose value is currently stored. For example, the statement such as
code.m = 379;
code.x=7859.36;
printf(“%d”, code.m);
would produce erroneous output.
In effect, a union creates a storage location that can be used by any one of its members at a
time. When a different member is assigned a new value, the new value supercedes the previous
67 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
member’s value.
SIZE OF STRUCTURES
We normally use structures, unions and arrays to create variables of large sizes. The actual size
of these variables in terms of bytes may change from machine to machine. We may use the unary
operator sizeof to tell us the size of a structure. The expression sizeof(struct x) will evaluate the
number of bytes required to hold all the members of the structure x. If y is a simple structure variable
of type struct x, then the expression sizeof(y) would also give the same answer. However, if y is an
array variable of type struct x, then sizeof(y) would give the total number of bytes the array requires.
This kind of information would be useful to determine the number of records in a database. For
example, the expression sizeof(y) / sizeof(x) would give the number of elements in the array y.
BIT FIELDS
C permits us to use small bit fields to hold data items and thereby to pack several data items in a
word of memory. Bit fields allow direct manipulation of string of a string of preselected bits, as if it is
represented an integral quantity. A bit field is a set of adjacent bits whose size can vary from 1 to 16
bits in length. A word can be divided into a number of bit fields. The name and size of bit fields are
defined using a structure.
The general form of bit filed definition is
struct tag-name
{
data-type name1 : bit-length;
data-type name2 : bit-length;
data-type name3 : bit-length;
---------
---------
---------
data-type nameN : bit-length;
}
The data type is either int or unsigned int or signed int and the bit-length is the number of bits
used for the specific name. The bit-length is decided by the range of value to be stored. The largest
value that can be stored is 2n-1, where n is bit-length. The internal representation of bit-field is machine
dependent. It depends on the size of int and the ordering of bits.
Example :
Suppose we want to store and use the personal information of employees in compressed form.
This can be done as follows:
struct personal
{
unsigned sex: 1
unsigned age : 7
unsigned m_status: 1
unsigned children: 3
unsigned : 4
} emp;
68 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
This defines a variable name emp with 4 bit fields. The range of values each filed could have is as
follows:
Bit Filed Bit length Range of values
sex 1 0 or 1
age 7 0 to 127 ( 27 – 1)
m_status 1 0 or 1
children 3 0 to 7 ( 23 – 1)
The following statements are valid :
emp.sex =1 ;
emp.age = 50;
It is important to note that we can not use scanf to read the values in to the bit field.
69 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Lesson 14 FILES
Outline
Introduction - Defining and Opening a File - Closing a File - Input/Output operations on Files
INTRODUCTION
Many real-life problems involve large volumes of data and in such situations, the console
oriented I/O operations pose two major problems.
1. It becomes cumbersome and time consuming to handle large volumes of data through
terminals.
2. The entire data is lost when either the program is terminated or the computer is turned-off.
It is therefore necessary to have a more flexible approach where data can be stored on the disk
and read whenever necessary, without destroying the data. This method employs the concept of files to
store data.
There are two distinct ways to perform file operations in C. The first one is known as the low-
level I/O and uses UNIX system calls. The second method is referred to as the highlevel I/O operation
and uses functions in C’s standard I/O library.
FILE *fp;
fp = fopen(“filename”, “mode”);
70 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
CLOSING A FILE
A file must be closed as soon as all operations on it have been completed. This ensures that all
outstanding information associated with the file is flushed out from the buffers and all links to the file
are broken. It also prevents any accidental misuse of the file. The syntax for closing a file is
fclose( file_pointer);
This would close the file associated with the FILE pointer file_pointer .
Example:
…..
…..
FILE *p1, *p2;
p1 = fopen(“INPUT”, “w”);
p2 = fopen(“OUTPUT” , “r”);
…..
…..
fclose(p1);
fclose(p2);
…..
This program opens two files and closes them after all operations on them are completed. Once
a file is closed, its file pointer can be reused for another file. All files are closed automatically
whenever a program terminates.
71 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Program
/*********************************************************************/
/* WRITING TO AND READING FROM A FILE */
/*********************************************************************/
#include <stdio.h>
main ( )
{
FILE *fp1;
char c;
printf(“Data input\n\n”);
f1 = fopen(“INPUT” , “w” ) /* Open the file INPUT */
while((c = getchar( ))!=EOF) /* Get a character from keyboard */
putc(c,f1) /* Write a character to INPUT */
fclose(f1); /* Close the file INPUT */
printf(“\n Data OUTPUT\n\n”);
f1 = fopen(“INPUT” , “r”) /* Reopen the file INPUT */
while ((c =getc( f1))!=EOF) /* Read a character from INPUT */
printf(“%c”, c); /* Display a character on the screen */
fclose(f1); /* close the file INPUT */
}
Output
Data input Data output
This a program to test the file handling
features in the system ^z This is a program to test the file handling
features in the system
A program to read a series of integer numbers from the file DATA and then write all odd
numbers into the file ODD and even numbers into file EVEN is given below:
72 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Program HANDLING OF INTEGER DATA FILES The fprintf and fscanf functions
#include <stdio.h> The functions fprintf and
main ( ) fscanf perform I/O operations that
{ are identical to the printf and scanf
FILE *f1, *f2, *f3; functions except of course that they
int number, i; work on files. The general form of
printf(“Contents of DATA file\n\n”); fprintf is
f1 = fopen(“DATA”, “w”); /*Create DATA file */
for(i =1; i< =30; i++) fprintf(fp, “control string”, list);
{
scanf(“%d”, &number); The general format of fscanf is
if(number == -1)break;
putw(number,f1); fscanf(fp, “control string”, list);
}
fclose(f`1); Write a program to open a file
f1 = fopen(“DATA” , “r”); named INVENTORY and store in it
f2 = fopen(“ODD” , “w”); the following data:
f3 = fopen(“EVEN”, “w”); (see next page)
while((number = getw(f1))!= EOF) /*Read from DATA file */
{
if(number %2 = = 0)
putw(number,f3); /*Write to EVEN file */
else
putw(number,f2); /*Write to ODD file */
}
fclose(f1);
fclose(f2);
fclose(f3);
f2 = fopen(“ODD” , “r”);
f3 = fopen(“EVEN” , “r”);
printf(“\n\nContents of ODD file \n\n”);
while((number = getw(f2)) != EOF)
printf(“%4d”, number);
printf(“\n\n Contents of EVEN file\n\n”);
while((number = getw(f3)) ! = EOF)
printf(“%4d” , number);
fclose(f2);
fclose(f3);
}
73 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
74 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
75 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
fseek function is used to move the file position to a desired location within the file.
The syntax is
fseek(file ptr, offset, position);
The position can take any one of the following three values:
Value Meaning
0 Beginning of file.
1 Current position.
2 End of file.
The offset may be positive, meaning move forwards, or negative , move backwards. The
following examples illustrates the operation of the fseek function:
Statement Meaning
fseek(fp,0L,0); Go to the beginning .
fseek(fp,0L,1); Stay at the current position.
fseek(fp, 0L,2); Go to the end of the file, past the last character of the file.
fseek(fp,m,0); Move to (m+1)th bytes in the file.
fseek(m,1); Go forward by m bytes.
fseek(fp,-m,1); Go backward by m bytes from the current position.
fseek(fp,-m,2); Go backward by m bytes from the end.
When the operation is successful, fseek returns 0 or if the operation fails it returns –1.
76 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
77 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
INTRODUCTION
Data structure is one of the method of representation of logical relationships between individual
data elements related to the solution of a given problem. Data structure is the most convenient way to
handle data of different data types including abstract data type for a known problem. For example, the
characteristics of a house can be represented by house name, house number, location, number of floors,
number of rooms on each floor etc. Data structure is the base of the programming tools and the choice
of data structure provides the following things:
1. The data structure should be satisfactory to represent the relationship between data elements.
2. The data structure should be easy so that the programmer can easily process the data, as per
requirement.
Data structures have been classified in several ways as outlined below:
Linear: In the linear method, values are arranged in a linear fashion. An array, linked list, stacks
and queues are examples of linear data structure in which values are stored in a sequence. There
is a relation between the adjacent elements of a linear list.
Non-linear: This is just opposite to linear. The data values in this structure are not arranged in
order. Tree, graph, table and sets are examples of nonlinear data structure.
Homogenous: In this type of data structure, values of same data types are stored. An example
of it can be an array that stores similar data type elements having different locations for each
element of them.
78 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Non-homogenous: In this type, data values of different types are grouped like in structure and
classes.
Dynamic: In dynamic data structure like references and pointers, size and memory locations
can be changed during program execution.
Static: A static keyword in C/C++ is used to initialize the variable to 0(NULL). Static variable
value remains in the memory throughout the program. Value of the static variable persists. In
C++, a member
function can be declared as static and such a function can be invoked directly.
IMPLEMENTATION OF A LIST
There are two methods to implement the list: They are classified as Static and Dynamic.
Static implementation: Static implementation can be achieved using arrays. Though it is a very simple
method, it has a few limitations. Once the size of an array is declared, its size cannot be altered during
program execution. In array declaration, memory is allocated equal to array size. Thus, the program
itself decides the amount of memory needed and it informs accordingly to the compiler. Hence memory
requirement is determined in advance before compilation and the compiler provides the required
memory. Static allocation of memory has a few disadvantages. It is an inefficient memory allocation
technique. It is suitable only when we exactly know the number of elements to be stored.
Dynamic implementation: Pointers can also be used for implementation of a stack. The linked list is
an example of this implementation. The limitations noticed in static implementation can be removed
using dynamic implementation. The dynamic implementation is achieved using pointers. Using pointer
implementation at run time there is no restriction on number of elements. The stack may be expanded.
It is efficient in memory allocation because the program informs the compiler its memory requirement
at run time. Memory is allocated only after an element is pushed.
TRAVERSAL OF A LIST
A simple list can be created using an array in which elements are stored in successive memory
locations. The following program is an example. Given below is a program to create a simple list of
elements. The list is displayed in original and reverse order.
#include <stdio.h> for(j=0; j<5; j++)
#include <conio.h> printf(“%d”, sim[j]);
main() printf(“\n Reverse List :”);
{ for(j=4; j>=0; j--)
int sim[5],j; printf(“%d”,sim[j]); }
clrscr();
printf(“\n Enter five elements :”); OUTPUT
for(j=0; j<5; j++) Enter five elements: 1 5 9 7 3
scanf(“%d”, &sim[j]); List : 1 5 9 7 3
printf(“\n List :”); Reverse list: 3 7 9 5 1
Explanation: In the above program, using the declaration of an array a list is implemented. Using for
loop and scanf() statements five integers are entered. The list can be displayed using the printf()
statement. Once a list is created, various operations such as sorting and searching can be applied.
79 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
The above diagram shows the predecessor and successor elements of number 10.
80 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
The following program displays the predecessor and successor elements of the entered element from
#include<stdio.h> break;
#include<conio.h. }
main() k++;
{ }
int num[8], j, n, k=0, f=0; if(f = = 0)
clrscr(); printf(“\n The element % d is not found in list”,
printf(“\n Enter eight elements :
OUTPUT
for(j=0; j<8; j++) Enter eight elements :
scanf(“%d”, &num[j]); 1 2 5 8 7 4 46
printf(“\n Enter an element :”); Enter an element : 5
scanf(“%d”, &n); The predecessor of 5 is 2
for(j=0; j<8; j++) The successor of 5 is 8
{ Enter eight elements :
if (n= = num[j]) 12345678
{ Enter an element:1
f=1; No predecessor
(j>0) ? printf(“\n The predecessor of %d The successor of 1 is 2
is %d”, num[j],num[j-1]); Enter eight elements:
printf(“ No predecessor”); 12 34 54 76 69 78 85 97
(j= =7) ? printf(“\n No successor”); Enter an element : 3
printf(“\n The successor of %d is %d”, The element 3 is not found in the list.
num[j], num[j+1]);
the list. Program to find the predecessor and successor of the entered number in a list.
INSERTION
When a new element is added in the list it called as appending. However, when an element is
added in between two elements in the list, then the process is called as insertion. The insertion can be
done at the beginning, inside or anywhere in the list. For successful insertion of an element, the array
implementing the list should have at least one empty location. If the array is full, insertion cannot be
possible. The target location where element is to be inserted is made empty by shifting elements
downwards by one position and the newly inserted element is placed at that location.
81 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Insertion
There are two empty spaces available. Suppose we want to insert 3 in between 7 and 9. All the
elements after 7 must be shifted towards end of the array. The entered number 3 can be assigned to that
memory location .The above example describes the insertion of an element.
The following program illustrates the insertion operation
#include<stdio.h> sacnf(“%d %d”, &p,&n);
#include<conio.h.> --p; }
#include<process.h> else
main() while(num[k]!=0)
{ k++;
int num[8]={0}, j, k=0, p, n; k--;
clrscr(); for(j=k;j>=p;j--)
printf(“\n Enter elements (0 to exit) : ” ); num[j+1]=num[j];
for(j=0; j<8; j++) num[p]=n;
{ for(j=0;j<8;j++)
scanf(“%d” , &num[j]); printf(“%d’, num[j]);
if( num[j]= =0) }
break; OUTPUT
} Enter elements(0 to Exit): 1 2 3 4 5 6 0
if(j<8) Enter position number and element: 5 10
{ 1 2 3 4 10 5 6 0
printf(“\n Enter position number and element :”);
DELETION
Like insertion, deletion of an element can be done from the list. In deletion, the elements are moved
upwards by one position.
Explanation:
In the above program, elements are entered by the user. The user can enter maximum eight elements.
82 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
The element which is to be removed is also entered. The while loop calculates the position of the
element in the list. The second for loop shifts all the elements next to the specified element one position
up towards the beginning of the array. The element which is to be deleted is replaced with successive
elements.
SORTING
Sorting is a process in which records are arranged in ascending or descending order. The
records of the list of these telephone holders are to be sorted by the name of the holder. By using this
directory, we can find the telephone number of any subscriber easily. Sort method has great importance
83 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Lesson 18 STACK
Outline
Introduction – Stack - Representation and terms – Operations – Insertion -
Deletion – Implementations
INTRODUCTION
There are two common data objects found in computer algorithm called stacks and queues Data
objects in an ordered list is A(a1,a2,……an) where n>=0 and ai are the atoms taken from the set. If the
list is empty or Null then n=0.
STACK
Stack is an array of size N, where N is an unsigned integer. It is an ordered list in which all
insertions and deletions are made at one end called TOP.
STACK OPERATIONS
CREATE (S) ß Creates an empty stack
ADD (i,S) ß Add i to rear of stack
DELETE (S) ß Removes the top element from stack
FRONT (S) ß Returns the top element of stack.
ISEMT(S) ß returns true if stack is empty else false.
84 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
INSERTION OPERATION
CREATE ( ) : = declare Stack(1:n) ,top<- 0
ISEMTS (S) =If TOP=0 then true else false.
TOP(S) = if top= 0 then error else stack (top)
ADD & DELETE operations are implemented as,
Procedure ADD (item, stack,n,top)
If top >=n then call stack-Full
Top<- top + 1
Stack (top) <- item
End ADD.
DELETION OPERATION
Procedure DELETE (item, stack,top)
If top <=0 then call stack-empty
Item <- stack(top)
Top<- top-1
End delete.
IMPLEMENTATION OF A STACK
The stack implementation can be done in the following ways:
Static implementation: Static implementation can be achieved using arrays. Though, it is a very
simple method, but it has few limitations. Once the size of an array is declared, its size cannot be altered
during program execution. While in array declaration, memory is allocated equal to array size. The vacant
space of stack (array) also occupies memory space. Thus, it is inefficient in terms of memory utilization. In
both the cases if we store less argument than declared, memory is wasted and if we want to store more
elements than declared, array could not expand. It is suitable only when we exactly know the number of
elements to be stored.
Elements are entered stored in the stack .The element number that is to be deleted from the stack
will be entered from keyboard. Recall that in a stack, before deleting any element, it is
compulsory to delete all elements before that element. In this program the elements before a target element
are replaced with value NULL(0). The elements after the target element are retained. Recall that when an
element is inserted in the stack the operation is called ’push’, When an element is deleted from the stack
then the operation is pop.
The push() operation inserts an element into the stack. The next element pushed() is displayed after
the first element and so on. The pop() operation removes the element from the stack. The last element
inserted is deleted first.
85 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
INTRODUCTION
Data representation have the property that successive nodes of data object were stored at a fixed
distance. Thus,
(i) if element aij table stored at the location Lij
(ii) if the ith node in a queue at location Li.
(iii) if the top most node of the stack will be at the location Lt.
When a sequential mapping is used for ordered list, operations like insertion and deletion becomes
expensive.
For eg., consider some English words. Three letter word ending with “AT” like BAT, CAT, EAT,
FAT, HAT,……….,WAT. If we want to add GAT in the list we have to move BAT,CAT…..,WAT. If we
want to remove the word LAT then delete many from the list.The problem is list having varying sizes,
so sequential mapping is in adequate. By storing each list with maximum size storage space may be
wasted. By maintaining the list in a single array large amount of data movement is needed. The data
object polynomial are ordered by exponent while matrices ordered rows and columns. The alternative
representation to minimize the time needed for insertion and deletion is achieved by linked
representation.
Both header and rear are initialized the address of the first node.
The statement would be
Header=first;
Rear=first;
3. The address of pointer first is assigned to pointers header and rear. The rear is used to identify
the end of the list and to detect the NULL pointer.
86 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
4. Again, create a memory location, suppose 1890, for the successive node.
node node->next
5.Join the element of 1890 by assigning the value of node rear->next. Move the rear pointer to
the last node.
Header: The pointer header is very useful in the formation of a linked list. The address of first
node(1888) is stored in the pointer header. The value of the header remains unchanged until it turns out
to be NULL. The starting location of the list ca only be determined by the pointer header.
While ( header!=NULL)
{
printf(“%d”, header->num);
header=header->next;
}
87 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Adjusting pointers: The insertion operation changes the sequence. Hence, according to the
sequence, the address of the next element is assigned to the inserted node. The address of the
current node (inserted) is assigned to the previous node.
The node can be inserted in the following positions in the list.
Insertion of the node at the starting: The created node is inserted before the first element.
After insertion, the newly inserted element will be the first element of the linked list. In this
insertion only the contents of the successive node’s pointer are changed.
Insertion at the end of the list: A new element is appended at the end of the list. This is easy
as compared to other two (a) and (c) operations. In this insertion only the contents of the
previous node’s pointer are changed.
Insertion at the given position in the list: In this operation, the user has to enter the position
number. The given pointer is counted and the element is inserted. In this insertion contents of
both the previous and next pointers are altered.
88 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
89 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
In figure (a) linked list elements are shown. The element 3 is to be deleted. After deletion the linked
list would be shown as in figure(b).
Deleting a node from the list has the following three cases.
1. Deleting the first node
2. Deleting the last node
3. Deleting the specific node
While deleting the node, the node which is to be deleted is searched first. If the first node is to be
deleted, then the second node is assigned to the header. If the last node is to be deleted, the last but one
node is accessed and its link field is assigned a NULL value. If the node which is to be deleted is in
between the linked list, then the predecessor and successor nodes of the specified node are accessed
and linked.
90 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
INTRODUCTION
The doubly linked list has two link fields one linking in forward direction and another one in
backward direction.
It has one special node called head node. It may or may not be Circular. An empty list is not really empty since it
will always have its head node.
Insert algorithm:
Procedure DINSERT (P,X)
(insert node p to right of node x)
LLINK (P) ß X
RLINK (P) ß RLINK (X) (set LLINK & RLINK of nodes)
LLINK (RLINK (X) ß P
End Dinsert
Delete algorithm:
Procedure DDELETE (X,L)
If X=L then no more nodes (L ß list)
RLINK ( LLINK (X) ) ß RLINK (X)
LLINK ( RLINK(X) ) ß LLINK(X)
Call RET (x)
End DDelete
91 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
INSERTION
Insertion of an element in the doubly linked list can be done in three ways.
1. Insertion at the beginning
2. Insertion at the specified location
3. Insertion at the end
Insertion at the beginning: The process involves creation of a new node, inputing data and adjusting
the pointers.
Insertion at the end or a specified position: An element can be inserted at a specific position in the
linked list.The following program can be used to insert an element at a specific position.
int addafter(int n, int p)
{
struct doubly *temp, *t;
int j;
t= first;
for(j=0;j<p-1;j++)
{
t=t-next;
if(t= =NULL)
{
printf(“\n There are less than %d element:”,p);
return 0;
92 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
}
temp=(struct doubly*) malloc(sizeof(struct doubly));
temp->next=t->next;
temp->number=n;
t->next=temp;
return 0;
}
DELETION
An element can be removed from the linked list by an operation called deletion. Deletion can be
done at the beginning or at a specified position.
In the deletion process the memory of the node to be deleted is released using free( ) function.
The previous and next node are linked.
93 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
94 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
QUEUES
Queues ignore the existence of priority. There are two different ends called FRONT and REAR
end. Deletions are made from the FRONT end. If job is submitted for execution it joins at the REAR
end. job at the front of queue is next to be executed.
Queue is an common data objects found in computer algorithm. In queue the insertions are
made at one end called rear and the deletion at one end called front. Queue follows the FIFO basis
(First in First Out).
Deletions are made from the Front end and joins at the REAR end. Job at the FRONT of queue
is next to be executed. Some operations performed on queues are:
CREATE Q (Q) ß Creates an empty queue
ADD (i,Q) ß Add i to rear of queue
DELETE (Q) ß Removes the front element
FRONT (Q) ß Returns the front element of queue.
ISEMTQ ß returns true if queue is empty else false.
OPERATIONS OF A QUEUE
Add procedure on a queue:
Procedure ADDQ (item , Q, n, rear)
If rear = n then Queue- full
Rear <- rear +1
Q(rear) <- item
end ADDQ.
Delete Procedure of Queue:
Procedure DELETE Q(item, Q, Front)
If front = rear then queue –empty
Front <- front +1
Item <- Q(front)
End DeleteQ
95 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
SEARCHING
The searching of an item starts from the first item and goes up to the last item until the expected
item is found. An element that is to be searched is checked in the entire data structure in a sequential
way from starting to end. Sorting is a term used to arrange the data items in an order.
The searching methods are classified into two types as Linear search and Binary search
methods.
LINEAR SEARCH
The linear search is a usual method of searching data. The linear search is a sequential search. It
is the simple and the easiest searching method. An element that is to be searched is checked in the
entire data structure in a sequential way from starting to end. Hence, it is called linear search. Though,
it is straight forward, it has serious limitations. It consumes more time and reduces the retrieval rate of
the system. The linear or sequential name implies that the items are stored in a systematic manner. The
linear search can be applied on sorted or unsorted linear data structure.
The number of iterations for searching depends on the location of an item. If it were located at
first position then the number of iteration required would be 1. Here, least iterations would be needed
hence, this comes under the best case. In case the item to be searched is observed somewhere at the
middle then the number of iterations would be approximately N/2, where N is the total number of
iterations. This comes under average number of iterations. In the worst case to search an item in a list,
N iterations would be required provided the expected item is at the end of the list.
Next to linear and sequential search the better known methods for searching is binary search.
This search begins by examining the record in the middle of file rather at any one end. It takes 0(log
n)time for the search. It begins by examining the record in the middle of file rather at any one end. File
being searched is ordered by non-decrementing values of the key.
Based on the result of comparison with the middle key km one of the following conclusion is
obtained.
a. If k < km record being searched in lower half of the file.
b. If k=km is the record which is begin searched for.
c. If k>km records begin searched in upper half of the file.
After each comparison either it terminates successfully or the size of the file searching is
reduced to one half of the original size. 0(log2n). The file be examined at most [(n/2)^k] where n is the
number of records , k is key. In worst case this method requires 0(logn) comparisons.
Always in binary search method the key in the middle of subfile is currently examined. Suppose
there are 31 records. The first tested is k16 because[(1+31)/2]=16. If k is less than k16 then k8 is tested
next because [(1+15)/2]=8 or if k>k16 then k24 is tested & it is repeated until the desired record is
reached.
96 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
97 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Lesson 22 SORTING
Outline
Introduction – Sorting - Comparison with other method
INTRODUCTION
Sorting is an important phenomenon in the programming domain. If large volumes of records
are available, then sorting of them becomes very crucial. If the records are sorted either in ascending or
descending order based on keys, then searching becomes easy.
SORTING
Sorting is a process in which records are arranged in ascending or descending order. In real life
we come a cross several examples of such sorted information. For example, in a telephone directory the
names of the subscribers and their phone numbers are written in ascending alphabets. The records of
the list of these telephone holders are to be sorted by their names. By using this directory, we can find
the telephone number and address of the subscriber very easily. The sort method has great impact on
data structures in our daily life.
For example, consider the five numbers 5,9,7,4,1.
The above numbers can be sorted in ascending or descending order.
The representations of these numbers in
Ascending order (0 to n): 1 4 5 7 9
Descending order (n to 0): 9 7 5 4 1
Similarly, alphabets can be sorted as given below.
Consider the alphabets B, A, D, C, E. These are sorted in
Ascending order (A to Z): A B C D E
Descending order (Z to A): E D C B A.
INSERTION SORT
In insertion sort an element is inserted at the appropriate place. Here the records must be sorted
from R1,R2,…….Rn in non – decreasing value of the key k. Assume n is always greater than 1.
Algorithm:
Procedure INSORT(R,N) ordered sequence is also ordered on key K.
K0← -α Assume that R0 is a dummy record such
For I ←2 TO N DO that K>=K0)
T ← RJ j←I
Call INSERT (T,J-1) while K<kj do
END {for} Rj+1 ← Rj
END {INSORT} J← j-1
Procedure INSERT (R,I) END {while}
(Insert record R with key K into the ordered Rj+1 ← R
sequence such that resulting End {insert}
98 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
case 1:
K0 ← -α
for j ← 2 to 6 do
T ← R2
Call Insert (R2,1)
Procedure insert (R,I)
j←I i←1 (i.e.) j=1
while K<kj do
3<5 (True)
R2←R1
j←1-1 = 0 (ie.-j=0)
end {while}
R0+1←R
R1←R
R1 ← 3 (ie.R1=3)
SELECTION SORT
The selection sort is nearly same as exchange sort. Assume we have a list containing n
elements. By applying selection sort, the first element is compared with remaining (n-1) elements. The
smallest element is placed at the first location. Again, the second element compared with the remaining
(n-2) elements. If the item found is lesser than the compared elements in the remaining n-2 list than the
swap operation is done. In this type, the entire array is checked for the smallest element and then
swapped.
In each pass, one element is sorted and kept at the left. Initially the elements are temporarily
sorted and after next pass, they are permanently sorted and kept at the left. Permanently sorted elements
are covered with squares and temporarily sorted with encircles. Element inside the circle ‘O’ is chosen
for comparing with the other elements marked in a circle and sorted temporarily. Sorted elements inside
the square ‘y’ are shown.
Time Complexity
The performance of sorting algorithm depends upon the number of iterations and time to
compare them. The first element is compared with the remaining n-1 elements in pass 1. Then n-2
elements are taken in pass 2. This process is repeated until the last element is encountered. The
mathematical expression for these iterations will be equal to (n-1) + (n-2) +…..+ (n-(n-1)). Thus the
expression becomes n*(n-1) / 2. Thus the number of comparisons is proportional to (n2). The time
complexity of selection sort is O (n2).
99 | A. T h o t t a r a y a s w a m y M. C.A, M.P h i l
| DATA STRU CT URES AN D C PR O G RA M M I N G
Consider the elements 2, 6, 4, 8 and 5 for sorting under selection sort method.
1. In pass 1, select element 2 and check it with the remaining elements 6, 4, 8 and 5. There is no
smaller value than 2, hence the element 2 is placed at the first position.
2. Now, select element 6 for comparing with remaining (n-2) elements i.e., 4, 8, and 5. The
smaller element is 4 than 6. Hence we swap 4 and 6 and 4 is placed after 2.
3. Again we select the next element 6 and compare it with the other two elements 8, 5 and
swapping is done between 6 and 5.
4. In the next pass element 8 is compared with the remaining one element 6. In this case, 8 is
swapped with 6.
5. In the last pass the 8 is placed at last because it is highest number in the list.
INTRODUCTION
Bubble sort is a commonly used sorting algorithm and it is easy to understand. In this type, two
successive elements are compared and swapping is done if the first element is greater than the second
one. The elements are sorted in ascending order. Though it is easy to understand, it is time consuming.
The quick sort method works by dividing into two partitions.
BUBBLE SORT
The bubble sort is an example of exchange sort. In this method comparison is performed
repetitively between the two successive elements and if essential swapping of elements is done. Thus,
step-by-step the entire array elements are checked. It is different from the selection sort. Instead of
searching the minimum element and then applying swapping, two records are swapped instantly upon
noticing that they are not in order.
Let us consider the elements 9, 5, 1, 4 and 3 for sorting under bubble sort.
1. In pass 1, first element 9 is compared with its next element 5.The next element is
smaller than the 9. Hence, it is swapped. Now the list is 5, 9, 1, 4, 3 again the 9 is
compared with its next element 1 the next element is smaller than the 9 hence swapping
is done. The same procedure is done with the 4 and 3 and at last we get the list as 5, 1, 4,
3, 9.
2. In pass 2, the elements of pass 1 are compared. The first element 5 is compared with
its next element 1.5 and 1 are swapped because 1 is smaller than 5. Now the list becomes
1, 5, 4, 3, 9. Next, 5 is compared with element 4. Again, the 5 and 4 are swapped. This
process is repeated until all successive
elements are compared and if the succeeding number is smaller than the present number
then the numbers are swapped. The final list at the end of this pass is 1, 4, 3, 5, 9.
3. In pass 3, the first element 1 is compared with the next element 4. The element 4 is
having the higher value than the first element 1, hence they remain at their original
positions. Next 4 is compared with the subsequent element 3 and swapped due to smaller
value of 3 than 4.
TIME COMPLEXITY
The performance of bubble sort in worst case is n(n-1)/2. This is because in the first pass n-1
comparisons or exchanges are made; in the second pass n-2 comparisons are made. This is carried out
until the last exchange is made. The mathematical representation for these exchanges will be equal to
(n-1) + (n-2) +…. + (n(n-1)). Thus the expression becomes n*(n-1)/2.
Thus, the number of comparisons is proportional to (n2). The time complexity of bubble sort is
0 (n2).
QUICK SORT
It is also known as partition exchange sort. It was invented by C A R Hoare. It is based on
partition. Hence, the method falls under divide and conquer technique. The main list of element is
divided into two sub-lists. For example, suppose lists of X elements are to be sorted. The quick sort
marks an element in a list called as pivot or key. Consider the first element J as a pivot. Shift all the
elements whose value is less than J towards the left and elements whose value is grater than J to right
of J. Now, the key element divides the main list in to two parts. It is not necessary that selected key
element must be at middle. Any element from the list can act as key element. However, for best
performance is given to middle elements. Time consumption of the quick sort depends on the location
of the key in the list.
Consider the following example in which five elements 8, 9, 7, 6, 4 are to be sorted using quick sort.
Consider pass 1 under which the following iterations are made. Similar operations are done in
pass 2, pass 3, etc.
In iteration 1 the first element 8 is marked as pivot one. It is compared with the last element
whose value is 4. Here 4 is smaller than 8hence the number are swapped. Iteration 2 shows the
swapping operation.
In the iteration 3 and 4, the position of 8 is fixed. In iteration 2, 8 and 9 are compared and
swapping is done after Iteration 2.
In iteration 3, 8 and 6 are compared and necessary swapping is done. After this, it is impossible
to swap. Hence, the position of 8 is fixed. Because of fixing the position of 8 the main list is
divided into two parts. Towards left of 8 elements having smaller than 8 are placed and towards
the right greater than 8 are placed.
Towards the right of 8 only one element is present hence there is no need of further swapping.
This may be considered under Pass2.
However towards the left of 8 there are three elements and these elements are to be swapped as
per the procedure described above. This may be considered under Pass3.
TIME COMPLEXITY
The efficiency of quick sort depends upon the selection of pivot. The pivot can bifurcate the list
into compartments. Sometimes, the compartments may have the same sizes or dissimilar sizes. Assume
a case in which pivot is at middle. Thus, the total elements towards lift of it and right are equal. We can
express the size of list with the power of 2. The mathematical representation for the size is n=2 s. The
value of s can be calculated as log2n.
After the first pass is completed there will be two compartments having equal number of
elements that is, n/2 elements are on the left side as well as right side. In the subsequent pass, four
portions are made and each portion contains n/4 elements. In this way, we will be proceeding further
until the list is sorted. The number of comparisons in different passes will be as follows.
Pass 1 will have n comparisons. Pass 2 will have 2*(n/2) comparisons. In the subsequent passes
will have 4*(n/4), 8*(n.8) comparisons and so on. The total comparisons involved in this case would be
O(n)+O(n)+O(n)+…..+s.
The value of expression will be O (nlog n).Thus time complexity of quick sort is O(n log n).
INTRODUCTION
If the nodes in the binary tree are in specific prearranged order, then heap sorting method can be
used. A Heap is defined to be a complete binary tree with a property that the value of each node is at
least as large as the value of its children nodes.
TREE SORT
In binary tree, we know that the elements are inserted according to the value greater or less in
between node and the root in traversing. If the value is less than traversing node then, insertion is done
at left side. If the value is greater than traversing node, it is inserted at the right side. The elements of
such a tree can be sorted. This sorting involves creation of binary tree and then in order traversing is
done.
HEAP SORT
In heap sort, we use the binary tree, in which the nodes are arranged in specific prearranged
order. The rule prescribes that each node should have bigger value than its child node. The following
steps are to be followed in heap sort.
1. Arrange the nodes in the binary tree form.
2. Node should be arranged as per specific rules.
3. If the inserted node is bigger than its parent node then replace the node.
4. If the inserted node is lesser than its parent node then do not change the position.
5. Do not allow entering nodes on right side until the child nodes of the left are fulfilled.
6. Do not allow entering nodes on left side until the child nodes of the right are fulfilled.
7. The procedure from step 3 to step 6 is repeated for each entry of the node.
Consider the numbers 56, 23, 10, 99, 6, 19, 45, 45, 23 for sorting using heap. Sorting process is shown
in the below figure.
1. At first, we pick up the first element 56 from the list. Make it as the root node.
2. Next, take the second element 23 from the list. Insert this to the left of the root node 56. Refer
to Fig. 16.7(2).
3. Then take the third element 10 from the list for insertion. Insert it to the right of the root
node.
4. Take the fourth element 99. Insert it to the left side of node 23. The inserted element is
greater than the parent element hence swap 99 with 23. But the parent node 56 is smaller than
the child node 99 hence 99 and 56 are swapped. After swapping 99 becomes the root node.
5. Consider the next element 6 to insert in the tree. Insert it at the left side. There exists a left
node hence insert it to the right of 56.
6. Element 19 is inserted to the right side of 99 because the left side gets full. Insert the element
19 to the right side of node 10. However, the parent element is lesser than the child hence swap
19 with 10.
7. Now element 45 is to be inserted at the right side of 19. However, the parent element is
having value lesser than the child element hence swap 45 with19.
8. Now the right side is fully filled hence add the next element 45 to the left. The element 45 is
inserted at the last node of left i.e., 23. However, the parent element is having value lesser than
the child element hence swap 45 with 23.
9. Insert the last element 23 to the left side node i.e. 45. The left of 45 is already filled hence
insert element 23 at the right of 45. 10. At last, we get a sorted heap tree.
:: REFERENCES
• Programming and Data Structures by Ashok N Kamthane – Pearson Education, First Indian
Print 2004, ISBDN 81-297-0327-0.
• Programming in ANSI C by E. Balagurusamy, Tata McGraw-Hill, 1998.
• Data Structure using C by Aaron M Tanenbaum, Yedidyeh langsam, Moshe J Augenstein - PHI
PUB.
• Fundamentals of Data Structure by Ellis Horowitz and Sartaj Sahni - Galgotia Book Source.
• The C programming languageBy Brian W. Kernighan, Dennis M. Ritchie
• C programming FAQs: frequently asked questions By Steve Summit
• Expert C programming: deep C secrets By Peter Van der Linden
• C programming: the essentials for engineers and scientists By David R. Brooks
• C programming By Larry Edward Ullman, Marc Liyanage
• C programming for the absolute beginner: the fun way to learn programming By Michael A. Vine
• C programming guide By Jack Jay Purdum
• Advanced Data Structures by Peter Brass
• Data Structures and Algorithms by Alfred V. Aho, Jeffrey D. Ullman, and John E. Hopcroft
• Data Structures and Their Algorithms by Harry R. Lewis and Larry Denenberg
• Data Structures Using C by Aaron M. Tenenbaum
• Schaum's outline of theory and problems of programming with C By Byron S. Gottfried
• Advanced C Struct Programming: Data Structure Design and Implementation in C by John W. L.
Ogilvie
• Data Structures: A Pseudocode Approach With C by Richard F. Gilberg and Behrouz A. Forouzan
• Data Structures Using C by Aaron M. Tenenbaum
• C Programming with Data Structures by T. Sudha and B. Poornima
• Practical Data Structures Using C/C++ by James L. Antonakos and Kenneth C. Mansfield
• An Introduction to Data Structures and Algorithms (Progress in Theoretical Computer Science) by
J.A. Storer and John C. Cherniavsky
• Data Structures and Program Design in C++ by Robert L. Kruse and Alex Ryba
• Data Structures and Abstraction Using C by Geoff Whale
• DATA-STRUCTURES AND PROGRAMMING by Malcolm C. Harrison
• Algorithms and Data Structures: An Approach in C by Charles F. Bowman
• Data Structures and C. Programmes by Christopher J. Van Wyk
• Data Structure for C Programming by Kumar Ajay
:: APPENDICES
BHARATHIAR UNIVERSITY B.Sc. COM.SCI DEGREE COURSE SYLLABUS
CORE 3 : DATA STRUCTURES AND C PROGRAMMING
Subject Description:
This subject deals with the methods of data structures using C programming language.
Goal: To learn about C programming language using data structural concepts.
Objective:
On successful completion of this subject the students should have writing programming ability on
data structures dealing with Stacks, Queues, List, Searching and Sorting algorithms etc.,
UNIT I:
Programming development methodologies Programming style Problem solving techniques:
Algorithm, Flowchart, Pseudocode - Structure of a C program C character set Delimiters
Keywords Identifiers Constants Variables Rules for defining variables Data types
Declaring and initializing variables Type conversion. Operators and Expressions Formatted and
Unformatted I/O functions Decision
statements Loop control statements.
UNIT II:
Arrays String and its standard functions. Pointers Functions Preprocessor directives: #define,
#include, #ifndef, Predefined macros.
UNIT III:
Structure and Union: Features of structure, Declaration and initialization of structure, Structure
within structure, Array of structure, Pointer to structure, Bit fields, Enumerated data types, Union.
Files: Streams and file types, Steps for file operation, File I/O, Structures read and write, other file
functions, Command line arguments, I/O redirection.
UNIT IV:
Linear data structures: Introduction to data structures List: Implementations, Traversal, Searching
and retrieving an element, Predecessor and Successor, Insertion, Deletion, Sorting, Merging lists
Stack: Representation, Terms, Operations on stack, Implementation.
Single linked list, Linked list with and without header, Insertion, Deletion, Double linked list
Queues: Various positions of queue, Representation
UNIT V:
Searching and Sorting Searching: Linear, Binary. Sorting Insertion, Selection, Bubble, Quick,
Tree, Heap.
section B (5x6=30Marks)
11. a. Explain the structure of a C Program. Or
b. Write a C program to find the sum of the digits of an integer number.
12. a. Discuss about functions in C. Or
b. Write a C program to find the sum of the n given numbers using pointer.
13. a. Write about enumerated data types. Or
b. Discuss on I/O redirection.
14. a. Write about inserting an element into the stack. Or
b. Discuss on deleting an element in a single linked list.
15. a. Explain binary search algorithm. Or
b. Sort the following numbers using selection sort.
81, 17, 12, 32, 45
section C (5X12=60Marks)
16. a. Discuss the following:
i. Data types (3 marks)
ii. Declaring and initializing variables (3 marks)
iii. Type conversion (4 marks)
iv. Formatted I/O (2 marks) Or
b. Write a C program to find the sum of even numbers from 2 to 100.
17. a. Explain about arrays in C. Or
b. Write a C program to find whether a given number is available in a given set of numbers (or) not.
18. a. Explain the following:
BHARATHIAR UNIVERSITY
B.Sc. COMPUTER SCIENCE DEGREE COURSE
CORE LAB-2: PROGRAMMING LAB C (DATA STRUCTURES)
PRACTICAL LIST
• 1. Write a C program to create two array list of integers. Sort and store the elements of both of
them in the third list.
• 2. Write a C program to experiment the operation of STACK using array implementation.
• 3. Write a C program to create menu driven program to implement QUEUE to perform
the following:
(i) Insertion
(ii) Deletion
(iii) Modification
(iv) Listing of elements using points
• 4. Write a C program to create LINKED LIST representation of employee records and do the
following operations using pointers:
a. To add a new record
b. To delete an existing record
c. To print the information about an employee
d. To find the number of employees in the structure.
• 5. Write a C program to count the total nodes of the linked list.
• 6. Write a C program to insert an element at the end of the linked list.
• 7. Write a C program to insert an element at the beginning of the Double linked list.
• 8. Write a C program to display the hash table, which is to be prepared by using the Mid-square
method.
• 9. Write a C program to demonstrate Binary search.
• 10. Write a C program to insert nodes into a Binary tree and to traverse in pre-order.
• 11. Write a C program to arrange a set of numbers in ascending order using QUICKSORT.
• 12. Write a C program to arrange a set of numbers in descending order using EXCHANGE-
SORT.