Download as pdf or txt
Download as pdf or txt
You are on page 1of 209

Downloaded From : www.EasyEngineering.

net

ww
w.E
a syE
ngi
nee
rin
g.n
et

**Note: Other Websites/Blogs Owners Please do not Copy (or) Republish


this Materials, Students & Graduates if You Find the Same Materials with
EasyEngineering.net Watermarks or Logo, Kindly report us to
easyengineeringnet@gmail.com

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Syllabus

Structure of a C program – compilation and linking processes – Constants,


Variables – Data Types – Expressions using operators in C – Managing Input
and Output operations – Decision Making and Branching – Looping
statements. Arrays – Initialization – Declaration – One dimensional and Two-
dimensional arrays. Strings- String operations – String Arrays. Simple
programs- sorting,searching – matrix operations.

S.no Topic
1 Structure of a C program
2 compilation and linking processes
3 Constants
4 Variables

ww
5
6
7
Data Types
Expressions using operators in C
Managing Input and Output operations in C
8
9 w.E
Decision Making and Branching in C
Looping statements in C
10 Arrays
asy
Initialization
Declaration
One dimensional array
En
Two-dimensional arrays
11 Strings
String operations gin
String Arrays
eer
12 Simple programs- sorting,searching – matrix operations
sorting ing
searching
matrix operations .ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

STRUCTURE OF C PROGRAM

ww
w.E
asy
En
gin
eer
ing
.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Documentation section: The documentation section consists of a set of


comment lines giving the name of the program, the author ,date on which
program is written and other details, which the programmer would like to use
later.

Link section:
The link section provides instruction to the compiler to link or include the
required in-built functions from the system library such as using the #include
directive.Eg #include<stdio.h>, #include<string.h>,#include<math.h>.

Definition section:
The definition section defines all symbolic constants using the #define
directive(optional). Having the constants being defined here, we can use them

ww
elsewhere in code.

# define N 100 /* which means N’s value is 100*/


w.E
# define pi 3.14

asy
Global declaration section :
There are some variables that are used in more than one function. i.e common

En
to more than one function.Such variables are called global variables and are
declared in the global declaration section that is outside of all the functions.

main () function section : gin


eer
Every C program must have one main function section. This section contains
two parts; declaration part and executable part.
ing
Declaration part : The declaration part declares all the variables used in
the executable part.
Executable part : There is at least one or more statements in the .ne
executable part designed for some task\executing some logic.
These two parts must appear between the opening and closing braces. The
program execution begins at the opening brace and ends at the closing brace.
t
The closing brace of the main function is the logical end of the program. All
statements in the declaration and executable part end with a semicolon(;).

Sub program section:


If the program is a multi-function program then the subprogram section
contains definition of all the user-defined functions which were declared earlier
in the Definition Section. User-defined functions are generally placed
immediately after the main () function, although they may appear in any order.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Figure 1.2 A C program contains one or more


main() functions, where a function is defined as a
{
group of statements that perform a well-
Statement 1;
Statement 2; defined task.
...........
Statement Figure 1.2 shows the structure of a C
N; program.
}
Function1() The statements in a function are written to
{ perform a specific task.
Statement 1;
Statement 2; The main() function is the most important
Statement N; function and is a part of every C program
}
and is mandatory
Function2()
{
ww Statement 1; The execution of a C program begins with
main( )function.

} w.E
Statement 2;
Statement N;
A C program can have any number of

asy
FunctionN() functions depending on the number of
{ independent tasks that have to be
Statement 1; performed, and each function can have any
Statement 2;
Statement N;
En number statements.
}
gin
Pre-processor directives tells the preprocessor

eer
to look for special code libraries, make
substitutions in the code and in other ways

ing
prepare the code for translation into machine
language.

.ne
t
PROGRAM STATEMENT
A statement performs an action
when a program is executed.

All C program statements are


terminated with a semi-colon (;).

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Declaration statement: the name and type of the data objects needed during
program execution.
Example :-int a
Expression statement: is the simplest kind of statement

Example x = a+b*c^4 is an expression

Compound statement: is a sequence of statements that may be treated as a


single statement

Labeled statements: can be used to mark any statement so that control may be
transferred to the statement by switch statement

Case 1:
ww labelABC:

w.E
Control statement: is a statement whose execution results in a choice being
made as to which of two or more paths to execute.

asy
Eg:categories of if and if..else

En
Selection statements: allow a program to select a particular execution path
from a set of one or more alternatives. Eg Switch

gin
Iteration statements: are used to execute a group of one or more statements

eer
repeatedly. while, for, and do..while statements falls under this group.

ing
Jump statements: cause an unconditional jump to some other place in the
program. goto statement falls in this group.
.ne
EXAMPLE C PROGRAM

//sample.c//
t
#include<stdio.h>
main()
{
printf(“welcome to C”);
return 0;
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


Compile and Link C Program
There are three basic phases occurred when we execute any C program.

 Preprocessing
 Compiling
 (assembler)
 Linking

Preprocessing Phase :A C pre-processor is a program that accepts C code with


preprocessing statements and produces a pure form of C code that contains no
preprocessing statements (like #include).

Compilation Phase:The C compiler accepts a preprocessed output file from the


preprocessor and produces a special file called an object file. Object file contains machine
code generated from the program.

wwLinking Phase:The link phase is implemented by the linker. The linker is a process that
accepts as input object files and libraries to produce the final executable program.

w.E
Compiling and Linking a C program is a multi-stage process.

asy
The process can be split into four separate stages: Preprocessing, compilation, assembly, and
linking.
/*
En
* "Hello, World!": A classic.
*/

#include <stdio.h> gin


int main(void)
eer
ing
{
puts("Hello, World!");
return 0;
}

.ne
Preprocessing t
The first stage of compilation is called preprocessing. In this stage, lines starting with a #
character are interpreted by the preprocessor as preprocessor commands. These commands
form a simple macro language with its own syntax and semantics.

reduce repetition in source code


invoke inline files
define macros
joining continued lines (lines ending with a \)
removes comments.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


To print the results of the preprocessing stage, pass the -E option to cc:

gcc -E hello_world.c

[lines omitted for brevity]

extern int __vsnprintf_chk (char * restrict, size_t,


int, size_t, const char * restrict, va_list);
# 493 "/usr/include/stdio.h" 2 3 4
# 2 "hello_world.c" 2

int main(void) {
puts("Hello, World!");
return 0;
}

ww
Compilation

w.E
In this stage, the preprocessed code is translated to assembly instructions These form an
intermediate readable language.

asy
Some compilers also supports the use of an integrated assembler, in which the
compilation stage generates machine code directly, avoiding the overhead of generating

En
the intermediate assembly instructions and invoking the assembler. object code is
directly produced by compiler.

gin
to view the result of the compilation stage, pass the -S option to cc:

gcc -S hello_world.c
eer
ing
This will create a file named hello_world.s
.section __TEXT,__text,regular,pure_instructions .ne
.macosx_version_min 10, 10
.globl _main
.align 4, 0x90
_main: ## @main
t
.cfi_startproc
## BB#0:
pushq %rbp
Ltmp0:
.cfi_def_cfa_offset 16
Ltmp1:
.cfi_offset %rbp, -16
movq %rsp, %rbp
Ltmp2:
.cfi_def_cfa_register %rbp
subq $16, %rsp
leaq L_.str(%rip), %rdi
movl $0, -4(%rbp)
callq _puts
xorl %ecx, %ecx
movl %eax, -8(%rbp) ## 4-byte Spill

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


movl %ecx, %eax
addq $16, %rsp
popq %rbp
retq
.cfi_endproc

.section __TEXT,__cstring,cstring_literals
L_.str: ## @.str
.asciz "Hello, World!"

Assembly

During the assembly stage, an assembler is used to translate the assembly instructions to
machine code, or object code.
--The output consists of actual instructions to be run by the target processor.

Input to assembler :cc -c hello_world.c

ww
Output of assembler phase: hello-worls.o
The contents of this file is in a binary format and can be viewed using hexdump or od
commands:

Linking
w.E gcc -C hello_world.c

asy
The object code generated in the assembly stage is composed of machine instructions that the

En
processor understands but some pieces of the program are out of order or missing. To
produce an executable program, the existing pieces have to be rearranged and the missing
ones filled in. This process is called linking.
gin
The result of this stage is the final executable program(.exe)

Finally to run eer


a.out hello_world.c ing
.ne
Commands to compile and execute C program

Save the program file using .c extention


t
To compile:

gcc filename.c

To run the program

./a.out

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Constants/Literals
A constant is a value or an identifier whose value cannot be altered in a program.

For example: 1, 2.5, "C programming is easy", ‘apple’ etc.

We can define constants in a C program in the following ways.

1. By “const” keyword
2. By “#define” preprocessor directive

Syntax1: const type constant_name;


Eg 1: const double PI = 3.14 //variable PI is a constant ,3.14 cannot be changed

ww
Eg-1
#include<stdio.h>
main()
{
w.E
const int SIDE = 10;
int area;
area = SIDE*SIDE; asy
}
En
printf("The area of the square %d is: %d sq. units" , SIDE, area);

Output
The area of the square 10 is: 100 sq. Units
gin
Syntax 2: #define variable value
Eg-2 #define PI 3.14 eer
Constants can be classified into broad categories ing
C constant .ne
Primary Constants
t
-integer constant
-floating point constant
-character Constant
-String Constant
-Backslash Constant

1. Integer constants
An integer constant is a numeric constant (associated with number) without any fractional or
exponential part. There are three types of integer constants in C programming:
 decimal constant(base 10)
 octal constant(base 8)
 hexadecimal constant(base 16)

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


For example:
Decimal constants: 1,0, -9, 22 etc
Octal constants: 021, 077, 033 etc
Hexadecimal constants: 0x7f, 0x2a, 0x521 etc

In C programming, octal constant starts with a 0 and hexadecimal constant starts with a 0x.

55 /*int constant */
55l /*unsigned int constant*/
55 ul /*unsigned long constant*/

Rules for defining integer constants:

 An integer constant must have at least one digit.


 It must not have a decimal point.
 It can either be positive or negative.
 No commas or blanks are allowed within an integer constant.

ww

If no sign precedes an integer constant, it is assumed to be positive.
The allowable range for integer constants is -32768 to 32767.

w.E
2. Floating-point constants

asy
A floating point constant is a numeric constant that has either a fractional form or an
exponent form(decimal point). For example:

-2.0 6.333 –correct


En 633E---illegal..incomplete exponent
633f—illegal..no decimal or exponent
0.0000234
-0.22E-5 633E-4L-correct
gin
.e633—illegal..missing integer

Rules for defining floating point(real) constants:


eer


A real constant must have at least one digit
It must have a decimal point ing


The mantissa part and exponential part should be separated by a letter e/E
.ne
The mantissa part must have a positive or negative sign. The default sign of mantissa


part is positive.
No commas or blanks are allowed within a real constant.

3. Character constants
t
A character constant is a constant which uses single quotation around characters.
For example:
'a'
'6',
'=',
'F'
Rules for defining character constants

 A character constant is a single alphabet, a single digit or a single special symbol


enclosed within single quotes.
 The maximum length of a character constant is 1 character.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


4. String constants
String constants are the constants which are enclosed in a pair of double-quote marks. For
example:
"good" //string constant
"" //null string constant
" " //string constant of six white space
"x" //string constant having single character.
String constants are enclosed within double quotes.
5. Backslash Character Constants in C:
 There are some characters which have special meaning in C language.
 They should be preceded by backslash symbol.(\)
Backslash_character Meaning
\b Backspace
\f Form feed
\n New line

ww \r
\t
Carriage return
Horizontal tab
\” w.E Double quote
\’
\\ asy Single quote
Backslash
\v
EnVertical tab
\a
\? gin
Alert or bell
Question mark
\N
eer
Octal constant (N is an octal constant)
\XN Hexadecimal constant (N – hex.dcml cnst)
ing
Example Program Using Const Keyword
#include<stdio.h>
Using # Define
#include<stdio.h> .ne
int main( )
{
int const BASE ,HEIGHT;
#define BASE 100
#define HEIGHT 100
#define NEWLINE ‘\n’
t
float area; int main( )
char NEWLINE=’\n’; {
area=0.5*BASE*HEIGHT float area;
printf(“The Area of Triangle is:”); area=0.5*BASE*HEIGHT
printf(“%c”,NEWLINE); printf(“The Area of Triangle is:”);
printf(“%f”,area); printf(“%c”,NEWLINE);
return 0; printf(“%f”,area);
} return 0;
}

OUTPUT OUTPUT
10 20 10 20
The Area of Triangle is: The Area of Triangle is:

100 100

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Example program using const keyword in C:

#include <stdio.h>
void main()
{
const int height = 100; /*int constant*/
const float number = 3.14; /*Real constant*/
const char letter = 'A'; /*char constant*/
const char letter_sequence[10] = "ABC"; /*string constant*/
const char backslash_char = '\?'; /*special char cnst*/
printf("value of height :%d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);
}

ww
Output:
value of height : 100

w.E
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
asy
En
2. Example program using #define preprocessor directive in C:

#include <stdio.h>
#define height 100
#define number 3.14 gin Output:

#define letter 'A'


#define letter_sequence "ABC" eer
value of height : 100
value of number : 3.140000
#define backslash_char '\?'
void main() ing
value of letter : A
value of letter_sequence : ABC
{
printf("value of height : %d \n", height );
value of backslash_char : ?
.ne
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n",letter_sequence);
printf("value of backslash_char : %c \n",backslash_char);
t
}
------------------------------------------------------------------------------------------------------
Difference between variable and constants
The difference between variables and constants is that variables can change their value at
any time but constants can never change their value.

Variable Constant variable


int a =10; const int a =10;
a++; a++;
printf(“%d”,a); printf(“%d”,a);
----------------------- ---------------------
o/p:= 11 o/p:= 10

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

DATA TYPES IN C

The data type, of a variable determines a set of values that a variable might take and a set
of operations that can be applied to those values.

Data type refer to the type and size of data associated with the variable and functions.

Data types can be broadly classified as shown in Figure

Basic data type of C

ww
w.E
Data Type Size in Range Format-

int asy
Bytes
2 -32768 to +32767
Specifier
%d
short signed int (or)
signed int
2

En 32768 to +32767 %d

int
short unsigned int
(or)
unsigned int
2

gin
0 to 65535 %u

long signed int (or)


long int
4
eer
-2147483648 to 2147483647 %ld

long unsigned int 4 0 to 4294967295


ing %lu

char char or signed char


unsigned char
1
1
-128 to 127
0 to 255
.ne %c
%c
float
Allows 6 digits after
decimal point.
4 -3.4e-38 to +3.4e38 %f
t
double 8 -1.7e-308 to +1.7e308 %lf

Allows 15 digits
after decimal point.
long double 10 -1.7e-4932 to 1.7e4932 %LF

Allows 15 digits
after decimal point.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

/*Program*/
#include<stdio.h>
int main()
{
char a;
unsigned char b;
int i;
unsigned int j;
long int k;
unsigned long int m;
float x;
double y
long double z;

ww
printf(“\n char and unsigned char”);
scanf(“%c %c”,&a,&b) //get char and unsigned char value
w.E
printf(“%c %c”,a,b) //display char and unsigned char value

asy
printf(“\n int unsigned int”);
scanf(“%d %u”,&i,&j) //get int unsigned int value

En
printf(“%d %u”,i,j) //display int unsigned int value

printf(“\n long int unsigned long int”); gin


eer
scanf(“%ld %lu”,&i,&j) //get long int and long unsigned int value
printf(“%ld %lu”,i,j) //display int unsigned int value

printf(“\n float,double and long double”);


ing
scanf(“%f %lf %Lf”,&i,&j) //get float,double and long double value .ne
printf(“%f %lf %Lf”,i,j) //display float,double and long double value

return 0;
t
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

The specifiers and qualifiers for the data types can be broadly classified into
three types

 Size specifiers— short and long


 Sign specifiers— signed and unsigned
 Type qualifiers— const, volatile and restrict.

Size qualifiers alter the size of the basic data types. There are two such qualifiers that can
be used with the data type int; these are short and long.

short, when placed in front of the data type int declaration, tells the C compiler that the
particular variable being declared is used to store fairly small integer values. Long specifies it
is a very big integer value.Long integers require twice the memory of than small ints.

ww
Table: Sizes (bytes) of short int ,int,long int

16-bit Machine 16-bit Machine 16-bit Machine

short int w.E (size in bytes)


2
(size in bytes)
2
(size in bytes)
2
int
long int
asy 2
4
4
4
4
8

En
Table:Size and range of long long type (64-bit machine)

Data type
bytes)gin
Size (in Range

long long int 8


eer
-9, 223, 372, 036, 854, 775, 808 to
+9, 223, 372, 036, 854, 775, 808

unsigned long int or 4 ing


0 to + 4, 294, 967, 295
unsigned long
unsigned long long int or 8 .ne
0 to + 18, 446, 744, 073,709, 551, 615
unsigned long long

Sign specifiers: for example fot int data type out of 2bytes(2*8=16bits) of its size the
highest bit(the sixtheenth bit) is used to store the sign of the integer value. The bit is 1 if
t
number is negative and 0 if the number is positive.

Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Sign of number
(1 for –ve and 0
for +ve0

Type qualifiers : There are two type qualifiers, const and volatile;
Eg: const float pi = 3.14156; // specifies that the variable pi can never be changed by the
Program.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Table:Size and range in (16-bit machines)

Data type Size (in bits) Range


note:[1byte=8bits]
char 8 –128 to 127
int 16 –32768 to 32767
float 32 1.17549 × 10–38 to 3.40282 × 1038
double 64 2.22507 × 10–308 to 1.79769 × 10 308
Void 8 valueless

Table:Size and range of (32-bit machine)

Data type Size (in bits) Range


note:[1byte=8bits]
char 8 –128 to 127
–2147483648 to 2147483647
ww
int
float
double
32
32
64
1.17549 × 10–38 to 3.40282 × 1038
2.22507 × 10-308 to 1.79769 × 10 308
Void
w.E 8 valueless

asy
Allowed combinations of basic data types and modifi ers in C for a 16-bit
computer

En
gin
eer
ing
.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


VARIABLES
Variable is the name of memory location which holds the data. Unlike constant, variables are
changeable, value of a variable can be changed during execution of a program. A
programmer must chose a meaningful variable name.

Variables are used for holding data values so that they can be utilized for various
computations in a program.A variable must be declaed and then used for coputation work in
program./A variable is an identifier used for storing and holding some data(value).

All variables have three important attributes.

1.A data type: Like int, double, float. Once defined,the type of a C variable
cannot be changed.
2.A name of the variable.
3.A value that can be changed by assigning a new value to the variable. The
ww
kind of values a variable can assume depends on its type.
Eg : for variable int salary,it can only take integer values can only take integer
w.E
values like 65000 and not 6500.0

asy
Rules For Constructing Variables

En
1. A variable name can be a combination of alphabets, numbers and special character
underscore( _ ).

gin
2. The first character in the variable name must be an alphabet.
3. No commas or blank spaces are available are allowed within a variable name.
4. No special symbol other than an underscore is allowed.

eer
5.Upper and Lower case names are treated as different, as C is case sensitive, so it is
suggested to keep the variable names in lower case.

Declaring and Initializing a variable:= ing


Declaration of a variable must be done before it is used for any computation in the .ne
program.
Declaration tells the compiler what the variable name is.
 Declaration tells what type of data the variable will hold.
Until the variable is not defined/or/declared compiler will not allocate memory space to the
t
variables.
 A variable can also be declared outside main() function.
A variable can also be declared in other program and declared using extern keyword.

int yearly_salary;
float monthly_salary;
int a;
double x;
int ECE1111;

Initializing a variable:=
Initializing a variable means to provide a value to variable

int yearly salary=5,00,000


float monthly_salary= 41666.66

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Difference between identifier and variable


Identifier Variable
Indentifier is the name given to a While variable is used to name a memory
variable,function etc. location which stores data
An identifier can be a variable ,but not all All variables names are identifiers
identifiers are variables
Example : void average() Example: int average
{
}

Variables are a way of reserving memory to hold some data and assign names to them so that
we don’t have to remember the numbers like REG46735 or memory address like FFFFoxFF
and instead we can use the memory location by simply referring to the variable.

Every variable is mapped to a unique memory address.

ww
And variable will be having a data type associated

w.E
int salary = 65000;

asy
En
gin
eer
ing
[[[[[[note A computer memory is made up of registers and cells. It accesses data in a
collection of bits, typically 8 bits, 16 bit, 32 bit or 64 bit. A computer memory holds information in
the form of binary digits 0 and 1 (bits).]]]]]]

.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


Operators in C

An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of
operators –

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators

Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language.
Assume variable A holds 10 and variable B holds 20

ww
Operator
+ Adds two operands.
Description Example
A + B = 30

*
w.E
Subtracts second operand from the first.
Multiplies both operands.
A − B = -10
A * B = 200
/
asy
Divides numerator by de-numerator.
Modulus Operator and remainder of after an
B/A=2

%
integer division.
En B%A=0

++
one.
gin
Increment operator increases the integer value by
A++ = 11

--
Decrement operator decreases the integer value
by one.
eer A-- = 9

Relational Operators ing


The following table shows all the relational operators supported by C.
.ne
t
Assume variable A holds 10 and variable B holds 20 then

Operator Description Example


Checks if the values of two operands are equal or not. If
== (A == B) is not true.
yes, then the condition becomes true.
Checks if the values of two operands are equal or not. If the
!= (A != B) is true.
values are not equal, then the condition becomes true.
Checks if the value of left operand is greater than the value
> (A > B) is not true.
of right operand. If yes, then the condition becomes true.
Checks if the value of left operand is less than the value of
< (A < B) is true.
right operand. If yes, then the condition becomes true.
Checks if the value of left operand is greater than or equal
>= to the value of right operand. If yes, then the condition (A >= B) is not true.
becomes true.
Checks if the value of left operand is less than or equal to
<= the value of right operand. If yes, then the condition (A <= B) is true.
becomes true.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


Logical Operators

Following table shows all the logical operators supported by C language. Assume variable A
holds 1 and variable B holds 0, then −

Operator Description Example


Called Logical AND operator. If both the operands are
&& (A && B) is false.
non-zero, then the condition becomes true.
Called Logical OR Operator. If any of the two operands is
|| (A || B) is true.
non-zero, then the condition becomes true.
Called Logical NOT Operator. It is used to reverse the
! logical state of its operand. If a condition is true, then !(A && B) is true.
Logical NOT operator will make it false.

Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as follows −
p q p&q p|q p^q

ww
0
0
0
1
0
0
0
1
0
1
1
1
1
0
w.E
0
1
1
1
1
0

Assume A = 60 and B = 13 in binary format, they will be as follows −


A = 0011 1100
B = 0000 1101
----------------- asy
A&B = 0000 1100
A|B = 0011 1101 En
A^B = 0011 0001
~A = 1100 0011
gin
The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and variable 'B'
holds 13, then −
Operator Description eer Example

&
Binary AND
It takes 1 if both operands has value 1. ing
(A & B) = 12, i.e., 0000 1100

Binary OR
Operator copies a bit if it exists in either operan .ne
|
The output of bitwise OR is 1 if at least one
corresponding bit of two operands is 1.
Binary XOR
(A | B) = 61, i.e., 0011 1101
t
^ 1 if the corresponding bits of two operands are (A ^ B) = 49, i.e., 0011 0001
opposite
Binary Ones Complement
~ (~A ) = -60, i.e,. 1100 0100
'flipping' bits- 0 changed to 1and 1 changed to 0
Binary Left Shift Operator.
<< The left operands value is moved left by the A << 2 = 240 i.e., 1111 0000
number of bits specified by the right operand.
Binary Right Shift Operator.
>> The left operands value is moved right by the A >> 2 = 15 i.e., 0000 1111
number of bits specified by the right operand.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


Assignment Operators

The following table lists the assignment operators supported by the C language

Operator Description Example


Simple assignment operator. Assigns values from C = A + B will assign the value
=
right side operands to left side operand of A + B to C
Add AND assignment operator. It adds the right
C += A is equivalent to
+= operand to the left operand and assign the result to
C=C+A
the left operand.
Subtract AND assignment operator. It subtracts
C -= A is equivalent to
-= the right operand from the left operand and
C=C-A
assigns the result to the left operand.
Multiply AND assignment operator. It multiplies
C *= A is equivalent to
*= the right operand with the left operand and assigns
C=C*A

ww/=
the result to the left operand.
Divide AND assignment operator. It divides the
left operand with the right operand and assigns the
C /= A is equivalent to

w.E
result to the left operand.
Modulus AND assignment operator. It takes
C=C/A

C %= A is equivalent to
%=
asy
modulus using two operands and assigns the
result to the left operand.
C=C%A

<<=
En
Left shift AND assignment operator.
C <<= 2 is same as
C = C << 2

>>= Right shift AND assignment operator.


gin C >>= 2 is same as
C = C >> 2
&=
^=
Bitwise AND assignment operator.
Bitwise exclusive OR and assignment operator. eer C &= 2 is same as C = C & 2
C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator.
ing
C |= 2 is same as C = C | 2

Misc Operators
.ne
Operator Description

sizeof() Returns the size of a variable.


int a;
Example

sizeof(a), where a is integer, will return 2.


t
&a; returns the actual address of the
& Returns the address of a variable.
variable a .(OxFFA)
* Pointer to a variable. *a;
If Condition is true ? then value X :
?: Conditional Expression.
otherwise value Y

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Operators Precedence in C

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.

Table showing highest precedence to lowest precedence

Category Operator Associativity


Postfix ( ) [ ] -> . ++ - - Left to right
Unary Unary +,unary-, (type) * & sizeof Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift << >> Left to right

ww Relational
Equality
< <= > >=
= = !=
Left to right
Left to right
Bitwise AND
Bitwise XOR w.E &
^
Left to right
Left to right
Bitwise OR
Logical AND
asy &&
| Left to right
Left to right
Logical OR
Conditional En||
?:
Left to right
Right to left
Assignment
Comma , gin
= += -= *= /= %= >>= Right to left
Left to right

eer
Expression
ing
Expression is a combination of variables(like a,b,m,n..), constants(3,2,1) and
operators(+,/*). .ne
Eg : c+d t
x/y+b+a*a*a

3.14 *r *r

Algebraic Expression C Expression


ab-c a*b-c
(m+n)(k+j) (m+n)*(k+j)
(ab/c) a*b/c
3x2+2x+1 3*x^2+2*x+1

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


Example Program
#include<stdio.h>
Program
int main( )
{
int x=2,y=3,result;
result=x*5+y*7;
printf(“result =:%d”,result);
return 0;
}
Expression evaluation
result=x*5 + y*7;
result=2*5 + 3*7;
result=2*5 + 3*7;

ww result=10 + 3*7;
result=10 + 21;
result=31;
w.E
Example program –find greatest of 3 numbers

asy
Example of logical(&& logical AND) and relational operators(>)

#include<stdio.h>
int main()
En
{
int num1,num2,num3;
gin
printf("\nEnter value of a, b and c:");
eer
scanf("%d %d %d",&a,&b,&c);
ing
if((a>b)&&(a>c))
printf("\n %d is greatest",a); .ne
else if(b>c)
printf("\n %d is greatest",b ");
else
t
printf("\n %d is greatest",c);
return 0;
}

Example program –find odd or even number


Example of Arithmetic(% mod) and relational operators(==)
#include<stdio.h>
int main()
{ int num,result;
if(num%2==0)
printf(“even number \n”);
else
printf(“odd number \n”);
return 0;
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Bitwise XOR
Explanation

12 = 00001100 (In Binary)


#include <stdio.h> 25 = 00011001 (In Binary)
int main()
{ Bitwise XOR Operation of 12 and 25
00001100
int a = 12, b = 25; 00011001
printf("Output = %d", a^b); ________
return 0; 00010101 = 21 (In decimal)
}

Output = 21

ww
Bitwise complement 1’s compliment

#include <stdio.h>
Explanation

35 = 00100011 (In Binary)


int main()
{ w.E
printf("complement = %d\n",~35);
Bitwise complement Operation of 35
~ 00100011

}
return 0;
asy ________
11011100 = 220 (In decimal)

OutPut:
En
complement = 220
gin
eer
Bitwise AND and OR operator 12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
#include <stdio.h> Bitwise AND Operation of 12 and 25
int main()
{
00001100
& 00011001 ing
int a = 12, b = 25;
printf("OutputAND = %d", a&b);
________
00001000 = 8 (In decimal)
.ne
Bitwise OR Operation of 12 and 25

}
printf("OutputOR = %d", a|b);
return 0;
00001100
| 00011001
________
00011101 = 29 (In decimal)
t
OutputAND = 8
OutputOR = 29

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Managing Input and Output operations

Constructs for getting input Constructs for displaying output


1)scanf( ) 1)scanf( )
2)putchar() 2)getchar()
3)puts() 3)gets( )

4)getche( )

5)fgets( ) 4)fputs( )
6)fscanf( ) 5)fprint( )

ww
C Input and Output

w.E
Input means to provide the program with some data to be used in the program

Output means to display data on screen or write the data to a printer or a file.

asy
1. Single character input and output[getchar( ) and putchar()]

 input- getchar()
En
 output- putchar()
gin
eer
The int getchar(void) function reads the next available character from the screen and returns
it as an integer. This function reads only single character at a time.

ing
The int putchar(int c) function puts the passed character on the screen and returns the same
character. This function puts only single character at a time.
.ne
program
#include <stdio.h>
int main( ) {
t
output
int c; $./a.out
Enter a value : this is DS class
printf( "Enter a value :"); You entered: t
c = getchar( );

printf( "\nYou entered: ");


putchar( c );

return 0;
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

2. String input and output[gets() and puts()

 Input--- gets (str)


 Output---puts (str)

The gets( ) function reads a line from stdin into the buffer pointed to by s until either a
terminating newline or EOF (End of File).

The puts( ) function writes the string 's' and 'a' trailing newline to stdout.

Program

#include <stdio.h> Output


int main( ) {

ww char str[100];
$./a.out
Enter a value : this is DS class
You entered: this is DS class

w.E
printf( "Enter a value :");
gets( str );

asy
printf( "\nYou entered: ");
puts( str );

}
return 0;

En
gin
3.Formatted Input [ scanf ( ) ] and Formatted Output [ printf ( ) ]
Specifier Meaning
%c – Print a character
%d – Print a Integer eer
%i – Print a Integer
%u-- Unsigned int ing
%ld-- Long int
%e – Print float value in exponential form.
%f – Print float value .ne
%g – Print using %e or %f whichever is smaller
%lf --Double
%lf-- Long double
t
%o – Print octal value
%s – Print a string
%x – Print a hexadecimal integer (Unsigned) using lower case a – f
%X – Print a hexadecimal integer (Unsigned) using upper case A – F
%a – Print a unsigned integer.
%p – Print a pointer value
%hx – hex short

scanf()
scanf() is a predefined function in "stdio.h" header file. It can be used to read the input value
from the keyword.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


Syntax of scanf() function
1.& ampersand symbol is the address operator specifying the address of the variable
2.control string holds the format of the data
3.variable1, variable2, ... are the names of the variables that will hold the input value.

scanf("control string", &variable1, &variable2, ...);


Example
int a;
float b;
scanf("%d%f",&a,&b);

Example

double d;
char c;
long int l;

ww
scanf("%c%lf%ld",&c&d&l);

Printf
w.E
Printf is a predefined function in "stdio.h" header file, by using this function, we can print the

asy
data or user defined message on console or monitor. While working with printf(), it can take
any number of arguments but first argument must be within the double cotes (" ") and every

En
argument should separated with comma ( , ) Within the double cotes, whatever we pass, it
prints same, if any format specifies are there, then value is copied in that place.

Program gin
#include <stdio.h> eer
//This is needed to run printf() function.
int main()
{
printf("C Programming"); //displays the content inside quotation ing
}
return 0;
.ne
Output
C Programming

Program(integer and float)


t
#include <stdio.h>
#include <conio.h>
void main();
{
int a;
float b;
clrscr();
printf("Enter any two numbers: ");
scanf("%d %f",&a,&b);
printf("%d %f \n",a,b);
getch();
}

Output: Enter any two numbers:10 3.5


10
3.5

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Program
#include <stdio.h>
int main()
{

int integer = 9876;


float decimal = 987.6543;

printf("4 digit integer right justified to 6 column: %6d\n", integer);

printf("4 digit integer right justified to 3 column: %3d\n", integer);

printf("Floating point number rounded to 2 digits: %.2f\n",decimal);

printf("Floating point number rounded to 0 digits: %.f\n",987.6543);

printf("Floating point number in exponential form: %e\n",987.6543);

}
ww return 0; Output

4 digit integer right justified to 6 column: 9876

w.E 4 digit integer right


Floating point number
Floating point number
Floating point number
justified to 3 column: 9876
rounded to 2 digits: 987.65
rounded to 0 digits: 988
in exponential form: 9.876543e+02

asy FILE INPUT and OUTPUT

En
4. File string input and output using fgets( )and fputs( )
The fgets() function

Syntax fgets(char str[],int n,FILE *fp); gin


The fgets() function is used to read string(array of characters) from the file.

eer
The fgets() function takes three arguments, first is the string read from the file, second is size
of string(character array) and third is the file pointer from where the string will be read.

Example File*fp; ing


Str[80];
fgets(str,80,fp)
.ne
Example program
#include<stdio.h>
void main()
t
{
FILE *fp;
char str[80];
fp = fopen("file.txt","r"); // opens file in read mode (“r”)

while((fgets(str,80,fp))!=NULL)
printf("%s",str); //reads content from file
fclose(fp);
}
Data in file...
C is a general-purpose programming language.
It is developed by Dennis Ritchie.

C is a general-purpose programming language.


It is developed by Dennis Ritchie.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


Output :

The fputs() function


The fputs() function is used to write string(array of characters) to the file.

 The fputs() function takes two arguments, first is the string to be written to the file and
second is the file pointer where the string will be written.
Syntax:
fputs(char str[], FILE *fp);
#include < stdio.h >
int main ()
{
FILE *fp;
fp = fopen("proverb.txt", "w+"); //opening file in write mode
fputs("Cleanliness is next to godliness.", fp);
fputs("Better late than never.", fp);
fputs("The pen is mightier than the sword.", fp);
fclose(fp);
return(0);
}
ww
Output

w.E
Cleanliness is next to godliness.
Better late than never.
The pen is mightier than the sword.

asy
4. File string input and output using fgets( )and fputs( )

The fscanf() function


En
The fscanf() function is used to read mixed type(characters, strings and integers) form the file.

gin
The fscanf() function is similar to scanf() function except the first argument which is a file pointer
that specifies the file to be read.
Syntax:
Example program
eer
fscanf(FILE *fp,"format-string",var-list);

#include<stdio.h>
ing
void main()
{
FILE *fp; .ne
char ch;

int roll;
char name[25];
t
fp = fopen("file.txt","r");
printf("\n Reading from file...\n");

while((fscanf(fp,"%d%s",&rollno,&name))!=NULL)
printf("\n %d\t%s",rollno,name);//reading data
fclose(fp);
}

Output :

Reading from file...


6666 keith
7777 rose

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

The fprintf() function:


 The fprintf() function is used to write mixed type(characters, strings and integers) in the
file.
The fprintf() function is similar to printf() function except the first argument which is a file
pointer specifies the filename to be written.
Syntax
fprintf(FILE *fp,"format-string",var-list);

Example program
#include<stdio.h>

void main()
{ Output
FILE *fp;
int roll; 6666
char name[25]; john
fp = fopen("file.txt","w");

ww scanf("%d",&roll);
scanf("%s",name);
fprintf(fp,"%d%s%",roll,name);

}
w.E close(fp);

asy
En
gin
eer
ing
.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Decision Making and Branching

Conditional Branching Conditional Branching


if statement break
nested if statement continue
if ..else statement goto
nested if else statement

These include conditional type branching and unconditional type branching.


if statement

It takes the following form

if(test-expression)

ww
It allows the computer to evaluate the expression first and them depending on whether
the value of the expression is "true" or "false", it transfer the control to a particular

w.E
statements. This point of program has two paths to flow, one for the true and the other
for the false condition.

if(test-expression)
{
asy
En
statement-block
}

gin
statement-x;

The statement-block may be a single statement or group of statements. If the test

eer
expression is true, the statement-block will be executed; otherwise the statement-block
will be skipped and the execution will jump to the statement-x. But when is condition
true both the statement-block and the statement-x are executed in sequence.
ing
.ne
Eg: Example program: C Program to check equivalence of
two numbers using if statement
#include<stdio.h>
void main()
{
int m,n;
t
clrscr();
printf(" \n enter two numbers:");
scanf(" %d %d", &m, &n);
if(m-n= = 0)
{
printf(" \n two numbers are equal");
Eg-2 }
if (code = = 1) getch();
{ }
salary = salary + 500;
}
printf("%d",salary); o/p

44

two numbers are equal

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Nested if

The syntax for a nested if statement is as follows


if( cond 1)
{
/* Executes boolean expression when cond 1 is true */
if(cond 2) {
/* Executes when the boolean expression 2 is true */
}
}

Example:
#include <stdio.h>
int main ()
{
int a = 100;

wwint b = 200;
if( a == 100 ) {
/* if condition is true then check the following */

w.E
if( b == 200 ) {
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200\n" );

}
}

asy
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
En
}

The if-else statement


gin
eer
The if-else statement is an extension of the simple if statement. The general form is If the test-

ing
expression is true, then true-block statements immediately following if statement are executed
otherwise the false-block statements are executed.

Example: C program to find largest of two numbers


if(test-expression)
{true-block statements .ne
#include<stdio.h>
int main()
{
int m,n,large;
}
else
{
t
false-block statements
printf(" \n enter two numbers:"); }statement-x
scanf(" %d %d", &m, &n);
if(m>n)
large=m;
else
large=n;
printf(" \n large number is = %d", large);
return 0;
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Nested if-else statement

Nested if construct is also known as if-else-if construct.

Syntax-1 Syntax-2

if(test-condition-1) If(test-condition-1)
{ {
(stmts) if(test-condition-2)
else {
{ statement-1;
if(condition 2) }
{ else
Statement-1; {
} statement-2;
else }
{ }

}
ww
}
statement-2; else
{
statement-3;
}
statement-x w.E }
statement-x

asy
If the test-condition-1 is false, the statement-3 will be executed; other wise it continues

En
the second test. If the condition-2 is true, the statement-2 will be evaluated and then the
control is transferred to the statement-x.

gin
Example:Program to relate two integers using =, > or <

#include <stdio.h>
int main()
{ eer
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
ing
//checks if two integers are equal. .ne
if(number1 == number2)
{

}
printf("Result: %d = %d",number1,number2);
t
//checks if number1 is greater than number2.
else if (number1 > number2)
{
printf("Result: %d > %d", number1, number2);
}

// if both test expression is false


else
{
printf("Result: %d < %d",number1, number2);
}
return 0;
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

The switch statement:


When many conditions are to be checked then using nested if...else is very difficult, confusing and
cumbersome.So C has another useful built in decision making statement known as switch.
This statement can be used as multiway decision statement.The switch statement tests the
value of a given variable or expression against a list of case values and when a match is
found, a block of statements associated with that case is executed.
Eg-1
int i = 1; switch( code)
switch(i) {
{ case 1:
case 1: stmts1;
printf("A"); break;
break; case 2:
case 2: stmts2;
printf("B"); break;
break; case 3:
case 3: stmts3
printf("C"); break;

ww default:
}
break;
default:
stmtsx

w.E
Example2: C program to find largest of two numbers }
#include<stdio.h>
For case 1,da=10% of basic salary.
void main ()
{
float basic , da , salary ; asy For case 2, da=15% of basic salary.
For case 3, da=20% of basic salary.

En
int code ; For default case >3 da is not given.(da=0)
char name[25];
da=0.0;
printf("Enter employee name\n");
scanf("%[^\n]",name); gin o/p
printf("Enter basic salary\n");
scanf("%f",&basic); eer
Enter name of employee:
printf("Enter code of the Employee\n");
scanf("%d",&code);
Kartiyani
Enter Basic salary
5000 ing
switch (code)
{ Enter code of employee
.ne
t
case 1: 1
da = basic * 0.10;
break; Employee name is
case 2: Kartiyani
da = basic * 0.15; DA is 500 and total salary is 5500
break;
case 3:
da = basic * 0.20; break;
default :
da = 0;
}
salary = basic + da;
printf("Employee name is\n");
printf("%s\n",name);
printf ("DA is %f and Total salary is =%f\n",da, salary);
getch();
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

ww
w.E
asy
Rules for using switch statement

En
1. The expression (after switch keyword) must yield an integer value
2. The case label values must be unique.
3. The case label must end with a colon(:)
gin
Difference between switch and if
eer

ing
if statements can evaluate float conditions. switch statements cannot evaluate
float conditions.

.ne
if statement can evaluate relational operators. switch statement cannot evaluate
relational operators i.e they are not allowed in switch statement.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


BREAK

The break statement in C programming has the following two usages −

 When a break statement is encountered inside a loop, the loop is immediately


terminated and the program control resumes at the next statement following the
loop.
 It can be used to terminate a case in the switch statement

BREAK is a keyword that allows us to jump out of a loop instantly, without waiting to
get back to the conditional test.

The syntax for a break statement in C is as follows −

break;

ww
w.E
asy
En
gin
eer
ing
Output .ne
Example program
#include <stdio.h>
int main ()
value of
value of
value of
a:
a:
a:
10
11
12
t
{ value of a: 13
int a = 10; value of a: 14
while( a < 20 ) value of a: 15
{
printf("value of a: %d\n", a);
a++;
if( a > 15)
{
break;
}
}
return 0;
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


Continue

The continue statement in C programming works somewhat like the break statement.
Instead of forcing termination, it forces the next iteration of the loop to take place,
skipping any code in between.

For the for loop, continue statement causes the conditional test and increment portions
of the loop to execute. For the while and do...while loops, continue statement causes the
program control to pass to the conditional tests.

Syntax: continue;

ww
w.E
asy
En
gin
eer
Example program ing
.ne
Output
#include <stdio.h> value of a: 10
int main () value of a: 11
{
int a = 10;
do {
value of
value of
value of
value of
a:
a:
a:
a:
12
13
14
16
t
value of a: 17
if( a == 15) value of a: 18
{ value of a: 19
/* skip the iteration */
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;
} while( a < 20 );
return 0;
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Break Continue
The break statement can be used in both The continue statement can appear only in
switch and loop (for, while, do while) loops. You will get an error if this appears
statements. in switch statement.
A continue doesn't terminate the loop, it
A break causes the switch or loop
causes the loop to go to the next iteration.
statements to terminate the moment it is
The continue statement is used to skip
executed. Loop or switch ends abruptly
statements in the loop that appear after the
when break is encountered.
continue.
The continue statement can appear only in
The break statement can be used in both
loops. You will get an error if this appears
switch and loop statements.
in switch statement.
When a break statement is encountered, it When a continue statement is
terminates the block and gets the control encountered, it gets the control to the next

ww
out of the switch or loop. iteration of the loop.

w.E
GOTO

GOTO STATEMENT

asy
‘C’ supports goto statement to branch unconditionally from one point to another in the program.

A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled
statement.
En
gin
NOTE − Use of goto statement is highly discouraged in any programming language because it makes
difficult to trace the control flow of a program, making the program hard to understand and hard to

eer
modify. Any program that uses a goto can be rewritten to avoid them.

Syntax
ing
The syntax for a goto statement in C is as follows −
.ne
goto label;
..
.
label: statement;
t
Or

label: statement;
...

...

goto label;

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Output

ww value
value
value
of
of
of
a:
a:
a:
10
11
12

w.E
Example program
#include <stdio.h>
int main ()
value
value
value
value
of
of
of
of
a:
a:
a:
a:
13
14
16
17
{
int a = 10;
ABCL:do asy value
value
of
of
a:
a:
18
19
{
if( a == 15) En
{
a = a + 1;
goto ABCL;
gin
}
printf("value of a: %d\n", a); eer
a++;
}while( a < 20 );
return 0; ing
}
program to print ‘n’ natural number .ne
#include<stdio.h>
void main( )
t
{
int n,i=1;
clrscr();
printf("enter number");
scanf("%d\t",n);
printf("natural numbers from 1 to %d", n);
lb: printf("%d\t",i);
i++;
if(i<=n)
goto lb;
getch();
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

LOOPING STATEMENTS

Loop constructs supports repeated execution of statements when a condition


match.

If the loop Test Condition is true, then the loop is executed, the
sequence of statements to be executed is kept inside the curly braces { } is
known as the Loop body. After every execution of the loop body, condition is
verified, and if it is found to be true the loop body is executed again. When the
condition check returns false, the loop body is not executed, and execution
breaks out of the loop.

ww
Types of Loop

There are 3 types of Loop in C language, namely:


w.E
1. while loop
2. for loop
3. do while loop asy
while loop En
gin
Repeats a statement or group of statements while a given condition is
eer
true. It tests the condition before executing the loop body.
while(condition)
{ ing
}
statements;
.ne
Example-- Example: Program to print first 10 natural numbers
#include<stdio.h>
void main( )
t
{
int x;
x = 1;
while(x <= 10)
{
printf("%d\t", x);
x++;
}
}
Output: 1 2 3 4 5 6 7 8 9 10

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


do while loop

In some situations it is necessary to execute body of the loop before


testing the condition. Such situations can be handled with the help of do-while
loop. do statement executes the body of the loop first and at the end, the
condition is checked using while statement. It means that the body of the loop
will be executed at least once, even though the starting condition inside while
is initialized to be false. do
{
General syntax . ...
. ...
Example: Program to print first 10 multiples of 5. }
#include<stdio.h> while(condition)

ww
void main()
{
int a, i;
a = 5;
i = 1;
w.E
do
{ asy
printf("%d\t", a*i);
En
}
i++;
gin
}
while(i <= 12);
eer
Output
ing
5 10 15 20 25 30 35 40 45 50 55 60
.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

ww
w.E Jumping Out of Loops

asy
Sometimes, while executing a loop, it becomes necessary to skip a part of the
loop or to leave the loop

1) break statement En
gin
When break statement is encountered inside a loop, the loop is immediately
eer
exited and the program continues with the statement immediately following
the loop.
ing
.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


2) continue statement

It causes the control to go directly to the test-condition and then continue the
loop process. On encountering continue, cursor leave the current cycle of loop,
and starts with the next cycle.

ww
w.E
asy
For Loop
En
gin
for loop is used to execute a set of statements repeatedly until a particular

eer
condition is satisfied. We can say it is an open ended loop.. General format is,

for(initialization; condition; increment/decrement)


{ ing
}
statement-block;
.ne
In for loop we have exactly two semicolons, one after initialization and second
after the condition. In this loop we can have more than one initialization or
increment/decrement, separated using comma operator. But it can have only
t
one condition.

The for loop is executed as follows:

1. It first evaluates the initialization code.


2. Then it checks the condition expression.
3. If it is true, it executes the for-loop body.
4. Then it evaluate the increment/decrement condition and again follows
from step 2.
5. When the condition expression becomes false, it exits the loop.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


Example: Program to print first 10 natural numbers
#include<stdio.h>
void main( )
{
int x;
for(x = 1; x <= 10; x++)
{
printf("%d\t", x);
}
}
Output: 1 2 3 4 5 6 7 8 9 10

ww
w.E
Nested for loop
asy
We can also have nested for loops, i.e one for loop inside another for loop.
Basic syntax is,
En
gin
for(initialization; condition; increment/decrement)
{

{
statement ; eer
for(initialization; condition; increment/decrement)

}
}
ing
Example: Program to print half Pyramid of numbers
#include<stdio.h> .ne
void main( )
{
int i, j;
Output

1
t
21
for(i = 1; i < 5; i++) /* first for loop */ 321
{ printf("\n"); 4321
/* second for loop inside the first */ 54321
for(j = i; j > 0; j--)
{
printf("%d", j);
}
}
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


ARRAYS

<Arrays – Initialization – Declaration – One dimensional and Two-dimensional arrays.>

1. ONE DIMENTIONAL ARRAY

2. TWO DIMENTIONAL ARRAY

3. STRING ARRAYS (ONE DIMENTIONAL ARRAY and TWO DIMENTIONAL ARRAY)

4. MULTIDIMENTIONAL ARRAYS

An array is a collection of similar data items, accessed using a common name. The collection of
element can all be integers or be all decimal value or be all characters or be all strings.

 A one-dimensional array is like a list


 A two dimensional array is like a table
 The C language places no limits on the number of dimensions in an array

ww ONE DIMENTIONAL ARRAY

w.E
Array Declaration:

asy
To declare an array in C, a programmer specifies the type of the elements and the number
of elements required. The arraySize must be an integer constant greater than zero and
datatype can be any valid C data type.

En
gin
Syntax1: datatype arrayName[ arraySize ];

Example-1

int number[20];
int n=25;
double x[n], y[n]; //array eer int n;
Scanf(“%d”,&n);//get size
int marks[44];
float salary[10];
double value[25];
declaration
ing
int x[n]; //array declaration

#include<stdio.h>
#define N 100
#include<stdio.h>
int main( ) .ne
int main( )
{
int marks[N];//array dec
....
{
int N=10,M=20;
int marks[N*M];//array dec
....
t
return 0; return 0;
} }

Syntax-2
<storage class> datatype arrayName[ arraySize ];

Example: static int marks[20];

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


Array intitialization:
Example-1 int mark[5] = {55, 66, 77, 88, 99};

mark[0] = 55
mark[1] = 66
mark[2] = 77
mark[3] = 88
mark[4] = 99

ww
Example-2 double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};

it means....
balance[0]
balance[1]
balance[2]
=
=
=
w.E 1000.0;
2.0;
3.4;
balance[3]
balance[4]
=
=
7.0;
50.0;
asy
En
gin
Automatic sizing eer
int arr[] = {3,1,5,7,9};
ing
Here, the C compiler will deduce the size of the array automatically based on the number of
elements. Array size is deduced to be 5
.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


OPERATIONS ON ARRAYS
o Traversing an array
o Inserting an element in an array
o Searching an element in an array
o Deleting an element from an array
o Merging two arrays
o Sorting an array in ascending or descending order
Working with one dimensional array
STORE and DISPLAY VALUES IN AN ARRAY (traversing an array)
#include<stdio.h>
int main( ) Output:
{ Enter the array elements
int k,array[10];//array declaration 2
printf(“Enter the array elements:”); 4
for(k=0;k<5;k++) 3
{ 1
scanf(“%d ”,&array[i]); // storing values in array 8
} Display the array elements

ww
printf(“\n Display the array elements:”); 2
for(k=0;k<5;k++) 4
3
{

w.E
1
printf(“%d \n”,array[i]);//displaying values of array
8
}
return 0;
}
asy
FIND SUM AND AVERAGE OF N NUMBERS
#include<stdio.h>
int main( )
{ En Output:
Enter the array size: 6

int k,n,sum=0;array[10];//array declaration


float avg; gin Enter the array elements
9
2
printf(“\n Enter the array size:”);
scanf(“%d”,&n);
printf(“\n Enter the array elements:”);
4
3
eer
for(k=0;k<n;k++)
{
1
8
ing
scanf(“%d ”,&array[i]); // storing values in array
}
sum=27 and avg=4.50000

.ne
for(k=0;k<n;k++)
{
sum=sum+array[i]; //sum of array elements
}
t
avg=sum/n;
printf(“\n sum=%d and avg=%f ”,sum,avg);
}
return 0; Output:
} Enter the array elements
REVERSE OF ARRAY ELEMENTS 2
#include<stdio.h> 4
int main( ) 3
{ 1
8
int k,n,array[10];//array declaration
Display the array elements
printf(“\n Enter the array size:”);
8
scanf(“%d”,&n);
1
printf(“\n Enter the array elements:”);
3
for(k=0;k<n;k++) 4
2

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


{
scanf(“%d ”,&array[i]); // storing values in array
}
printf(“\n array elements in reverse order:”);
for(k=n-1;k>=0;k--)
{
printf(“%d \n”,array[i]);//displaying values of array
}
return 0;
}
Write a program to print the position of the smallest number of n numbers using
arrays.

#include <stdio.h>
int main()
{
int i, n, arr[20], small, pos;

ww
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
printf("\n Enter the elements : ");

w.E
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
small = arr[0] Output
for(i=1;i<n;i++)
{ asy
Enter the number of elements in the array : 5
Enter the elements : 7 6 5 14 3
if(arr[i]<small)
{ En
The smallest element is : 3
The position of the smallest element in the
small = arr[i];
pos = i;
array is : 4
gin
}
}
eer
printf("\n The smallest element is : %d", small);
printf("\n The position of the smallest element in the array is:
%d", pos); ing
return 0;
} .ne
Program example-1 Printing binary equivalent of a decimal number using array t
Logic Here the remainders of the integer division of a decimal number by 2 are stored as
consecutive array elements.The division procedure is repeated until the number becomes 0.

#include <stdio.h> Output:


int main() Enter the decimal Integer: 12
{ Binary equivalent of 12 is: 1100
int bi[20],i,m,num,rem;
printf(“\n Enter the decimal Integer”);
scanf(“%d”,&n);
m=n;
for(i=0;i>n;i++)
{
rem=num%2;

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


bi[i]=rem;
num=num/2;
}
printf(“\n Binary equivalent of %d is: \t”,m);
for(i--;i>=0;i--)
printf(“%d”,a[i]);
return 0;
}
Program example- Fibonacci series using an array
Logic In Fibonacci series each element is the sum of the previous two elements. This
program stores the series in an array Display the fibonacci elements
0
#include <stdio.h> 1
int main() 1
2
{ 3
int fib[15]; // array declaration 5
int i; 8

ww
fib[0] = 0; // first array element value=0
fi b[1] = 1;// second array element value=1
13
21
34

{
w.E
for(i = 2; i < 15; i++)

fib[i] = fib[i-1] + fib[i-2];


55
89
144
}
asy
printf(“\n Display the fibonacci elements:”);
233
377
for(i = 0; i < 15; i++)
{
printf(“%d\n”, fi b[i]); En
}
return 0; gin
}
Example- Inserting an Element in an Array eer
ing
If an element has to be inserted at the end of an existing array, then the task of insertion is
quite simple. We just have to add 1 to the upper_ bound and assign the value. Here, we assume

contain 10 elements, but currently it has only 8 elements, then obviously there is space to
.ne
that the memory space allocated for the array is still available. For example, if an array is declared to

accommodate two more elements. But if it already has 10 elements, then we will not be ableto add
another element to it.
Program to insert a number at a given location in an array
#include <stdio.h>
t
int main()
{
int i, n, num, pos, arr[10];
clrscr();
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n arr[%d] = ", i);
scanf("%d", &arr[i]);
}
printf("\n Enter the number to be inserted : ");
scanf("%d", &num);
printf("\n Enter the position at which the number has to be added: ");

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


scanf("%d", &pos);
for(i=n–1;i>=pos;i––)
arr[i+1] = arr[i];
arr[pos] = num;
n = n+1;
printf("\n The array after insertion of %d is :num ");
for(i=0;i<n;i++)
printf("\n arr[%d] = %d", i, arr[i]);
getch();
return 0;
}
Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4

ww
arr[4] = 5
Enter the number to be inserted : 0
Enter the position at which the number has to be added : 3

arr[0] = 1
arr[1] = 2
w.E
The array after insertion of 0 is :

arr[2] = 3
arr[3] = 0 asy
arr[4] = 4
arr[5] = 5 En
3.Deleting an Element from an Array gin
Algorithm to delete an element from the middle of an array
eer
Step 1: [INITIALIZATION] SET I = POS
Step 2: Repeat Steps 3 and 4 while I <= N – 1 ing
Step 3: SET A[I] = A[I + 1]
Step 4: SET I = I + 1 .ne
[END OF LOOP]
Step 5: SET N = N – 1
Step 6: EXIT
t
Write a program to delete a number from a given location in an array.
#include <stdio.h>
int main()
{
int i, n, pos, arr[10];
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n arr[%d] = ", i);
scanf("%d", &arr[i]);
}
printf("\nEnter the position from which the number has to be deleted : ");

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


scanf("%d", &pos);
Output
for(i=pos; i<n–1;i++) Enter the number of elements in the array :
arr[i] = arr[i+1]; 5
n– –; arr[0] = 1
printf("\n The array after deletion is : "); arr[1] = 2
for(i=0;i<n;i++) arr[2] = 3
arr[3] = 4
printf("\n arr[%d] = %d", i, arr[i]); arr[4] = 5
getch(); Enter the position from which the number
return 0; has to be deleted : 3
} The array after deletion is :
arr[0] = 1
arr[1] = 2
LINEAR SEARCH arr[2] = 3
Searching an element within an array Consider anarr[3]
array= of
5 n elements, where each
element is a key (e.g., a number). The task is to find a particular key(number) in the array.
The simplest method is a sequential search or linear search. The idea is to simply search the
array, element by element, from the beginning until the key is found or the end of the list is
reached. If found, the corresponding position in the array is printed; otherwise, a message

ww
will have to be displayed that the key(number) is not found. Now, the implementation of the
program will be

Program:
w.E
#include <stdio.h>
#include <stdlib.h>
int main() asy
{
En
int n,i,key, FOUND=0, a[30]; // array declaration
printf(“\n How many numbers:”);
scanf(“%d”,&n); // array size
printf(“\n Enter the array elements: \n”); gin Output

for(i=0 ; i<n; i++)


{ eer
How many numbers: 6
Enter the array elements:
21
scanf(“%d”, &a[i]);
}
33
46 ing
.ne
printf(“\n Enter the key to be searched: ”); 52
27
scanf(“%d”,&key); Enter the key to be searched: 73
for(i=0 ; i<n; i++) // searching an element in an array
if(a[i] == key)
{
NOT FOUND
t
printf(“\n Found at %d”,i);
FOUND=1;
}
Output
if(FOUND = = 0)
printf(“\n NOT FOUND...”); How many numbers: 6
return 0; Enter the array elements:
} 21
33
46
52
27
Enter the key to be searched: 52
Found at 3

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

BINARY SEARCHING

In Binary searching the drawbacks of sequential search can be eliminated

The binary search halves the size of the list to search in each Iteration

Logic : Binary search can be explained simply by the analogy of searching for a page in a
book. Suppose a reader is searching for page 90 in a book of 150 pages. The reader would
first open the book at random towards the latter half of the book. If the page number is less
than 90, the reader would open at a page to the right; if it is greater than 90, the reader would
open at a page to the left, repeating the process till page 90 was found.

Binary search requires sorted data(in ascending order) to operate on.

In binary search, the following procedure is implemented.

ww  Look at the middle element of the list.


 If it is the value being searched, then the job is done.

w.E
 If the value that is being searched is smaller than the middle element, then continue
with the bottom half of the list.
 If the value that is being searched is larger than the middle element, then continue

asy
with the top half of the list.
Eg:-Depiction of binary search algorithm (the number to be searched is greater than mid
value)
En
gin
eer
Algorithm: The algorithm determines the position of T in the LIST.
1. START ing
2. PRINT “ENTER THE NO. OF ELEMENTS IN THE ARRAY”
3. INPUT N .ne
4. I=0
5. PRINT “ENTER ARRAY ELEMENT”
6. INPUT LIST(I)
7. I=I+1
t
8. IF I<N THEN GOTO STEP 5
9. PRINT “ENTER THE ELEMENT TO SEARCH”
10. INPUT T
11. HIGH = N - 1
12. LOW = 0
13. FOUND = 0
14. MID = (HIGH + LOW)/ 2
15. IF T = LIST [MID]
FOUND = 1
ELSE IF T < LIST[MID]
HIGH = MID-1
ELSE
LOW = MID+1
16. IF (FOUND =0) and (HIGH > = LOW) THEN GOTO STEP 14

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


17. IF FOUND =0 THEN PRINT “NOT FOUND”
18. ELSE PRINT “FOUND AT”, MID.
19. STOP
The C program for this algorithm is as follows:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[30],n,i,t,low,mid,high,found=0;
printf(“\n Enter the number of elements in the array:”);
scanf(“%d”,&n);
printf(“\n Enter the elements of the array:”);
for(i=0 ; i< n; i++)
scanf(“%d”, &a[i]);
printf(“\n Enter the element to search :”);
scanf(“%d”,&t);
low = 0;

ww
high = n - 1;
while(high >= low)
{

w.E
mid = (low + high) / 2;
if(a[mid] == t)
{
found = 1;
break; asy
}
else if (t < a[mid]) En
high = mid - 1;
else gin
low = mid + 1;
} eer
if(found==0)
printf(“\n NOT FOUND”); ing
else
printf(“\n FOUND AT %d”,mid);
.ne
return 0;
}
Output
Enter the number of elements in the array: 9 Enter the number of elements in the array 9
t
Enter the elements of the array: Enter the elements of the array:
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
Enter the element to search: 7 Enter the element to search: 7
FOUND AT 6 NOT FOUND

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

C PROGRAM FOR BUBBLE SORT


Bubble sort is a simple sorting algorithm in which each element is compared with adjacent element
and swapped if their position is incorrect. It is named as bubble sort because same as like bubbles the
lighter elements come up and heavier elements settle down.
It is less efficient as its average and worst case complexity is high, there are many other fast
sorting algorithms like quick-sort, heap-sort, etc. Sorting simplifies problem-solving in computer
programming.
Step by Step
– First Pass:
( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps them.
( 1 5 4 2 8 ) ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not
swap them.
– Second Pass:
(14258)(14258)
( 1 4 2 5 8 ) ( 1 2 4 5 8 ), Swap since 4 > 2

ww
(12458)(12458)
(12458)(12458)
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm

-Third Pass:
(12458)(12458)
w.E
needs one whole pass without any swap to know it is sorted.

(12458)(12458)
(12458)(12458)
(12458)(12458) asy
En
Finally, the array is sorted, and the algorithm can terminate.
Program
#include <stdio.h>
int main() gin
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
Output
eer
Enter number of elements
scanf("%d", &n);
printf("Enter %d integers\n", n);
5
Enter 5 integers ing
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
5 1 4 2
Sorted list in ascending order:
8
.ne
t
for (c = 0 ; c < n - 1; c++) 1 2 4 5 8
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c < n; c++)
printf("%d\n", array[c]);
return 0;
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

INSERTION SORT

This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which


is always sorted. For example, the lower part of an array is maintained to be sorted. An
element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate place and
then it has to be inserted there. Hence the name, insertion sort.

The array is searched sequentially and unsorted items are moved and inserted into the sorted
sub-list (in the same array). This algorithm is not suitable for large data sets as its average and
worst case complexity are of Ο(n2), where n is the number of items.

How Insertion Sort Works?

We take an unsorted array for our example.

ww
w.E
Insertion sort compares the first two elements.

asy
En
gin
It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list.

eer
ing
Insertion sort moves ahead and compares 33 with 27.
.ne
t
And finds that 33 is not in the correct position.

It swaps 33 with 27. It also checks with all the elements of sorted sub-list. Here we see that
the sorted sub-list has only one element 14, and 27 is greater than 14. Hence, the sorted sub-
list remains sorted after swapping.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10.... and so on.

Algorithm

Now we have a bigger picture of how this sorting technique works, so we can derive simple
steps by which we can achieve insertion sort.

Step 1 − If it is the first element, it is already sorted. return 1;


Step 2 − Pick next element

ww
Step
Step
the
3
4


Compare with all elements in the sorted sub-list
Shift all the elements in the sorted sub-list that is greater than

w.E
value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted

Program
asy
#include<stdio.h>
int main()
{ En
int data[100],n,temp,i,j;
gin
printf("Enter number of terms(should be less than 100): ");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0;i<n;i++) eer
Enter number of terms(should be less than 100):5
{

}
scanf("%d",&data[i]); Enter elements: 33 12 4 26 77
ing
for(i=1;i<n;i++)
{
In ascending order: 4 12 26 33 77
.ne
temp = data[i];
j=i-1;
while(temp<data[j] && j>=0)
/*To sort elements in descending order, change temp<data[j] to temp>data[j]
in above line.*/
t
{
data[j+1] = data[j];
--j;
}
data[j+1]=temp;
}
printf("In ascending order: ");
for(i=0; i<n; i++)
printf("%d\t",data[i]);
return 0;
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Ascending order
Step by step descriptive logic to sort array in ascending order.
1. Input size of array and elements in array. Store it in some variable say size and arr.
2. To select each element from array, run an outer loop from 0 to size - 1. The loop structure
must look like for(i=0; i<size; i++).
3. Run another inner loop from i + 1 to size - 1 to place currently selected element at its correct
position. The loop structure should look like for(j = i + 1; j<size; j++).
4. Inside inner loop to compare currently selected element with subsequent element and swap
two array elements if not placed at its correct position.
Which is if(arr[i] > arr[j]) then swap arr[i] with arr[j].
Program

#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
int main()
{
int arr[MAX_SIZE];

ww int size;
int i, j, temp;

w.E
printf("Enter size of array: ");
scanf("%d", &size);

asy
/* Input elements in array */
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
En
}

for(i=0; i<size; i++) gin


{

eer
/* Place currently selected element array[[i]to its correct place*/
for(j=i+1; j<size; j++)
{
/* Swap if currently selected ing
array element is not at its correct position.
*/
if(arr[i] > arr[j])
{ .ne
}
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp; t
}
}
/* Print the sorted array */
printf("\nElements of array in ascending order: ");
for(i=0; i<size; i++)
{
printf("%d\t", arr[i]);
}

return 0;
}
OUTPUT
Enter size of array: 10
Enter elements in array: 20 2 10 6 52 31 0 45 79 40
Elements of array in ascending order:
0 2 6 10 20 31 40 45 52 79

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

/*C program to sort an one dimensional array in descending order.*/


#include <stdio.h>
#define MAX 100
int main()
{
int arr[MAX],n,i,j;
int temp;

printf("Enter total number of elements: ");


scanf("%d",&n);

//read array elements


printf("Enter array elements:\n");
for(i=0;i< n;i++)
{
printf("Enter element %d: ",i+1);
scanf("%d",&arr[i]);
}

ww //sort array
for(i=0;i< n;i++)
{

{
w.E
for(j=i+1;j< n;j++)

if(arr[i]< arr[j])
{
temp
asy
=arr[i];
arr[i] =arr[j];

}
arr[j] =temp;

En
gin
}
}

printf("\nArray elements after sorting:\n");


for(i=0;i< n;i++)
{ eer
}
printf("%d\n",arr[i]);
ing
}
return 0;

.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


TWO DIMENTIONAL ARRAY

Two dimentional arrays stores data in tabular column format represented as rows and columns

Array Declaration:
datatype arrayname[size][size];

Array Initialization:
int a[2][2]={ {1,4 },{2,3}}

int b[2][2]={1,4,2,3}

1 4
2 3

ww float[ ][ ]={12.3, 45.2,19.3,23.4}

12.3 45.2

19.3 w.E
23.4

Accessing two-dimensional Arrays


asy
Program-sample two dimnentional array

En
#include <stdio.h>
int main()
{ gin
int i,j;
int a[3][2] = {{4,7},{1,0},{6,2}}; eer
for(i = 0; i < 3; i++)
{ ing
for(j = 0; j < 2; j++)
{ .ne
printf(“%d”, a[i][j]);
}
printf(“\n”);
}
t
return 0;
}
Row-1 4 7
Row -2 1 0
Row-3 6 2

The above array actually ‘looks’ like this

1 2 3 4 5 6 7 8 9
Row 0 Row 1 Row 2

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


WORKING WITH TWO-DIMENSIONAL ARRAYS

Transpose of a matrix

Example program:-Transpose of a matrix

Transpose of A is AT=(aji), where i is the row number and j is the column number.

Program

#include <stdio.h>

int main()
{
int a[10][10], transpose[10][10], r, c, i, j;
printf("Enter rows and columns of matrix: ");
scanf("%d %d", &r, &c);
Sample output
// getting elements of the matrix Enter rows and columns of

ww
printf("\nEnter elements of matrix:\n");
for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
matrix: 2
3

{
w.E
printf("Enter element a%d%d: ",i+1, j+1);
scanf("%d", &a[i][j]);
Enter element of matrix:
Enter element a11: 2
Enter element a12: 3

asy
} Enter element a13: 4
Enter element a21: 5
// Displaying the matrix a[][] */ Enter element a22: 6
printf("\n Entered Matrix: \n");
for(i=0; i<r; ++i)
En Enter element a23: 4

gin
for(j=0; j<c; ++j) Entered Matrix:
{ 2 3 4
printf("%d ", a[i][j]);
if (j == c-1)
printf("\n\n");
eer 5 6 4

// Finding the transpose of matrix a ing


Transpose of Matrix:
2 5
for(i=0; i<r; ++i)
for(j=0; j<c; ++j) 3 6
.ne
t
{
transpose[j][i] = a[i][j]; 4 4
}

// Displaying the transpose of matrix a


printf("\nTranspose of Matrix:\n");
for(i=0; i<c; ++i)
for(j=0; j<r; ++j)
{
printf("%d ",transpose[i][j]);
if(j==r-1)
printf("\n\n");
}

return 0;
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


Program -2(Transpose)

#include <stdio.h>

void main()
{
int array[10][10];
int i, j, m, n;

printf("Enter the order of the matrix \n");


scanf("%d %d", &m, &n);
printf("Enter the coefiicients of the matrix\n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &array[i][j]);
}
}
printf("The given matrix is \n");

ww for (i = 0; i < m; ++i)


{
for (j = 0; j < n; ++j)

w.E
{

}
printf(" %d", array[i][j]);

printf("\n");
}
asy
printf("Transpose of matrix is \n");
for (j = 0; j < n; ++j)
{
En
for (i = 0; i < m; ++i)
{

}
gin
printf(" %d", array[i][j]);

}
printf("\n");
eer
$ cc pgm85.c
$ a.out ing
Enter the order of the matrix
3 3
Enter the coefiicients of the matrix .ne
3 7 9
2 7 5
6 3 4
The given matrix is
t
3 7 9
2 7 5
6 3 4
Transpose of matrix is
3 2 6
7 7 3
9 5 4

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Matrix addition and subtraction

Addition If A and B above are matrices of the same type

Subtraction If A and B are matrices of the same type, then

Program to Add Two Matrices

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

wwint r, c, a[100][100], b[100][100], sum[100][100], i, j;

printf("Enter number of rows (between 1 and 100): ");

w.E
scanf("%d", &r);
printf("Enter number of columns (between 1 and 100): ");
scanf("%d", &c);

for(i=0; i<r; ++i)


for(j=0; j<c; ++j) asy
printf("\nEnter elements of 1st matrix:\n");
Output
{
En
printf("Enter element a%d%d: ",i+1,j+1);
Enter number of rows (between
1 and 100): 2

}
scanf("%d",&a[i][j]);
gin Enter number of columns
(between 1 and 100): 3
printf("Enter elements of 2nd matrix:\n");
for(i=0; i<r; ++i)
for(j=0; j<c; ++j) eer
Enter elements of 1st matrix:
Enter element a11: 2
{
printf("Enter element a%d%d: ",i+1, j+1); ing
Enter element a12: 3
Enter element a13: 4
Enter element a21: 5

}
scanf("%d", &b[i][j]); Enter element a22: 2
Enter element a23: 3
.ne
Enter elements of 2nd matrix:
// Adding Two matrices
for(i=0;i<r;++i)
for(j=0;j<c;++j)
{
Enter element a11: -4
Enter element a12: 5
Enter element a13: 3
Enter element a21: 5
t
sum[i][j]=a[i][j]+b[i][j]; Enter element a22: 6
} Enter element a23: 3
// Displaying the result
printf("\nSum of two matrix is: \n\n"); Sum of two matrix is:
for(i=0;i<r;++i)
for(j=0;j<c;++j) -2 8 7
{
10 8 6
printf("%d ",sum[i][j]);
if(j==c-1)
{
printf("\n\n");
}
}
return 0;
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Matrix multiplication

Matrix multiplication for two 2 × 2 matrices.

Finding norm of a matrix


The norm of a matrix is defi ned as the square root of the sum of the squares of the elements of a matrix.

#include <stdio.h>
#include <math.h>
#defi ne row 10
#defi ne col 10
int main()
{
fl oat mat[row][col], s;

ww
int i,j,r,c;
printf(“\n Input number of rows:”);
scanf(“%d”, &r);
w.E
printf(“\n Input number of cols:”);
scanf(“%d”, &c);
for(i = 0 ; i< r; i++)
{ asy
for(j = 0 ;j<c; j++)
{ En
scanf(“%f”, &mat[i][j]);
} gin
}
printf(“\n Entered 2D array is as follows:\n”);
eer
for(i = 0; i < r; i++)
{
for(j = 0; j < c; j++) ing
{
printf(“%f”, mat[i][j]); .ne
}
printf(“\n”);
}
t
s = 0.0;
for(i = 0; i < r; i++)
{
for(j = 0; j < c; j++)
{
s += mat[i][j] * mat[i][j];
}
}
printf(“\n Norm of above matrix is: %f”, sqrt(s));
return 0;
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


C Program to read a matrix and find sum, product of all elements of two dimensional (matrix)
array
include <stdio.h>
#define MAXROW 10 Enter number of Rows :3
#define MAXCOL 10 Enter number of Cols :3
int main()
{ Enter matrix elements :
int matrix[MAXROW][MAXCOL]; Enter element [1,1] : 1
int i,j,r,c; Enter element [1,2] : 1
int sum,product; Enter element [1,3] : 1
Enter element [2,1] : 2
printf("Enter number of Rows :");
Enter element [2,2] : 2
scanf("%d",&r);
Enter element [2,3] : 2
printf("Enter number of Cols :");
scanf("%d",&c);
Enter element [3,1] : 3
Enter element [3,2] : 3
printf("\nEnter matrix elements :\n"); Enter element [3,3] : 3
for(i=0;i< r;i++)
{ SUM of all elements : 18

ww for(j=0;j< c;j++)
{
Product of all elements :216

printf("Enter element [%d,%d] : ",i+1,j+1);

} w.E }
scanf("%d",&matrix[i][j]);

sum=0;
product=1;
for(i=0;i< r;i++) asy
{
for(j=0;j< c;j++)
En
{
sum+=matrix[i][j];
gin
product*= matrix[i][j];
} }
eer
printf("\nSUM of all elements : %d \nProduct of all elements :%d",sum,product);

}
return 0;

Find the sum of diagonal elements of a matrix 1 2 3 ing


#include < stdio.h >
int main() 2
3
4
5
6
8 .ne
t
{
int a[10][10],i,j,sum=0,r,c;
clrscr(); Sum of diagonal=13
printf("\n Enter the number of rows and column ");
scanf("%d%d",&r,&c);
printf("\nEnter the %dX%d matrix",r,c);
for(i=0;i < r;i++)
{
for(j=0;j < c;j++)
{
scanf("%d",&a[i][j]);
}//for
}//for
for(i=0;i < r;i++)
{ for(j=0;j < c;j++)
{ if(i==j)
{
sum+=a[i][j];
}
}//for

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


}//for
printf("\nThe sum of diagonal elements is %d",sum); return 0;
}//main

Sum of rows and columns


#include <stdio.h>
void main () Output
{
int array[10][10]; Enter the order of the matrix
int i, j, m, n, sum = 0; 22
printf("Enter the order of the matrix\n"); Enter the co-efficients of the matrix
scanf("%d %d", &m, &n); 23 45
printf("Enter the co-efficients of the matrix\n");
for (i = 0; i < m; ++i) 80 97
{ Sum of the 0 row is = 68
for (j = 0; j < n; ++j) Sum of the 1 row is = 177
{ Sum of the 0 column is = 103
scanf("%d", &array[i][j]); Sum of the 1 column is = 142
}

ww }

{
for (i = 0; i < m; ++i)

{
w.E
for (j = 0; j < n; ++j)

sum = sum + array[i][j] ;


}

asy
printf("Sum of the %d row is = %d\n", i, sum);
sum = 0;
}
sum = 0;
En
for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i) gin
{
sum = sum + array[i][j];
eer
}
printf("Sum of the %d column is = %d\n", j, sum);
sum = 0; ing
}
}
.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


C Program to do the Sum of the Main & Opposite Diagonal Elements of a MxN Matrix

#include <stdio.h>
void main ()
{ static int array[10][10]; Enter the order of the matix
int i, j, m, n, a = 0, sum = 0; 22
printf("Enetr the order of the matix \n"); Enter the co-efficients of the matrix
scanf("%d %d", &m, &n); 40 30
if (m == n ) 38 90
{ The given matrix is
printf("Enter the co-efficients of the matrix\n"); 40 30
for (i = 0; i < m; ++i) 38 90
{
for (j = 0; j < n; ++j) The sum of the main diagonal elements is
{ = 130
scanf("%d", &array[i][j]); The sum of the off diagonal elements is
} = 68
}
printf("The given matrix is \n");

ww for (i = 0; i < m; ++i)


{
for (j = 0; j < n; ++j)
{

} w.E
printf(" %d", array[i][j]);

}
printf("\n");

asy
for (i = 0; i < m; ++i)
{
En
}
sum = sum + array[i][i];
a = a + array[i][m - i - 1];
gin
eer
printf("\nThe sum of the main diagonal elements is = %d\n", sum);
printf("The sum of the off diagonal elements is = %d\n", a);
}
else
printf("The given order is not square matrix\n"); ing
}
.ne
t
C Program to Find the Frequency of Odd & Even Numbers in the given Matrix
#include <stdio.h>
void main()
{

static int array[10][10];


int i, j, m, n, even = 0, odd = 0;

printf("Enter the order ofthe matrix \n");


scanf("%d %d", &m, &n);

printf("Enter the coefficients of matrix \n");


for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &array[i][j]);
if ((array[i][j] % 2) == 0)
{
++even;

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


}
else
++odd;
}

printf("The given matrix is \n");


for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
printf(" %d", array[i][j]);
}
printf("\n");
}
printf("\n The frequency of occurrence of odd number = %d \n", odd);
printf("The frequency of occurrence of even number = %d\n", even);

ww}

Enter the order of the matrix


33
w.E
Enter the coefficients of matrix
34 36 39
23 57 98
12 39 49
The given matrix is asy
34 36 39
23 57 98
En
12 39 49

The frequency of occurrence of odd number = 5 gin


The frequency of occurrence of even number = 4
eer
ing
.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

STRINGS:

Strings in C are represented by arrays of characters. The end of the string is marked with a
special character, the null character

• string.h : collection of functions for string manipulation.

DECLARATION OF STRINGS

• Strings are declared in a similar manner as arrays char s[5];

• Strings can also be declared using pointer


char *p;

ww
Syntax: datatype string name[size];

w.E
char str[30];
char text[80];
STRING INITIALIZATION

char var[ ]=“hello”;


asy
En
gin
eer
ing
‘\0’ (NULL) charater would automatically be inserted at the end of string.
.ne
char arr[4]={‘s’,'h’,'b',’r‘,’\0’}

char arr[]={‘hello’, ‘good’ ,‘day’, ‘please’}


t
char Str = “abcdefg”

char greeting[] = “welcome";

char greeting[6] = {'H', 'e', 'l', 'l', 'o'};

char *c = "abcd";

char str=“100”

char str=“3.4”

Char str=“111000”

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


STRING INPUT /OUTPUT #include <stdio.h>
#include <string.h>
– printf("%s",str), scanf("%s",str) int main()
{
– gets(str),puts(str) char nickname[20];
scanf("%s", nickname);
– fgets with stdin and fputs with stdout printf("%s",nickname);
return 0;
– fgets( ) and fputs( )…for files }

Eg char s[1000] ; #include <stdio.h> #include <stdio.h>


fgets(s,1000,stdin); #include <string.h> #include <string.h>
int main() int main()
Example program { {
#include <stdio.h> char nickname[20]; char nickname[20];
int main() gets(nickname); fgets(nickname,20,stdin);
{ puts(nickname); fputs(nickname,stdout);
char name[10]; return 0; return 0;

ww
printf("Who are you? ");
fgets(name,10,stdin);
} }

return(0);
} w.E
printf("Glad to meet you, %s \n",name);

asy
String input and output using fscanf() and fprintf()
C program has three I/O streams.



stdin,
En
gin
stdout, and
 stderr

eer
--The input stream is called standard-input (stdin); the usual output stream is called standard-

ing
output (stdout); and the side stream of output characters for errors is called standard error
(stderr).

--Internally they represent file descriptors 0, 1, and 2 respectively.


.ne
--Calls to fprinf() and fscanf() differ significantly from calls to printf() and scanf().
--fprintf() sends formatted output to a stream and fscanf() scans and formats input from a
stream. t
Example program
#include <stdio.h>
int main()
{
int fi rst, second;
fprintf(stdout,“Enter two ints in this line: ”);
fscanf(stdin,“%d %d”, &fi rst, &second);
fprintf(stdout,“Their sum is: %d.\n”, fi rst + second);
return 0;
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


Character Manipulation

Table: Character functions in <ctype.h> where c is the character argument


ialnum(c) Returns a non-zero if c is alphabetic or numeric
isalpha(c) Returns a non-zero if c is alphabetic
scntrl(c) Returns a non-zero if c is a control character
isdigit(c) Returns a non-zero if c is a digit, 0 – 9
isgraph(c) Returns a non-zero if c is a non-blank but printing character
islower(c) Returns a non-zero if c is a lowercase alphabetic character, i.e., a – z
isprint(c) Returns a non-zero if c is printable, non-blanks and white space included
ispunct(c) Returns a non-zero if c is a printable character, but not alpha, numeric, or blank
isspace(c) Returns a non-zero for blanks and these escape sequences: ‘\f’, ‘\n’, ‘\r’, ‘\t’, and
‘\v’
isupper(c) Returns a non-zero if c is a capital letter, i.e., A – Z
isxdigit(c) Returns a non-zero if c is a hexadecimal character: 0 –9, a – f, or A – F

ww
tolower(c) Returns the lowercase version if c is a capital letter; otherwise returns c
toupper(c) Returns the capital letter version if c is a lowercase character; otherwise returns c

w.E
This program counts the number of words in a string
#include <stdio.h>
converts a given text into a capital letter
using toupper() function
#include <ctype.h>
int main()
{ asy #include <stdio.h>
#include <string.h>

En
char s[30]; int main()
int i=0,count=0;
printf(“\n enter the string\n”);
{
scanf(“%[^\n]”,s);
while(s[i]!=‘\0’)
{ gin
char a[30];
int i=0;
printf(“\n enter the string\n”);
while(isspace(s[i]))
i++;
if(s[i]!=‘\0’)
gets(a);
eer
while(a[i]!=‘\0’)
{
++count;
while(!isspace(s[i]) && s[i] != ‘\0’)
{
a[i]=toupper(a[i]);
i++; ing
i++;
}
}
}
a[i]=‘\0’; .ne
printf(“\n NO. of words in the string is %d:”, count);
return 0;
}
Output:
puts(a);
return 0;
}
Output:
t
enter the string
enter the string
how are you
how
NO. of words in the string is HOW
3

Disadvantage : C has the weakest character string capability. Strictly speaking, there are no
character strings in C, just arrays of single characters.

What character manupilation cannot do


o Assign one to the other: s1 = s2;
o Compare them for collating sequence: s1 < s2
o Concatenate them to form a single longer string: s1 + s2
o Return a string as the result of a function

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

String Manipulation

A set of standard C library functions that are contained in <string.h> provides the following.

Function Description
strcpy(s1,s2) Copies s2 into s1
strncpy(s1,s2,n) It copies first n characters of str2 into str1.
strcat(s1,s2) Concatenates s2 to s1. That is, it appends the string contained by s2 to
the end of the string pointed to by s1. The terminating null character
strncat(s1,s2,n) First n characters of str2 is concatenated at the end of str1
strlen(s1) Returns the length of s1. That is, it returns the number of characters in
the string without the terminating null character.
strcmp(s1,s2) Returns 0 if s1 and s2 are the same
Returns less than 0 if s1<s2
Returns greater than 0 if s1>s2
strncmp(s1,s2,n) Returns 0 if s1 and s2 are the same for first n characters

ww
strcmpi( ) Same as strcmp() function. But, this function negotiates case. “A”
and “a” are treated as same.
strchr(s1,ch)
strrchr(s1,ch )
strstr(s1,s2) w.E Returns pointer to first occurrence ch in s1
Returns pointer tolast occurrence ch in s1
Returns pointer to first occurrence s2 in s1
strlen( )
strdup( ) asy
function in C gives the length of the given string
function in C duplicates the given string
strlwr( )
strupr( )
En
function converts a given string into lowercase
function converts a given string into uppercase
strrev( )
gin
function reverses a given string in C language

strcat ( str1, str2 )


#include <stdio.h>
Source string = APPLE
Target string = LIME
eer
strncat ( str1, str2, n )
#include <stdio.h>
#include <string.h>
Source string = APPLEJUICE
Target string = LIME
Target string after strcat( ) =

ing
#include <string.h> Target string after strcat( ) =
LIME APPL
int main( ) LIME APPLE int main( )
{ { char source[ ] = " APPLEJIUCE" ;
char source[ ] = " APPLE" ;
char target[ ]= " LIME" ;
printf ( "\nSource string = %s", source ) ;
char target[ ]= “LIME" ;
printf ( "\nSource string = %s", source ) ;
printf ( "\nTarget string = %s", target ) ; .ne
printf ( "\nTarget string = %s", target ) ;
strcat ( target, source ) ;
printf ( "\nTarget string after strcat( ) = %s", target ) ;
return 0;
;
strncat ( target, source, 4 ) ;
printf ( "\nTarget string after strncat( ) = %s", target )

return 0;}
t
}

strcpy(str2,str1) source string = one strcpy(str2,str1,n) source string = mindblowing


#include <stdio.h> target string #include <stdio.h> target string =
#include <string.h> target string after strcpy( ) = one #include <string.h> target string after strncpy( ) =
int main( ) int main( ) mindb
{ {
char source[ ] = "fresh2refresh" ; char source[ ] = “mindblowing" ;
char target[20]= "" ; char target[20]= "" ;
printf ( "\n source string = %s", source ) ; printf ( "\n source string = %s", source ) ;
printf ( "\n target string = %s", target ) ; printf ( "\n target string = %s", target ) ;
strcpy ( target, source ) ; strncpy ( target, source, 5 ) ;
printf ( "\n target string after strcpy( ) = %s", target ) ; printf ( "\ntarget string after strcpy( ) = %s", target ) ;
return 0; return 0;}
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


strlen( ) strcmp(str1,str20 strcmp(str1, str2)
#include <stdio.h> string length = #include <stdio.h> = 32
#include <string.h> 6 #include <string.h> strcmp(str1, str3)
int main( ) int main() = 0 (same)
{ {
int len; char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
char str[20]=“APPLE" ; int result;
len = strlen(str) ; result = strcmp(str1, str2);
printf ( "\string length = %d \n" , len ) ; printf("strcmp(str1, str2) = %d\n", result);
return 0; result = strcmp(str1, str3);
} printf("strcmp(str1, str3) = %d\n", result);
return 0;
}

strchr(str,ch ) first occurrence of strrchr(str,ch ) Last occurrence of


character “i” in This is a character “i” in This is
#include <stdio.h> string for testing” is 3 #include <stdio.h> a string for testing” is
#include <string.h> #include <string.h> 26
int main () int main ()
{
ww
char string[55] ="This is a string for testing";
char *p;
{
char string[55] ="This is a string for testing";
char *p;

w.E
p = strchr (string,‘i');
printf ("First occurrence of character "i" in %s "
is” %s, string, p);
p = strrchr (string,'i');
printf ("Last occurrence of character "i" in "%s
is”, string, p);
return 0;
}
asy return 0;
}

En
strlwr(
return) 0; Output:
modify this
strupr( )
gin Output:
MODIFY THIS STRING TO
#include<stdio.h>
}
#include<string.h>
int main()
string to lower #include<stdio.h>
#include<string.h>
int main() eer
UPPER

{
char str[ ] = "MODIFY This String To
LOwer";
{
ing
char str[ ] = "Modify This String To Upper";
printf("%s\n",strupr(str));
printf("%s\n",strlwr (str));
return 0; }
return 0;
.ne
}
t
strrev( ) OUTPUT strset( ) Original string is : Test String
String before strrev( ) : Hello Test string after strset() :
#include<stdio.h> String after strrev( ) : olleH #include<stdio.h> ###########
#include<string.h> #include<string.h>
int main() int main()
{ {
char name[30] = "Hello"; char str[20] = "Test String";
printf("String before strrev( ): %s\n",name); printf("Original string is : %s", str);
printf("String after strrev( ) : %s",strrev(name)); printf("Test string after strset() : %s",strset(str,'#'));
return 0; printf("After string set: %s",str);
} return 0;
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Conversion functions

Typecast Function Description


atoi( ) Converts string to integer
atof( ) Converts string to float
atol( ) Converts string to long
itoa( ) Converts integer to string
ltoa( ) Converts long to string

atoi function atof function itoa( )-Converts integer to string


#include <stdio.h> #include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h> #include <stdlib.h> Output:
int main() #include <string.h> Binary value =
int main() { int main() 1101010000110101
{ char a[10] = "3.14"; { Decimal value = 54325
char a[10] = "100"; float pi = atof(a); int a=54325; Hexadecimal value = D435
int value = atoi(a); printf("Value of pi = %f\n", char buffer[20];

}
ww
printf("Value = %d\n", value);
return 0;
pi);

}
return 0;
itoa(a,buffer,2);
printf("Binary value = %s\n", buffer);
itoa(a,buffer,10);
Output:
Value = 100 w.E Output:
Value of pi = 3.140000
printf("Decimal value = %s\n", buffer);
itoa(a,buffer,16);
printf("Hexadecimal value = %s\n", buffer);

SCANSET asy }
return 0;


En
This conversion facility allows the programmer to specify the set of characters that are (or


are not) acceptable as part of the string.
gin
eer
A scanset conversion consists of a list of acceptable characters enclosed within square
brackets.

Program-1
#include<stdio.h>
Program-2
#include<stdio.h> ing
.ne
int main() int main()
{ {
char str[50]; char str[50];
printf(“Enter a string in lower case:”);
scanf(“%[a-z]”,str);
printf(“The string was : %s\n”,str);
return 0;
}
printf(“Enter a string in lower case:”);
scanf(“%[^a-z]”,str);
printf(“The string was : %s\n”,str);
return 0;
}
t
Output
Output Enter a string in lower case: abcd1234
(a) Enter a string in lower case: hello world The string was : 1234
The string was: hello world

(b) Enter a string in lower case: hello, world


The string was: hello
[In the second case, the character, ‘,’ (comma)
is not in the specified range.]

(c) Enter a string in lower case: abcd1234


The string was : abcd
[In the third case, the digit 1234 is not in
the specified range.]

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

STRING ARRAY [ONE DIMENTIONAL ]

CHAR/STRING ARRAY DECLARATION


String array are one-dimensional array of characters terminated by a null character '\0'.
 Character Array
char arr[]={‘s’,'h’,'b',’r'}
char arr[]={‘hello’, ‘good’ ,‘day’, ‘please’}
char Str = “abcdefg”
char greeting[] = "Hello";
char greeting[6] = {'H', 'e', 'l', 'l', 'o'};

ww
String Array

w.E
String Array = {“abc”, ”def”, “ghi”}

STRING ARRAY [TWO DIMENTIONAL ]


asy
En
Declaration of a two-dimensional array of strings.

gin
A two-dimensional array of strings can be declared as follows:
<data_type> <string_array_name>[<row_size>][<columns_size>];

char s[5][30]; eer


ing
Initialization
.ne
Two-dimensional string arrays can be initialized as shown

char s[5][10] ={“Cow”,”Goat”,”Ram”,”Dog”,”Cat”};


t
which is equivalent to

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET

Example program : Search a character in a string


#include<stdio.h>
int main() { Enter a string: apple lime juice
char str[20], ch;
int count = 0, i; Enter the character to be searched : i
printf("\nEnter a string : "); Character i is present
scanf("%s", &str);

printf("\nEnter the character to be searched : ");


scanf("%c", &ch);

for (i = 0; str[i] != '\0'; i++) {


if (str[i] == ch)
count++;
}
if (count == 0)
printf("\n Character '%c'is not present", ch);

ww else
printf("\n Character '%c'is present", ch);

}
w.E
return 0;

binary search for strings


#include <stdio.h>
#include <string.h> asy
void main()
{
int i,n,low,high,mid; En enter the number of names to be added
4
char a[50][50],key[20];
printf("enter the number of names to be added\n");
scanf("%d",&n); gin
enter the name in ascending order
mango

eer
jackfruit
printf("enter the name in ascending order\n"); apple
for(i=0;i<=n-1;i++)
grapes

ing
{
scanf("%s",&a[i]); enter the name to be searched
} oranges

.ne
printf("\n"); name not found
printf("enter the name to be searched\n");
scanf("%s",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
t
if (strcmp(key,a[mid])==0)
{
printf("key found at the position %d\n",mid+1);
exit(0);
}
else if(strcmp(key,a[mid])>0)
{
high=high;
low=mid+1;
}
else
{
low=low;
high=mid-1;
}
}
printf("name not found\n");
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


Program to Sort String Characters in string
#include <stdio.h>
#include <string.h>
int main (void) {
char string[] = "simplyeasylearning"; OUTPUT
char temp; String before sorting - simplyeasylearning
String after sorting - aaeegiillmnnprssyy
int i, j;
int n = strlen(string);

printf("String before sorting - %s \n", string);

for (i = 0; i < n-1; i++) {


for (j = i+1; j < n; j++) {
if (string[i] > string[j]) {
temp = string[i];
string[i] = string[j];
string[j] = temp;
}
}

ww }
printf("String after sorting - %s \n", string);
return 0;
}

w.E
program to sort the names of students.
#include <stdio.h>
#include <string.h>
int main()
{
char names[5][10], temp[10]; asy
int i, n, j;
clrscr();
printf("\n Enter the number of students : ");
En
scanf("%d", &n);
for(i=0;i<n;i++)
{ gin
eer
printf("\n Enter the name of student %d : ", i+1);
scanf(“%s”,&names[i]);
}

ing
for(i=0;i<n;i++)
{
for(j=0;j<n–i–1;j++)
{
if(strcmp(names[j], names[j+1])>0)
{
strcpy(temp, names[j]); .ne
strcpy(names[j], names[j+1]);
strcpy(names[j+1], temp);
}
}
}
t
printf("\n Names of the students in alphabetical order are : ");
for(i=0;i<n;i++)
{ printf(“%s \n”,names[i]);
}
return 0;
}
Output
Enter the number of students : 3
Enter the name of student 1 : Goransh
Enter the name of student 2 : Aditya
Enter the name of student 3 : Sarthak
Names of the students in alphabetical order are :
Aditya
Goransh
Sarthak

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


Eg Program to count vowels, consonants etc.
#include <stdio.h>
int main()
{
char line[150];
int i, vowels, consonants, digits, spaces;
vowels = consonants = digits = spaces = 0;
printf("Enter a line of string: ");
scanf("%[^\n]", line);
for(i=0; line[i]!='\0'; ++i)
{
if(line[i]=='a' || line[i]=='e' || line[i]=='i' ||
line[i]=='o' || line[i]=='u' || line[i]=='A' ||
line[i]=='E' || line[i]=='I' || line[i]=='O' ||

ww {
line[i]=='U')

} w.E
++vowels;

asy
else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
{

En
++consonants;
}
else if(line[i]>='0' && line[i]<='9')
{
gin
}
++digits;

eer
else if (line[i]==' ')
{
ing
}
++spaces;

.ne
}
printf("Vowels: %d",vowels);
printf("\nConsonants: %d",consonants);
t
printf("\nDigits: %d",digits);
printf("\nWhite spaces: %d", spaces);
return 0;
}
Output

Enter a line of string: adfslkj34 34lkj343 34lk


Vowels: 1
Consonants: 11
Digits: 9
White spaces: 2

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


Length of String Without Using strcat( )

#include <stdio.h>
int main()
{
char s[1000], i;

printf("Enter a string: ");


scanf("%s", s);

for(i = 0; s[i] != '\0'; ++i);

printf("Length of string: %d", i);


return 0;
}
Output
Enter a string: apple

ww
Length of string: 5

w.E
copy Two Strings Without Using strcpy( )

#include <stdio.h>
int main()
{
char s1[100], s2[100], i;
asy
printf("Enter string s1: ");
scanf("%s",s1); En
for(i = 0; s1[i] != '\0'; ++i)
{ gin
}
s2[i] = s1[i];

s2[i] = '\0'; eer


printf("String s2: %s", s2);
return 0; ing
}
Output
.ne
Enter String s1: apple
String s2: apple t

program to convert the lower case characters of a string into upper case without using string
functions

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


#include <stdio.h>
int main()
{ Output
char str[100], upper_str[100]; Enter the string : Hello
The string converted into upper case is : HELLO
int i=0;
clrscr();
printf("\n Enter the string :");
gets(str);
while(str[i] != '\0')
{
if(str[i]>='a' && str[i]<='z')
upper_str[i] = str[i] – 32;
else
upper_str[i] = str[i];
i++;
}
upper_str[i] = '\0';
printf("\n The string converted into upper case is : ");
puts(upper_str);
return 0;
}
ww
program to compare two strings without using string function
#include <stdio.h>

int main()
{ w.E
#include <string.h>

char str1[50], str2[50];

asy
int i=0, len1=0, len2=0, same=0;
clrscr();
printf("\n Enter the first string : ");
gets(str1);
En
gin
printf("\n Enter the second string : ");
gets(str2);
len1 = strlen(str1);
len2 = strlen(str2);
if(len1 == len2)
{ eer
while(i<len1)
{
ing
.ne
if(str1[i] == str2[i])
i++;
else break;
}
if(i==len1)
{
same=1;
t
printf("\n The two strings are equal");
}
}
if(len1!=len2)
printf("\n The two strings are not equal");
if(same == 0)
{
if(str1[i]>str2[i])
printf("\n String 1 is greater than string 2");
else if(str1[i]<str2[i])
printf("\n String 2 is greater than string 1");
}
return 0;
}
Write a program to reverse a given string without using string function
#include <stdio.h>

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


#include <conio.h>
#include <string.h>
int main() Output
{ Enter the string: Hi there
char str[100], reverse_str[100], temp; The reversed string is: ereht iH
int i=0, j=0;
clrscr();
printf("\n Enter the string : ");
gets(str);
j = strlen(str)–1;
while(i < j)
{
temp = str[j];
str[j] = str[i];
str[i] = temp;
i++;
j––;
}
printf("\n The reversed string is : ");
puts(str);

ww
getch();
return 0;
}

#include <stdio.h>
int main () w.E
C program to change case from upper to lower and lower to upper without using string function

asy
{ o/p
int i = 0; Input a string
char ch, s[1000]; file ABC

printf("Input a string\n");
En the string is
FILEabc
gets(s);

while (s[i] != '\0') { gin


ch = s[i];
if (ch >= 'A' && ch <= 'Z') // convrt to lower case
s[i] = s[i] + 32; eer
else if (ch >= 'a' && ch <= 'z') //convert to upper case
s[i] = s[i] - 32; ing
.ne
i++;
}
Printf(“\n the string is:”)

}
printf("%s\n", s);
return 0;

C Program to Count Number of Words in a given Text or Sentence


t
#include <stdio.h>
#include <string.h>
void main() o/p
{ enter the string
char s[200]; hello how are you friends
int count = 0, i; number of words in given string are: 5
printf("enter the string\n");
scanf("%[^\n]s", s);
for (i = 0;s[i] != '\0';i++)
{ if (s[i] == ' ')
count++; }
printf("number of words in given string are: %d\n", count + 1);
return 0;
}
Palindrome program in C language using built in functions

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


#include <stdio.h>
#include <string.h>
o/p
int main()
Enter a string to check if it is a palindrome
{
wow
char a[100], b[100];
Entered string is a palindrome
printf("Enter a string to check if it is a palindrome\n");
gets(a);
strcpy(b,a);
strrev(b);
if (strcmp(a,b) == 0)
printf("Entered string is a palindrome.\n");
else
printf("Entered string isn't a palindrome.\n");
return 0;
}
Palindrome program in C language without using built in functions
#include <stdio.h>
#include <string.h>
int main(){

wwchar string1[20]; o/p


int i, length; Enter a string:wow
int flag = 0; wow is not a palindrome

w.E
printf("Enter a string:");
scanf("%s", string1);
length = strlen(string1);
for(i=0;i < length ;i++){

asy
if(string1[i] != string1[length-i-1]){
flag = 1;

}}
break;

En
}
if (flag) {
printf("%s is not a palindrome", string1);
gin
else {
printf("%s is a palindrome", string1);
eer
}
}
return 0;
ing
C program to find the frequency of characters in a string
#include <stdio.h> Enter a string .ne
t
#include <string.h> maple tree
int main() a occurs 1 times in the string
{ e occurs 3 times in the string
char string[100]; l occurs 1 times in the string
int c = 0, count[26] = {0}, x; m occurs 1 times in the string
printf("Enter a string\n"); p occurs 1 times in the string
gets(string); r occurs 1 times in the string
while (string[c] != '\0') { t occurs 1 times in the string
/** Considering characters from 'a' to 'z'
only and ignoring others. */
if (string[c] >= 'a' && string[c] <= 'z') {
x = string[c] - 'a';
count[x]++;
}
c++;
}
for (c = 0; c < 26; c++)
printf("%c occurs %d times in the string.\n", c + 'a', count[c]);
return 0; }

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


C program to swap two strings
#include <stdio.h>
#include <string.h>
int main()
{
char first[100], second[100], temp[100];

printf("Enter first string\n");


gets(first);

printf("Enter second string\n");


gets(second);

printf("\nBefore Swapping\n");
printf("First string: %s\n", first);
printf("Second string: %s\n\n", second);

strcpy(temp, first);
strcpy(first, second);
strcpy(second, temp);

ww
printf("After Swapping\n");
printf("First string: %s\n", first);

w.E
printf("Second string: %s\n", second);

return 0;

asy
}
Write a program to extract a substring from the middle of a given string.
#include <stdio.h>
#include <conio.h>
int main()
{ En
char str[100], substr[100];
int i=0, j=0, n, m; gin
clrscr();
printf("\n Enter the main string : ");
gets(str); eer
printf("\n Enter the position from which to start the substring: ");
scanf("%d", &m);
printf("\n Enter the length of the substring: "); ing
scanf("%d", &n);
i=m; .ne
while(str[i] != '\0' && n>0)

substr[j] = str[i];
i++;
t
j++;
n––;
}
substr[j] = '\0';
printf("\n The substring is : ");
puts(substr);
getch();
return 0;
}
Output
Enter the main string : Hi there
Enter the position from which to start the substring: 1
Enter the length of the substring: 4
The substring is : i th

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


Write a program to insert a string in the main text.
#include <stdio.h>
int main()
{
char text[100], str[20], ins_text[100];
int i=0, j=0, k=0,pos;
clrscr();
printf("\n Enter the main text : ");
gets(text);
printf("\n Enter the string to be inserted : ");
gets(str);
printf("\n Enter the position at which the string has to be inserted: ");
scanf("%d", &pos);
while(text[i]! = '\0')
{
if(i==pos) Output
{ Enter the main text : newsman
while(str[k] != '\0') Enter the string to be inserted : paper
{ Enter the position at which the string has to be
ins_text[j] = str[k]; inserted: 4

ww
j++;
k++;
}
The new string is: newspaperman

}
else
{ w.E
ins_text[j] = text[i];
j++;
} asy
i++;
}
En
gin
ins_text[j] = '\0';
printf("\n The new string is : ");
puts(ins_text);
getch();
return0;
} eer
Write a program to delete a substring from a text.
#include <stdio.h>
int main() ing
{
char text[200], str[20], new_text[200];
int i=0, j=0, found=0, k, n=0, copy_loop=0;
Output
.ne
Enter the main text : Hello, how are you?
clrscr();
printf("\n Enter the main text : ");
gets(text);
printf("\n Enter the string to be deleted : ");
gets(str);
Enter the string to be deleted : , how are
you?
The new string is : Hello t
while(text[i]!='\0')
{
j=0, found=0, k=i;
while(text[k]==str[j] && str[j]!='\0')
{
k++;
j++;
}
if(str[j]=='\0')
copy_loop=k;
new_text[n] = text[copy_loop];
i++;
copy_loop++;
n++;
}
new_str[n]='\0';
printf("\n The new string is : ");
puts(new_str);
return 0;

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT EASYENGINEERING.NET


}
Write a program to replace a pattern with another pattern in the text.
#include <stdio.h>
#include <conio.h>
main()
{
char str[200], pat[20], new_str[200], rep_pat[100];
int i=0, j=0, k, n=0, copy_loop=0, rep_index=0;
clrscr();
printf("\n Enter the string : ");
gets(str);
printf("\n Enter the pattern to be replaced: ");
gets(pat);
printf("\n Enter the replacing pattern: ");
gets(rep_pat);
while(str[i]!='\0')
{
j=0,k=i;
while(str[k]==pat[j] && pat[j]!='\0')

{
k++;
j++;
}

{
ww
if(pat[j]=='\0')

copy_loop=k;
while(rep_pat[rep_index] !='\0')
{

w.E
new_str[n] = rep_pat[rep_index];
rep_index++;
n++;
}
}
new_str[n] = str[copy_loop]; asy
En
i++;
copy_loop++;
n++;

gin
}
new_str[n]='\0';
printf("\n The new string is : ");
puts(new_str);
getch();
return 0;
} eer
Output
Enter the string : How ARE you?
Enter the pattern to be replaced : ARE ing
Enter the replacing pattern : are
The new string is : How are you?
.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


SYLLABUS --UNIT II-FUNCTIONS, POINTERS, STRUCTURES AND UNIONS

Functions – Pass by value – Pass by reference – Recursion – Pointers - Definition – Initialization –


Pointers arithmetic. Structures and unions - definition – Structure within a structure - Union -
Programs using structures and Unions – Storage classes, Pre-processor directives.

S.No Functions
1 Functions
Introduction
Types of Function Implementation
Passing Arguments(Parameters) To Function
Call by Value
Call by Reference
Recursive Functions
Example Programs using functions
2 Pointers

ww Introduction --Definition --Declaration


Pointer Arithmetic
Pointers and arrays

w.E
Pointers and Strings
Pointers and Functions
3 Structures
Intro
asy
Declaration—Initialization --Accessing
Programs using structures
En
Structure within Structure[Nested Structure]
Arrays and Structures
Structure and functions gin
4 Union
Pointers and structure
eer
5
6
Union using Structure
Storage classes ing
7 Pre-processor directives.

.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

FUNCTION
A function is self contained program segment that carries out some specific,well defined task.
Need For Functions:
Many programs require a set of instructions to be executed repeatedly from several places in a
program, then the repeated code can be placed within a single function, which can be accessed
whenever it is required.

Dividing the program into separate well-defined functions facilitates each function to be written
and tested separately.
Understanding, coding, and testing multiple separate functions is easier than doing the same for one
big function main function.
 A big program is broken into comparatively smaller functions.

Advantages of Functions
-Improves readability of code.
-Divides a complex problem into simpler ones
- Improves reuseability of code.

ww
-Debugging errors is easier.
-modifying a program is easier.

Terms
w.E
A function f that uses another function g is known as the calling function, and

asy
g is known as the called function.
The inputs that a function takes are known as arguments.

En
When a called function returns some result back to the calling function, it is
said to return
that result.
gin
The calling function may or may not function,which can theot pass
parameters to the called function.
eer
Function Declaration
Function Definition ing
Function Call
Function Definition .ne
When a function is defined, space is allocated for that function in the memory. A function
definition comprises of two parts:
 Function header
t
 Function body
The syntax of a function definition can be given as:

return_data_type function_name(data_type variable1, data_type variable2,..)


{
statements
return(variable);
}

void sum(int a,int b) int sum(int a,int b) Note that the number of
{ { arguments and the order of
Int c; Int c; arguments in the function
c=a+b; c=a+b; header must be
return(c); return(c); the same as that given in the
} } function declaration
statement.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

Function Call
The function call statement invokes the function. When a function is invoked, the compiler
jumps to the called function to execute the statements that are a part of that function. Once
the called function is executed, the program control passes back to the calling function. A
function call statement has the following

Syntax-1:
function_name(variable1, variable2, ...);

function_name(argument1, argument2, ...);

If the return type of the function is not void then the following syntax can be used.
Syntax-2

ww
variable_name = function_name(variable1, variable2, ...);

variable_name = function_name(parameter1, parameter2, ...);

w.E
The following points are to be noted while calling a function:

asy
Function name and the number and the type of arguments in the function call must be same
as that given in the function declaration and the function header of the function definition.

En
Names (and not the types) of variables in function declaration, function call, and header of
function definition may vary.

Function Declaration gin


eer
It is also called as function prototype. A function prototype consists of 4 parts
(1) Return type
(2) function name
(3) parameter list
ing
.ne
(4) terminating (;) semicolin
data_type function_name(data_type1 variable1, ...,data_type n variable n);

A function prototype tells the compiler that the function may later be used in the
program. The function prototype is not needed if function is placed before
t
main function code.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

Example program
#include <stdio.h>
void sum(int a ,int b); //FUNCTION DECLARATION
int main()
{ int a,b; o/p
scanf(“%d%d”,&a,&b); //get input values for a and b 2
sum(a,b); //FUNCTION CALL 3
} c=5
void sum(int x,int y) // FUNCTION DEFINITION
{
int c;
c=x+y;
printf(“c=%d”,c);
}
void data type indicates that the function is returning nothing .(i.e) if the function is not returning
anything then its datatype is as specified as void.
Example program without function prototype(function declaration)

ww
#include <stdio.h>
void sum(int x,int y) // FUNCTION DEFINITION
{ int c;
o/p
2

}
c=x+y;
w.E
printf(“c=%d”,c);
3
c=5
int main()
{ int a,b;
scanf(“%d%d”,&a,&b);
asy
//get input values for a and b

}
sum(a,b); //FUNCTION CALL
En
gin
Eg-Write a program to find whether a number is even or odd using functions.
#include <stdio.h>
int evenodd(int); //FUNCTION DECLARATION
int main() eer
{
int num, flag;
printf("\n Enter the number : "); ing
scanf("%d", &num);
flag = evenodd(num); //FUNCTION CALL
Output
Enter the number : 78 .ne
if (flag == 1)
printf("\n %d is EVEN", num);
else
printf("\n %d is ODD", num);
78 is EVEN
t
return 0;
}
int evenodd(int a) // FUNCTION DEFINITION
{
if(a%2 == 0)
return 1;
else
retun 0;
TYPES OF FUNCTION IMPLEMENTATION
}

Not passing Not passing arguments passing arguments & passing arguments &
arguments & not & returning some value not returning returning some value
returning anything anything

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


CASE-1 NOT PASSING ARGUMENTS & NOT RETURNING SOME VALUE
#include <stdio.h>
int sum( ); //FUNCTION DECLARATION
int main( )
{ o/p
sum( ); //FUNCTION CALL 2
} 3
int sum( ) // FUNCTION DEFINITION c=5
{
int a,b,c;
scanf(“%d%d”,&a,&b); // get input values for a and b
c=x+y;
printf(“c=%d”,c);
}
CASE-2 NOT PASSING ARGUMENTS & RETURNING SOME VALUE
#include <stdio.h>
int sum( ); //FUNCTION DECLARATION o/p
int main( ) 2

ww
{ sum( ); //FUNCTION CALL
printf(“c=%d”,c);
3
c=5

w.E
}
int sum( ) // FUNCTION DEFINITION
{

asy
int a,b,c;
scanf(“%d%d”,&a,&b); // get input values for a and b
c=x+y;
return c;
}
En
#include <stdio.h>
int sum( int a,int b); //FUNCTION DECLARATIONgin
CASE-3 PASSING ARGUMENTS & NOT RETURNING ANYTHING
o/p
int main( )
{ int a,b; eer
2
3
c=5
scanf(“%d%d”,&a,&b); // get input values for a and b

}
sum(int a,int b ); //FUNCTION CALL
ing
int sum( int x,int y) // FUNCTION DEFINITION
{ .ne
}
int c;
c=x+y;
printf(“c=%d”,c);
t
CASE-4 NOT PASSING ARGUMENTS & RETURNING SOME VALUE
#include <stdio.h>
int sum( int a,int b); //FUNCTION DECLARATION o/p
int main( ) 2
{ int a,b,c; 3
scanf(“%d%d”,&a,&b); // get input values for a and b c=5
c=sum(int a,int b ); //FUNCTION CALL
printf(“c=%d”,c);
return 0;
}
int sum( int x,int y) // FUNCTION DEFINITION
{ int result
result=x+y;
return result; }

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

PASSING ARGUMENTS(PARAMETERS) TO FUNCTION

In programming function argument is commonly referred as actual parameter and function


parameter is referred as formal parameter.

ww
w.E
There are two ways by which parameters can be passed to a function
1. Call by Value
2. Call by Reference
asy
En
Call by value
gin
eer
In Call by value, during function call actual parameter value is copied and
passed to formal parameter. Changes made to the formal parameters does not
affect the actual parameter.
ing
.ne
Eg Program - C program to swap two numbers using call by value
#include<stdio.h>
int main()
{
int n1, n2;
printf("Enter two numbers: ");
scanf("%d%d", &n1, &n2);
t
printf("In Main values before swapping: %d %d\n\n", n1, n2);
swap(n1, n2);
printf("In Main values after swapping: %d %d", n1, n2);
return 0;
}
void swap(int num1, int num2)
{
int temp;
printf("In Function values before swapping: %d %d\n", num1, num2);
temp = num1;
num1 = num2;
num2 = temp;
printf("In Function values after swapping: %d %d\n\n", num1, num2);
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


Output -

Enter two numbers: 10 20


In Main values before swapping: 10 20
In Function values before swapping: 10 20
In Function values after swapping: 20 10
In Main values after swapping: 10 20

NOTE : In the above program swap() function does not alter actual parameter value. Before
passing the value of n1 and n2 to the swap() function, the C runtime copies the value of
actual parameter n1 and n2 to a temporary variable and passes copy of actual parameter.
Therefore inside the swap() function values has been swapped, however original value of n1
and n2 in main() function remains unchanged.

Call by reference

ww
In Call by reference we pass memory location (reference) of actual parameter to
formal parameter. It uses pointers to pass reference of an actual parameter to

w.E
formal parameter. Changes made to the formal parameter immediately reflects
to actual parameter.

asy
Eg Program - C program to swap two numbers using call by reference

#include <stdio.h>
int main()
En
{ int n1, n2;
printf("Enter two numbers: ");
gin
scanf("%d%d", &n1, &n2);

eer
printf("In Main values before swapping: %d %d\n\n", n1, n2);
swap(&n1, &n2);
printf("In Main values after swapping: %d %d", n1, n2);
return 0; ing
}
void swap(int * num1, int * num2) .ne
{
int temp;
printf("In Function values before swapping: %d %d\n", *num1, *num2);
temp = *num1;
t
*num1 = *num2;
*num2 = temp;
printf("In Function values after swapping: %d %d\n\n", *num1, *num2);
}
Output :-
Enter two numbers: 10 20
In Main values before swapping: 10 20
In Function values before swapping: 10 20
In Function values after swapping: 20 10
In Main values after swapping: 20 10
In above example instead of passing a copy of n1 and n2, to swap() function. Operations
performed on formal parameter is reflected to actual parameter (original value). Hence, actual
swapping is performed inside swap() as well as main() function.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


WRITE THESE SWAP PROGRAM(S) FOR YOUR EXAMS
Call by value
#include<stdio.h>
Void swap(int x,int y);
int main( ) Before swapping x and y
{ 10 20
int a = 10, b = 20 ; After swapping x and y
swap (a,b) ; // calling by value 20 10
printf ( "\n Before swapping x and y) ;
printf ( "\na = %d b = %d", a, b ) ;
return 0;
}
void swap( int x, int y )
{
int t ;
t=x;

wwx=y;
y=t;
printf ( "\n After swapping x and y) ;

} w.E
printf( "\nx = %d y = %d", *x,*y);

Call by reference
#include<stdio.h>
Void swap(int *x,int *y); asy Before swapping x and y
10 20
int main( )
{ En After swapping x and y
20 10
int a = 10, b = 20 ;
swap ( &a, &b ) ; // calling by reference gin
printf ( "\n Before swapping x and y) ;
printf ( "\na = %d b = %d", a, b ) ;
eer
ing
return 0;
}
void swap( int *x, int *y )
{
int t ; .ne
t = *x ;
*x = *y ;
*y = t ;
t
printf ( "\n After swapping x and y) ;
printf( "\nx = %d y = %d", *x,*y);
}
Call by value Call by reference
When a function is called the actual values are When a function is called the address of
passed values(arguments) are passed
The parameters passed are normal variables The parameters passed are pointer variables
In call by value, actual arguments cannot be Modification to actual arguments is possible
modified. within from called function.
Actual arguments remain preserved and no Actual arguments will not be preserved.
chance of modification accidentally.
Calling Parameters: swap(a,b) Calling Parameters: swap(&a,&b)
Receiving parameters: void swap( int x, int y ) Receiving parameters: void swap( int *x, int *y )

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


PASSING ARRAYS TO A FUNCTION

Passing Array Element to a Function


#include <stdio.h> output
void display(int a);
int main() 41
{
int age[] = { 21, 31, 41 };
display(age[2]); //Passing array element age[2] only.
return 0;
}
void display(int age)
{
printf("%d", age);
}
Passing Entire Array(1-Dimentional array) Element to a Function
#include <stdio.h>
float average(float age[]);

ww
int main()
{

w.E
float avg, age[] = { 30.5,40.5,60.5,80.5};
avg = average(age);
printf("Average age=%.2f", avg);

asy
return 0;
} Output
float average(float age[])
{
int i;
En 53.000000

float avg, sum = 0.0;


for (i = 0; i < 4; ++i)
{ gin
sum += age[i];
} avg = (sum / 4); eer
return avg;
}
ing
Passing Entire Array(2-Dimentional array) Element to a Function
#include <stdio.h>
void displaynumbers(int num[2][2]); Output .ne
int main( )
{
Int num[2][2],i,j;
Printf(“enter numbers”);
Enter numbers
10
20
30
t
40
for(i=0;i<2;i++) Display numbers
for(i=0;i<2;i++) 10
scanf(“%d”,&num[i][j]); 20
displaynumbers(num) // calling function 30
40
return 0;
}
void displaynumbers(int num[2][2]) / / function declaration
{
int i,j;
Printf(“display numbers”);
for(i=0;i<2;i++)
for(i=0;i<2;i++)
printf(“%d”,num[i][j]);
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


RECURSION FUNCTION

A function that calls itself is known as a recursive function. And, this technique is known as
recursion.

Advantage of Recursion

 Function calling related information will be maintained by recursion.


 Stack evaluation will be take place by using recursion.
 In fix prefix, post-fix notation will be evaluated by using recursion.

Disadvantage of Recursion

 It is a very slow process due to stack overlapping.


 Recursive programs can create stack overflow.
 Recursive functions can create as loops.

ww
w.E
asy
En
gin
eer
ing
.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


Example: Sum of Natural Numbers Using Recursion
#include <stdio.h>
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum=%d", result);
}
int sum(int num)
{
if (num!=0)
return num + sum(num-1); // sum() function calls itself
else
return num;
}
Output

ww
Enter a positive integer:3
6

w.E
asy
En
gin
eer
ing
.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

FACTORIAL OF A NUMBER USING RECURSIVE FUNCTION


#include <stdio.h>
int factorial( int ) ;
void main( )
{
int fact, n ; Enter any positive integer: 3
printf(“Enter any positive integer: ”) ; Factorial of 3 is 6
scanf(“%d”, &n) ;
fact = factorial( n ) ;
printf(“Factorial of %d is %d”, n, fact) ;
}
int factorial( int n )
{
int temp ;
if( n == o)
return 1 ;
else
temp = n * factorial( n-1 ) ; // recursive function call
return temp ;
}

ww
w.E
asy
En
gin
eer
3*2 =6
ing
.ne
t
2*1=2

1 * 1=1

Returns 1 as n value is 0

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


TOWER OF HANOI OF A NUMBER USING RECURSIVE FUNCTION
#include <stdio.h>
void hanoi(int n, char from, char to, char temp)
{
if (n == 1)
{
printf("\n Move Disk 1 from Peg %c to %c", from, to);
return;
}
hanoi(n-1, from, temp, to);
printf("\n Move disk %d from rod %c to rod %c", n, fr, tr);
hanoi(n-1, temp, to, from);
}
int main()
{
Printf(“ Towers of Honoi”);

wwint n;
printf(“\n Enter number of Disks”);
scanf(” %d ”,&n); // n implies the number of discs

w.E
hanoifun(n, 'A', 'C', 'B'); // A, B and C are the name of Peg
return 0;

asy
}
To Transfer from disks from peg A to C taking help of B

En
gin
eer
ing
.ne
t

Output
 Move Disk 1 from Peg 1 to Peg 3.
 Move Disk 2 from Peg 1 to Peg 2.
 Move Disk 1 from Peg 3 to Peg 2.
 Move Disk 3 from Peg 1 to Peg 3.
 Move Disk 1 from Peg 2 to Peg 1.
 Move Disk 2 from Peg 2 to Peg 3.
 Move Disk 1 from Peg 1 to Peg 3.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

Example: GCD of Two Numbers using Recursion


#include <stdio.h>
int hcf(int n1, int n2);
int main()
{
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);

printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1,n2));


return 0;
}

int hcf(int n1, int n2)


{
Output
if (n2 != 0)
return hcf(n2, n1%n2); Enter two positive integers: 27 18
else G.C.D of 27 and 8 is 9.

ww
}
return n1;

w.E
asy
En
gin
eer
ing
.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

Example: Fibonacci Series using Recursion


#include <stdio.h>
int fibonacci(int i)
{
if(i == 0)
{
return 0; Output
}
if(i == 1)
0
{
1
return 1;
1
}
2
return fibonacci(i-1) + fibonacci(i-2);
3
}
5
8

ww
int main()
{
int i,f;
13
21
34
{
w.E
for (i = 0; i < 10; i++)

f= fibonacci(i);

}
return 0; asy
printf("%d \n ",f);

En
gin
eer
ing
.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

Pointers in C Programming
A pointer is variable which stores address of another variable.

Pointers can only store addresses of other variable.

int x=10, y=20;


printf(“%u %u”, &x, &y);

ww
Note :Here %u is a format specifier. It stands for unsigned, so it will only display positive values.

w.E
You will get output of the above program like below.
605893 605897

&-address of operator.
asy
En
& is the “address of” operator. It is used to tell the C compiler to refer to the address of variables.
Address of any variable can’t be negative. This is the reason %u format specifier is used to print the
address of variables on the screen.

value at address (*) Operator


gin
eer
ing
This is the second operator used for pointers. It is used to access the value present at some
address. And it is used to declare a pointer.

Declaration and initialization of pointers .ne


int x=10;
int *ptr; // Declaration of Pointer variable
ptr=&x; // Storing address of x variable in y pointer variable
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


Example program-1

#include<stdio.h>
void main()
{ 6 12
65524 65522
int a=6,b=12; 65524 65522
int *x,*y; 6 12
x=&a; 65524 65522
y=&b; 6 12
printf("%d t %d n",a,b);
printf("%u t %u n",&a,&b);
printf("%u t %u n",x,y);
printf("%d t %d n",*x,*y);
printf("%d t %d",(&a),(&b));
printf("%d t %d",*(&a),*(&b));
}

ww
#include <stdio.h>
int main ()
{
int var = 20;
w.E /* actual variable declaration */
int *ip;
ip = &var; asy /* pointer variable declaration */
/* store address of var in pointer variable*/

En
printf("Address of var variable: %x\n", &var );
/*address stored in pointer variable*/
printf("Address stored in ip variable: %x\n", ip );

gin
/*access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );

}
return 0;

eer
A pointer is a variable whose value is the memory address of another
variable ing
syntax
.ne
type *var-name;

Here, type is the pointer's base type; it must be a valid C data type and var-
t
name is the name of the pointer variable.

int *ip; /* pointer to an integer */


double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

NULL Pointers
A pointer that is assigned NULL is called a null pointer.

The NULL pointer is a constant with a value of zero.

It is always a good practice to assign a NULL value to a pointer variable in


case you do not have an exact address to be assigned.

#include <stdio.h>
int main ()
{
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr);
return 0;
}

output

ww
The value of ptr is 0

w.E
Incrementing a Pointer(32-bit )
#include <stdio.h>
const int MAX = 3; asy
int main () {
int var[] = {10, 100, 200};
En
gin
int i, *ptr;
/* let us have array address in pointer */
ptr = var;
for ( i = 0; i < MAX; i++) {
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr ); eer
ptr++;
/* move to the next location */
ing
}

return 0; .ne
}

output
t
Address of var[0] = bf882b30
Value of var[0] = 10
Address of var[1] = bf882b34
Value of var[1] = 100
Address of var[2] = bf882b38
Value of var[2] = 200

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

Decrementing a Pointer(32-bit machine)


decreases its value by the number of bytes of its data type.

#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--) {
printf("Address of var[%d] = %x\n", i-1, ptr );
printf("Value of var[%d] = %d\n", i-1, *ptr );
/* move to the previous location */
ptr--;

ww }

return 0;
}

output
w.E
Address of var[2]
Value of var[2] = asy
= bfedbcd8
200
Address of var[1]
Value of var[1] =
= bfedbcd4
100
En
Address of var[0]
Value of var[0] =
= bfedbcd0
10
gin
Program for pointer arithmetic(32-bit machine) eer
#include <stdio.h>
ing
.ne
int main()
{
int m = 5, n = 10, val = 0;
int *p1;
int *p2;
int *p3;
t
p1 = &m; //printing the address of m
p2 = &n; //printing the address of n

printf("p1 = %d\n", p1);


printf("p2 = %d\n", p2);

printf(" *p1 = %d\n", *p1);


printf(" *p2 = %d\n", *p2);

val = *p1+*p2;
printf("*p1+*p2 = %d\n", val);//point 1

p3 = p1-p2;
printf("p1 - p2 = %d\n", p3); //point 2

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

p1++;
printf("p1++ = %d\n", p1); //point 3

p2--;
printf("p2-- = %d\n", p2); //point 4

return 0;
}

OUTPUT

p1 = 2680016
p2 = 2680012

*p1=5;
*p2=10;

ww
*p1+*p2 = 15

p1-p2 = 1
p1++ = 2680020
p2-- = 2680008
w.E
asy
En
gin
eer
ing
.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


STRUCTURES

Structure is a user-defined data type that can store related information (of different
data types) together. The major difference between a structure and an array is that an array can
store only information of same data type. A structure is therefore a collection of variables under a
single name. The variables within a structure are of different data types.
 A structure is a collection of variables under a single name. These variables can be of
different types, Therefore, a structure is a convenient way of grouping together
several pieces of related information.
 Complex hierarchies can be created by nesting structures.
 Declaration/Initializing/Accessing
 Nesting of Structures
 Arrays of Structures
 Structures and Pointers
 Structures and Functions
8.2.1 DECLARING STRUCTURES AND STRUCTURE VARIABLES

ww
A structure is declared by using the keyword struct followed by an optional structure tag
followed by the body of the structure. The variables or members of the structure are

w.E
declared within the body.

The general format of declaring a simple structure is given as follows.

asy
En
gin
eer
ing
There are three different ways to declare and/or define a structure. These are .ne
 Variable structure
 Tagged structure
 Type-defined structure
t
1. A variable structure may be defined as follows.
struct
{
member_list
}variable_identifier;

struct
{
where. ... a,student1-are called as
int r_no;
char name[20]; structure variables
char course[20];
float fees;
} student1;

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


...

2.A tagged structure has been described earlier. It has the following format:

struct tag_name
{
member_list
}variable_identifier;

struct student
{
int r_no;
char name[20];
char course[20];

ww
float fees;
} stud1, stud2; Memory allocation

w.E
asy
En
3.Type-defined structure declaration is as follows

 gin
typedef keyword enables the programmer to create a new data type name by using an
existing data type.
eer
typedef existing_data_type new_data_type;

typedef struct newdatatype ing


{
member_list;
typedef struct student
{
int r_no; .ne
} newdatatype variable_identifier;
char name[20];
char course[20];
float fees;
t
} student stud1;

When we precede a struct name with the typedef keyword, then the struct becomes a new
type. student becomes a new data type. To declare a variable of structure student, you may
write student stud1;

Note that we have not written struct student stud1.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI


EASYENGINEERING.NET

INITIALIZATION OF STRUCTURES
A structure can be initialized in the same way as other data types are initialized. Initializing
a structure means assigning some constants to the members of the structure.

struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
.......................
}struct_var = {constant1, constant2,
constant3,...};

Example-1

{
ww
struct student

int r_no;
char name[20];
w.E
char course[20];
float fees;

ACCESSING
The members are accessed asy
}stud1 = {01, "Rahul", "BCA", 45000};

by relating THE
them MEMBERS OFvariable
to the structure A STRUCTURE
with a dot operator.

En
The general form of the statement for accessing a member of a structure is as follows.
< structure_variable >.< member_name > ;

gin
stud1.r_no
stud1.name
Stud2.r_no
Stud2.name eer
stud1.course Stud2.course

ing
Each member of a structure can be used just like a normal variable, but its name will be a bit longer.
A structure member variable is generally accessed using a '.' (dot) operator.

stud1.r_no = 01; .ne


stud1.name = "Rahul";
stud1.course = "BCA";
stud1.fees = 45000;
t
To input values for data members of the structure variable stud1, we may write

scanf("%d", &stud1.r_no);
scanf("%s", stud1.name);

Similarly, to print the values of structure variable stud1, we may write

printf("%s", stud1.course);
printf("%f", stud1.fees);

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


Example-2 both initializing and accessing member data
struct {
float p, q,
int r;
} k = {k .p = 3.0, k.q = 7.9, k.r = 5};
Write a program using structures to read and display the information about a student

#include <stdio.h>
struct student
{
int roll_no;
char name[80];
float fees;
char DOB[80];
};

{
ww
int main()

struct student stud1;

w.E
printf("\n Enter the roll number : ");
scanf("%d", &stud1.roll_no);

asy
printf("\n Enter the name : ");
scanf("%s", stud1.name);
En
printf("\n Enter the fees : ");
scanf("%f", &stud1.fees); gin
printf("\n Enter the DOB : ");
eer
scanf("%s", stud1.DOB);

printf("\n ********STUDENT'S DETAILS *******"); ing


printf("\n ROLL No. = %d", stud1.roll_no);
printf("\n NAME = %s", stud1.name); .ne
printf("\n FEES = %f", stud1.fees);
printf("\n DOB = %s", stud1.DOB);
getch();
t
return 0;
}

Output
Enter the roll number : 01
Enter the name : Rahul
Enter the fees : 45000
Enter the DOB : 25–09–1991
********STUDENT’S DETAILS *******
ROLL No. = 01
NAME = Rahul
FEES = 45000.00
DOB = 25–09–1991

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

C program to read and print employee's record using structure

#include <stdio.h>

struct employee
{
char name[30];
int empId;
float salary;
};

int main()
{
struct employee emp; // declare structure variable
printf("\nEnter details :\n");

wwprintf(“\n ************”);
printf("Name ?:");
scanf(“%s”,emp.name);

w.E
printf("ID ?:");
scanf("%d",&emp.empId);

asy
printf("Salary ?:");
scanf("%f",&emp.salary);

/*print employee details*/


En
printf("\n Employee detail is:");
printf(“\n ************”); gin
printf("Name: %s" ,emp.name);
printf("Id: %d" ,emp.empId); eer
printf("Salary: %f\n",emp.salary);
return 0;
ing
.ne
}

Output

Enter details :
t
**********
Name ?:Mike
ID ?:1120
Salary ?:76543

Employee detail is:


***************
Name: Mike
ID: 1120
Salary: 76543.000000

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

Write a program to copy and compare structures for employee details

// A structure can be assigned to another structure of the same type. Here is an


example of assigning one structure to another.

#include <stdio.h>
struct employee
{
char grade;
int basic;
float allowance;
};

ww
int main()
{

w.E
struct employee ramesh={‘B’, 6500, 812.5};
member of employee */
/* creating & initializing

struct employee vivek;


employee */ asy /* creating another member of

En
vivek = ramesh;
ramesh to vivek */ gin /* copy respective members of

printf(“\n vivek’s grade is %c, vivek.grade); eer


printf(“\n vivek’s basic is Rs %d, vivek. Basic);
printf(“\n vivek’s allowance is Rs %f”, vivek.allowance); ing
return 0;
} .ne
Output:
t
vivek’s grade is B
vivek’s basic is Rs 6500
vivek’s allowance is Rs
812.500000

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

Using Typedef :- A program that prints the weight of various sizes of fruits.

#include <stdio.h>
typedef struct fruits
{
float big;
float medium;
float small;
}fruits weight;

int main()
{
weight apples={200.75,145.5,100.25};
weight pears={150.50,125,50};

ww
weight mangoes={1000, 567.25, 360.25};

w.E
printf(“\n\n apples: big size %f kg, medium size %f kg, small size %f kg”, apples.big,
apples.medium, apples.small);

asy
printf(“\n\n pears: big size %f kg, medium size %f kg,small size %f kg”, pears.big,
pears.medium, pears.small);

En
printf(“\n\n mangoes: big size %f kg, medium size %f kg,small size %f kg”, mangoes.big,
mangoes.medium, mangoes.small);
return 0;
} gin
eer
Output: ing
apples: big 200.75kg, medium 145.50kg, small 100.25kg
pears: big 150.50kg, medium 125.00kg, small 50.00kg .ne
mangoes: big 1000kg, medium 567.25kg, small 360.25kg
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

Nesting of Structures

A structure can be placed within another structure. In other words, structures can contain other structures
as members. A structure within a structure means nesting of structures.

In such cases, the dot operator in conjunction with the structure variables are used to access the members
of the innermost as well as the outermost structures.

typedef struct name


{
char first_name[20];
char mid_name[20]; assign values to the structure fields, we will write
char last_name[20]; student stud1;
}NAME; stud1.r_no = 01;
stud1.name.first_name = "Janak";
typedef struct dob stud1.name.mid_name = "Raj";
{ stud1.name.last_name = "Thareja";

ww
int dd;
int mm;
int yy;
stud1.course = "BCA";
stud1.DOB.dd = 15;

}DATE;
w.E
typedef struct student
stud1.DOB.mm = 09;
stud1.DOB.yy = 1990;
stud1.fees = 45000;

{
int r_no; asy
NAME name;
char course[20];
En
DATE DOB;
float fees;
} STU; gin
eer
ing
.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


Write a program to read and display the information of a student using a nested structure.
#include <stdio.h>
struct DOB
{
int day;
int month;
int year;
};

struct student
{
int roll_no;
char name[100];
float fees;
struct DOB date;
};

ww
int main()
{

w.E
struct student stud1;

printf("\n Enter the roll number : ");


scanf("%d", &stud1.roll_no);
asy
printf("\n Enter the name : ");
scanf("%s", stud1.name); En
printf("\n Enter the fees : "); gin
scanf("%f", &stud1.fees);
eer
printf("\n Enter the DOB : ");
scanf("%d %d %d", &stud1.date.day, &stud1.date.month, &stud1.date.year);
ing
printf("\n ********STUDENT'S DETAILS *******");
printf("\n ROLL No. = %d", stud1.roll_no); .ne
printf("\n NAME = %s", stud1.name);
printf("\n FEES = %f", stud1.fees);
printf("\n DOB = %d – %d – %d", stud1.date.day, stud1.date.month, stud1.date.year);
t
getch();
return 0;
}
Output
Enter the roll number : 01
Enter the name : Rahul
Enter the fees : 45000
Enter the DOB : 25 09 1991
********STUDENT’S DETAILS *******
ROLL No. = 01
NAME = Rahul
FEES = 45000.00
DOB = 25 – 09 – 1991

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


Write A program to demonstrate nesting of structures and accessing structure
members.
#include <stdio.h>
struct outer /* declaration of outer structure */
{
int out1; /* member of outer structure */
float out2; /* member of outer structure */

struct inner /* declaration of inner structure */


{
int in1; /* member of inner structure */
float in2; /* member of inner structure */
}invar; /* structure_variable of inner structure*/
};

int main()
{
ww
struct outer outvar;
outvar.out1= 2;
/* declaring structure_variable of outer */
/* assigning values to members */

w.E
outvar.out2= 10.57;
outvar.invar.in1= 2* outvar.out1; /* assigning values to members */

asy
outvar.invar.in2= outvar.out2 + 3.65;

printf(“ out1=%d, out2=%f, in1=%d, in2=%f”,outvar.out1, outvar.out2,outvar.invar.in1,


outvar.invar.in2);
return 0; En
}
gin
Output:
out1=2, out2= 10.57, in1=4, in2= 14.22 eer
ing
.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

Write a program to read, display, add, and subtract two complex numbers.

#include <stdio.h>
#include <conio.h> Output
int main() ******** MAIN MENU *********
{ 1. Read the complex numbers
typedef struct complex 2. Display the complex numbers
{ 3. Add the complex numbers
int real; 4. Subtract the complex numbers
int imag; 5. EXIT
}COMPLEX;
COMPLEX c1, c2, sum_c, sub_c; Enter your option : 1
Enter the real and imaginary parts of the first complex
int option; number : 4 5
Enter the real and imaginary parts of the second complex
do number : 2 3
{ Enter your option : 2

ww
printf("\n ******** MAIN MENU *********"); The first complex numbers is : 4+5i
printf("\n 1. Read the complex numbers"); The second complex numbers is : 2+3i

w.E
printf("\n 2. Display the complex numbers"); Enter your option : 3
printf("\n 3. Add the complex numbers"); The sum of two complex numbers is : 6+8i
printf("\n 4. Subtract the complex numbers"); Enter your option : 4
The difference between two complex numbers is : 2+2i

asy
printf("\n 5. EXIT");
printf("\n Enter your option : ");
Enter your option : 5
scanf("%d", &option);
En
switch(option)
{
case 1: gin
eer
printf("\n Enter the real and imaginary parts of the first complex number : ");
scanf("%d %d", &c1.real, &c1.imag);

ing
printf("\n Enter the real and imaginary parts of the second complex number : ");
scanf("%d %d", &c2.real, &c2.imag);
break;
case 2:
printf("\n The first complex number is : %d+%di", c1.real,c1.imag); .ne
printf("\n The second complex number is : %d+%di", c2.real,c2.imag);
break;
case 3:
sum_c.real = c1.real + c2.real;
t
sum_c.imag = c1.imag + c2.imag;
printf("\n The sum of two complex numbers is : %d+%di",sum_c.real, sum_c.imag);
break;
case 4:
sub_c.real = c1.real – c2.real;
sub_c.imag = c1.imag – c2.imag;
printf("\n The difference between two complex numbers
is :%d+%di", sub_c.real, sub_c.imag);
break;
}
}while(option != 5);
return 0;
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI


EASYENGINEERING.NET

ARRAYS
Arrays of structures means that the structure OF STRUCTURES
variable would be an array of objects, each of which contains
the member elements declared within the structure construct.

Why would need an array of structures


1. In a class, we do not have just one student. But there may be at least 60 students. So, the same
definition of the structure can be used for all the 30 students. This would be possible when we make an
array of structures.
2. Another example where an array of structures is desirable is in case of an organization. An
organization has a number of employees. So, defining a separate structure for every employee is
not a viable solution. So, here we can have a common structure definition for all the employees.

struct student
Syntax {
struct struct_name int r_no;
{ char name[20];
data_type member_name1; char course[20];

ww
data_type member_name2;
data_type member_name3;
......................
float fees;
};
};
w.E
struct struct_name
struct_var[index];
A student array can be declared by writing,
struct student stud[30];

asy
Now, to assign values to the ith student of the class, we can write as

stud[i].r_no = 09;
En
stud[i].name =
stud[i].course
stud[i].fees =
"RASHI";
= "MCA";
60000; gin
In order to initialize the array of structure variables eer
struct student stud[3][4] = {{01, "Aman", "BCA", 45000},{02, ing
"Aryan", "BCA", 60000}, {03,"John", "BCA", 45000}};
.ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

ww
w.E
Write a program to print the tickets of the boarders of a boat using array
of structures with initialization in the program.
#include <stdio.h>
asy
struct boat
{ En
// declaration of structure //

char name[20];
int seatnum; gin
float fare;
eer
};
ing
int main()
{ .ne
int i;
struct boat ticket[4][3]={{“Vikram”,1,15.50},{“Krishna”,2,15.50},
{“Ramu”,3,25.50},{“Gouri”,4, 25.50 } };
t
printf(“\n passenger Ticket num. Fare”);
for(i=0;i<=3;i++)
printf(“\n %s %d %f ”, ticket[i].name,ticket[i].seatnum,ticket[i].fare);
return 0;
}
Output:
Passenger Ticket num. Fare
Vikram 1 15.500000
Krishna 2 15.500000
Ramu 3 25.500000
Gouri 4 25.500000

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

C program to generate salary slip of employees using structures

#include<stdio.h>
struct emp
{
int empno ;
char name[10] ;
int bpay, allow, ded, npay ;
} e[10] ;

void main()
{
int i, n ;

ww printf("Enter the number of employees : ") ;


scanf("%d", &n) ;

{
w.E
for(i = 0 ; i < n ; i++)

asy
printf("\nEnter the employee number : ") ;
scanf("%d", &e[i].empno) ;
En
printf("\nEnter the name : ") ;
scanf("%s", e[i].name) ; gin
eer
printf("\nEnter the basic pay, allowances & deductions : ") ;
scanf("%d %d %d", &e[i].bpay, &e[i].allow, &e[i].ded) ;
ing
}
e[i].npay = e[i].bpay + e[i].allow - e[i].ded ;
.ne
printf("\nEmp. No.\t Name \t Salary \n") ;
printf("\n *************************") ;
for(i = 0 ; i < n ; i++)
t
{
printf("%d \t %s \t %f \t ", e[i].empno,e[i].name, e[i].npay) ;
} Enter the employee number 2
return 0;
Enter the employee number: 1001
} Enter the employee number: Rina
Enter the basic pay, allowances & deductions: 75000 10000 2000

Enter the employee number: 2001


Enter the employee number: Bina
Enter the basic pay, allowances & deductions: 80000 10000 3000

Emp.No. Name NetSalary


****************************
1001 Rina 83000
2001 Bina 87000

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


Write a program to read and display the information of all the students in a class. Then
edit the details of the ith student and redisplay the entire information.

#include <stdio.h>
#include <string.h>
struct student
{
int roll_no;
char name[80];
int fees;
char DOB[80];
};
int main()
{
struct student stud[50];
int n, i, num, new_rollno;
int new_fees;
char new_DOB[80], new_name[80];

ww
clrscr(); // clear screen
printf("\n Enter the number of students : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{ w.E
asy
printf("\n Enter the roll number : ");
scanf("%d", &stud[i].roll_no);

printf("\n Enter the name : ");


gets(stud[i].name);
En
printf("\n Enter the fees : ");
scanf("%d",&stud[i].fees); gin
printf("\n Enter the DOB : "); eer
gets(stud[i].DOB);
}
ing
for(i=0;i<n;i++)
{ .ne
printf("\n ********DETAILS OF STUDENT %d*******", i+1);
printf("\n ROLL No. = %d", stud[i].roll_no);
printf("\n NAME = %s", stud[i].name);
printf("\n FEES = %d", stud[i].fees);
t
printf("\n DOB = %s", stud[i].DOB);
}

printf("\n Enter the student number whose record has to be edited : ");
scanf("%d", &num);

printf("\n Enter the new roll number : ");


scanf("%d", &new_rolno);

printf("\n Enter the new name : "):


gets(new_name);

printf("\n Enter the new fees : ");


scanf("%d", &new_fees);

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


printf("\n Enter the new DOB : ");
gets(new_DOB);

stud[num].roll_no = new_rollno;
strcpy(stud[num].name, new_name);
stud[num].fees = new_fees;
strcpy (stud[num].DOB, new_DOB);

for(i=0;i<n;i++)
{
printf("\n ********DETAILS OF STUDENT %d*******", i+1);
printf("\n ROLL No. = %d", stud[i].roll_no);
printf("\n NAME = %s", stud[i].name);
printf("\n FEES = %d", stud[i].fees);
printf("\n DOB = %s", stud[i].DOB);
}
getch();
return 0;
}
ww Output
Enter the number of students : 2
Enter the roll number : 1

w.EEnter the name : kirti


Enter the fees : 5678
Enter the DOB : 9- 9- 99

asy
Enter the roll number : 2
Enter the name : kangana
Enter the fees : 5678
Enter the DOB : 27- 8- 99
En
********DETAILS OF STUDENT 1*******
ROLL No. = 1
NAME = kirti
FEES = 5678 gin
DOB = 9- 9- 99
********DETAILS OF STUDENT 2*******
ROLL No. = 2 eer
NAME = kangana
FEES = 5678
DOB = 27- 8 -99 ing
Enter the student number whose record has to be edited : 2
Enter the new roll number : 2 .ne
Enter the new name : kangana khullar
Enter the new fees : 7000
Enter the new DOB : 27- 8 -92

********DETAILS OF STUDENT 1*******


t
ROLL No. = 1
NAME = kirti
FEES = 5678
DOB = 9 -9 -99
********DETAILS OF STUDENT 2*******
ROLL No. = 2
NAME = kangana khullar
FEES = 7000
DOB = 27- 8 -92

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

STRUCTURES AND FUNCTIONS


Passing the entire structure
Passing structures to functions

Eg:Passing Individual Members Passing the address of structure

#include <stdio.h>
typedef struct
{
int x;
int y;
}POINT;

void display(int, int); // function declaration

{ww
int main()
Output

w.E
POINT p1 = {2, 3};
display(p1.x, p1.y);
return 0;
// function call The coordinates of the point are: 2 3

}
asy
void display(int a, int b) // function definition
{
En
gin
printf(" The coordinates of the point are: %d %d", a, b);
}

Eg:Passing the Entire Structure


eer
#include <stdio.h>
typedef struct
ing
{
int x;
int y; .ne
}POINT;

void display(POINT);
t
int main()
{
POINT p1 = {2, 3};
display(p1);
return 0;
}
void display(POINT p)
{
printf("The coordinates of the point are: %d %d", p.x, p.y);
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET

 Passing Structure by Value

 Passing Structure by Reference

Passing Structure by Value

In this approach, the structure object is passed as function argument to the definition of
function, here object is reperesenting the members of structure with their values.

Program
#include<stdio.h>

struct Employee
{
int Id;

ww char Name[25];
int Age;

};
w.E
long Salary;

asy
void Display(struct Employee);

En
void main()
{

gin
struct Employee Emp = {1,"Kumar",29,45000};

Display(Emp);

} eer
void Display(struct Employee E) ing
{
printf("\n\nEmployee Id : %d",E.Id);
.ne
}
printf("\nEmployee Name : %s",E.Name);
printf("\nEmployee Age : %d",E.Age);
printf("\nEmployee Salary : %ld",E.Salary);
t
Output :

Employee Id : 1
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


Passing Structure by Reference

In this approach, the reference/address structure object is passed as function argument to the
definition of function.

Program

#include<stdio.h>

struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};

ww void Display(struct Employee*);


void main()
{
w.E
struct Employee Emp = {1,"Kumar",29,45000};

Display(&Emp);
asy
}
En
void Display(struct Employee *E)
{ gin
printf("\n\nEmployee Id : %d",E->Id);
printf("\nEmployee Name : %s",E->Name);
eer
}
printf("\nEmployee Age : %d",E->Age);
printf("\nEmployee Salary : %ld",E->Salary);
ing
Output : .ne
Employee Id : 1
Employee Name : Kumar
t
Employee Age : 29
Employee Salary : 45000

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


Passing Structures through Pointers

struct struct_name
{
data_type
member_name1;
data_type
member_name2;
data_type
member_name3;
......................
}*ptr;

or,
struct struct_name
*ptr;

ww
w.E
we can declare a pointer variable by writing

struct student *ptr_stud, stud;

asy
The next thing to do is to assign the address of stud to the pointer using the address operator
(&).
En
ptr_stud = &stud;
gin
eer
To access the members of a structure, we can write

(*ptr_stud).roll_no;

(->)This operator is known as ‘pointing-to’ operator ing


ptr_stud -> roll_no = 01; .ne
t

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


Write a program to initialize the members of a structure by using a pointer to the structure.

#include <stdio.h>

struct student
{
int r_no;
char name[20];
char course[20];
int fees;
};

int main()
{
struct student stud1, *ptr_stud1;

ptr_stud1 = &stud1;

ww
printf("\n Enter the details of the student :");
printf("\n **************************”);

w.E
printf("\n Enter the Roll Number =");
scanf("%d", &ptr_stud1 -> r_no);

printf("\n Enter the Name = );


gets(ptr_stud1 -> name); asy
printf("\n Enter the Course = ");
En
gets(ptr_stud1 -> course);

printf("\n Enter the Fees = "); gin


scanf("%d", &ptr_stud1 -> fees);
eer
printf("\n DETAILS OF THE STUDENT");
printf("\n **************************”);
ing
printf("\n ROLL NUMBER = %d", ptr_stud1 –> r_no);
printf("\n NAME = %s", ptr_stud1 –> name); .ne
printf("\n COURSE = %s", ptr_stud1 –> course);
printf("\n FEES = %d", ptr_stud1 –> fees);
return 0;
}
t
Output
Enter the details of the student:
************************
Enter the Roll Number = 02
Enter the Name = Aditya
Enter the Course = MCA
Enter the Fees = 60000

DETAILS OF THE STUDENT


************************
ROLL NUMBER = 02
NAME = Aditya
COURSE = MCA
FEES = 60000

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


Storage Classes in C++ Programming

Storage class of a variable defines the lifetime and visibility of a variable. Lifetime means
the duration till which the variable remains active and visibility defines in which module of
the program the variable is accessible. They are:

1. Automatic
2. External
3. Static
4. Register

Storage Class Keyword Lifetime Visibility Initial Value


Automatic auto Function Block Local Garbage
External extern Whole Program Global Zero
Static static Whole Program Local Zero

ww
Register register Function Block Local Garbage

w.E
1. Automatic Storage Class

This variable is visible only within the function it is declared and its lifetime is same as the

asy
lifetime of the function as well. This is the default storage class we have been using so far. It
applies to local variables only and the variable is visible only inside the function in which it is

En
declared and it dies as soon as the function execution is over. If not initialized, variables of
class auto contains garbage value.

gin
The value is lost after the execution of function.
Syntax: auto datatype var_name1 [= value];
Example:
int var; // by default, storage class is auto
auto int var; // auto int j=10; eer
Example Program: ing
#include<stdio.h>

void display(); .ne


void main()
{
auto int a=10; //OR int a=10;
printf("\n A1 : %d",a);
t
display();
printf("\n A3 : %d",a);
}
void display()
{
int a=20; //OR auto int a=20;
printf("\n A2 : %d",a);
}

Output :

A1 : 10
A2 : 20
A3 : 10

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


2. External Storage Class

External storage class reference to a global variable declared outside the given program.
extern keyword is used to declare external variables. They are visible throughout the
program and its lifetime is same as the lifetime of the program where it is declared. This
visible to all the functions present in the program.

Syntax : extern datatype var_name1;


Example: extern float a;

The extern keyword is optional, there is no need to write it.

 The scope of external variable is the entire program.

ww

If not initialized external variable is assigned a zero value.
The value is not lost after the execution of function.

w.E
Example Program:

#include<stdio.h>
asy
void display();
extern int a=10;
En //global variable
void main()
{
printf("\nA : %d",a); gin
increment();
display();
printf("\nA : %d",a); eer
}
void increment()
ing
{
a = 20; .ne
}
void display()
{

}
printf("\nA : %d",a);
t
Output :

A : 10
A : 20
A : 20

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


3. Static Storage Class
Static storage class ensures a variable has the visibility mode of a local variable but
lifetime of an external variable. It can be used only within the function where it is declared
but destroyed only after the program execution has finished. The default initial value of static
variable is 0. The value of a static variable persists between function calls
.
Syntax: static datatype var_name1 [= value];
Example: static int x = 101;
static float sum;
During multiple calling static variables retains their previous value.

 We must declare variable as static.


 Static variables can't be accessed outside the function.
 If not initialized static variables have zero as initial value.

Example of static storage class

ww #include<stdio.h>
void display();

w.E void main()


{
display();
Output:

A:1

} asy
display();
display();
A:2
A:3

void display()
{
static int a=1; En
printf("\nA : %d",a);
a++; gin
}

eer
In the above example, we does not use static keyword then the output will be :
Output : A : 1
A : 1
ing
A : 1
4. Register Storage Class
Variables of class 'register' are stored in CPU registers instead of memory which.ne
allows faster access. It has its lifetime and visibility same as automatic variable. The scope of
the variable is local to the function in which it is defined and it dies as soon as the function
execution is over. It contains some garbage value if not initialized. The purpose of creating
register variable is to increase access speed and makes program run faster. As register space
t
is very limited, so only those variables which requires fast access should be made register It
is declared as:
Syntax: register datatype var_name1 [= value];
Example: register int count
register char a;
C program to create automatic, global(extern) variables.
#include<stdio.h>
void main() Output :
{
register int a=10; A : 10
printf("\nA : %d",a);
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


PREPROCESSOR DIRECTIVES
The C Preprocessor is not part of the compiler but it extends the power of C
programming language. . The preprocessor provides the ability for the inclusion of header
files, macro expansions, conditional compilation, and line control.The preprocessor’s
functionality comes before compilation of source code and it instruct the compiler to do
required pre-processing before actual compilation. Working procedure of C program is
shown in Fig. 2.8. In general, preprocessor directives
 begin with a # symbol
 do not end with semicolon
 are processed before compilation of source code

C Program

ww Preprocessor

w.E Compiler

asy Linker

En
Executable
Code
gin
Fig. 2.8 Working Procedure of C Program

eer
There are four types of Preprocessor Directives supported by C language. They are:
 File Inclusion directive
 Macro Substitution directive
 Conditional directive ing
 Miscellaneous directive
.ne
List of all possible directives belong to each of the above is listed in Fig 2.9.

Fig Preprocessor Directives

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


The details of above listed preprocessor directives are narrated in Table.
Table Preprocessor directives and their description
Directive Description
#include It includes header file inside a C Program.
#define It is substitution macro. It substitutes a constant with an expression.
#if It includes a block of code depending upon the result of conditional
expression.
#else It is a complement of #if
#elif #else and #if in one statement. It is similar to if else ladder.
#endif It flags the end of conditional directives like #if, #elif etc.
#undef Undefines a preprocessor macro.
#ifdef Returns true If constant is defined earlier using #define.
#ifndef Returns true If constant is not defined earlier using #define.
#pragma Issues special commands to the compiler.
#error Prints error message on stderr.

ww
File Inclusion directive

#include
w.E
It is used to include header file inside C Program. It checks for header file in current

asy
directory, if path is not mentioned. To include user defined header file double quote is used
("") instead of using triangular bracket (< >).
Example:
En
#include <stdio.h>
#include "big.h" gin
// Standard Header File
// User Defined Header File

eer
Preprocessor replaces #include <stdio.h> with the content of stdio.h header file.
#include "Sample.h" instructs the preprocessor to get Sample.h from the current directory
and add the content of Sample.h file.
ing
Macro Substitution directive
#define .ne
It is a simple substitution macro. It substitutes all occurrences of the constant and replace
them with an expression.There are two types of macro supported by C. They are:
1. Simple macro
t
2. macro with arguments
Simple macro
Syntax:
#define identifier value
Where
#define - is apreprocessor directive used for text substitution.
identifier - is an identifier used in program which will be replaced by value.(In
general the identifiers are represented in captital letters in order to
differentiate them from variable)
value -It is the value to be substituted for identifier.

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


Example:
#define PI 3.14
#define NULL 0
Example:
//Program to find the area of a circle using simple macro
#include <stdio.h>
#define PI 3.14
int main()
{
int radius;
float area;
printf(“Enter the radius of circle \n”);

ww scanf(“%d”, &radius);
area= PI * radius * radius;

}
w.E
printf(“Area of Circle=%f”, radius);

Output
asy
Enter the radius of circle
10 En
Area of Circle = 314.000000
gin
macro with arguments
eer
#define Preprocessing directive can be used to write macro definitions with

ing
parameters. Whenever a macro identifier is encountered, the arguments are substituted by the
actual arguments from the C program.

.ne
Data type definition is not necessary for macro arguments. Any numeric values like
int, float etc can be passed as a macro argument . Specifically, argument macro is not case
sensitive.
Example:
#define area(r) (3.14*r*r)
t
Example:
//Program to find the area of a circle using macro with arguments
#include <stdio.h>
#define area(r) (3.14*r*r)
int main()
{
int radius;
float a;
printf(“Enter the radius of circle \n”);
scanf(“%d”, &radius);
a= area(radius);
printf(“Area of Circle=%f”, a);
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


Output
Enter the radius of circle
10
Area of Circle = 314.000000

Predefined Macros in C Language

C Programming language defines a number of macros. Table 2.8 is the list of some
commonly used macros in C
Table 2.8 Predefined macros in C
Macro Description
NULL Value of a null pointer constant.
EXIT_SUCCESS Value for the exit function to return in case of successful
completion of program.
EXIT_FAILURE Value for the exit function to return in case of program

ww RAND_MAX
__FILE__
termination due to failure.
Maximum value returned by the rand function.
Contains the current filename as a string.
__LINE__
__DATE__ w.E Contains the current line number as a integer constant.
Contains current date in "MMM DD YYYY" format.
__TIME__

Example:
asy
Contains current time in "HH:MM:SS" format.

En
gin
// Program to print the values of Predefined macros
#include <stdio.h>
#include <stdlib.h>
int main()
{ eer
printf("NULL : %d\n", NULL );
printf("EXIT_SUCCESS : %d\n", EXIT_SUCCESS ); ing
printf("EXIT_FAILURE : %d\n", EXIT_FAILURE );
printf("RAND_MAX : %d\n", RAND_MAX );
.ne
printf("File Name : %s\n", __FILE__ );
printf("DATE : %s\n", __DATE__ );
printf("Line : %d\n", __LINE__ );
return 0;
t
}
Output

NULL : 0
EXIT_SUCCESS : 0
EXIT_FAILURE : 1
RAND_MAX : 32767
File Name : BuiltinMacro.c
DATE : Aug 16 2017
Line : 12

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


Conditional directive

#if, #elif, #else and #endif

The Conditional directives permit to include a block of code based on the result of
conditional expression.
Syntax:
#if <expression>
statements;
#elif <expression>
statements;
#else
statements;
#endif

ww
Where
Expression represents a condition which produces a boolean value as a result.

w.E
Conditional directive is similar to if else condition but it is executed before
compilation. Condition_Expression must be only constant expression.

Example:
asy
En
//Program to illustrate the conditional directives
#include <stdio.h>
#define A 10
int main() gin
{
#if (A>5)
printf(“A=%d”, X);
eer
#elif (A<5)
printf(“A=%d”, 4); ing
#else
printf(“A=%d”, 0);
.ne
}
Output
X=10
#endif
return 0;
t
#undef

The #undef directive undefines a constant or preprocessor macro defined


previously using #define.

Syntax:

#undef <Constant>

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


Example:
#include<stdio.h>
#define P 100
#ifdef P
#undef P
#define P 30
#else
#define P 100
#endif
int main()
{
printf("%d",P);
return 0;
}
Output
30

#ifdef #ifdef, #ifndef

ww
#ifdef
#ifdef directive is used to check whether the identifier is currently defined.

#ifndef
w.E
Identifiers can be defined by a #define directive or on the command line.

#ifndef directive is used to check whether the identifier is not currently defined.
Example:
#ifdef PI
asy
En
printf( "Defined \n" );
#endif
#ifndef PI

#endif
printf( "First define PI\n" );
gin
Output:
First define PI eer
Miscellaneous directive ing
The pragma directive is used to access compiler-specific preprocessor .ne
extensions. Each pragma directive has different implementation rule and use . There
are many type of pragma directive and varies from one compiler to another compiler .If
compiler does not recognize particular pragma then it ignores the pragma statement
without showing any error or warning message.
t
Example:
#pragma sample
int main()
{
printf(“Pragma verification “);
return 0;
}
Output
Pragma verification

Since #pragma sample is unknown for Turbo c compiler, it ignores sample


directive without showing error or warning message and execute the whole program

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net

EC8393 PREPARED BY SRILAKSHMI EASYENGINEERING.NET


assuming #pragma sample statement is not present. The following are the list of
possible #pragma directives supported by C.

1. #pragma startup
2. #pragma exit
3. pragma warn
4. #pragma option
5. #pragma inline
6. #pragma argsused
7. #pragma hdrfile
8. #pragma hdrstop
9. #pragma saveregs

ww
#error

w.E
The #error directive causes the preprocessor to emit an error message. #error
directive is used to prevent compilation if a known condition that would cause the
program not to function properly.

Syntax: asy
#error “message”
En
Example:
gin
int main()
{
#ifndef PI eer
#error "Include PI”
#endif ing
}
return 0;
.ne
Output
compiler error --> Error directive : Include PI
#line
It tells the compiler that next line of source code is at the line number which has been
t
specified by constant in #line directive
Syntax:
#line <line number> [File Name]
Where Output
File Name is optional 700
Example: 701
int main() 702
{
#line 700
printf(Line Number %d”, __LINE__);
printf(Line Number %d”, __LINE__);
printf(Line Number %d”, __LINE__);
return 0;
}

Downloaded From : www.EasyEngineering.net


Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List
UNIT III LINEAR DATA STRUCTURES
Arrays and its representations – Stacks and Queues – Linked lists – Linked list-based implementation of
Stacks and Queues – Evaluation of Expressions – Linked list based polynomial addition.

INTRODUCTION
Definition
▪ Data structure is a particular way of organizing, storing and retrieving data, so that it can be used efficiently. It is the
structural representation of logical relationships between elements of data.

Where data structures are used?


▪ Data structures are used in almost every program or software system. Different kinds of data structures are suited
to different kinds of applications, and some are highly specialized to specific tasks.
▪ Applications in which data structures are applied extensively
o Compiler design (Hash tables),
o Operating system,

ww
o Database management system (B+Trees),
o Statistical analysis package,
o Numerical analysis (Graphs),
o Graphics,
w.E
o Artificial intelligence,
o Simulation

Classification of data structure


asy
En
gin
eer
ing
.ne


Primitive Data Structure - Primitive data structures are predefined types of data, which are supported by the
programming language. These are the basic data structures and are directly operated upon by the machine
instructions, which is in a primitive level.
t
Non-Primitive Data Structure - Non-primitive data structures are not defined by the programming language, but are
instead created by the programmer. It is a more sophisticated data structure emphasizing on structuring of a group
of homogeneous (same type) or heterogeneous (different type) data items.
▪ Linear data structure- only two elements are adjacent to each other. (Each node/element has a single successor)
o Restricted list (Addition and deletion of data are restricted to the ends of the list)
✓ Stack (addition and deletion at top end)
✓ Queue (addition at rear end and deletion from front end)
o General list (Data can be inserted or deleted anywhere in the list: at the beginning, in the middle or at the end)
▪ Non-linear data structure- One element can be connected to more than two adjacent elements.(Each node/element
can have more than one successor)
o Tree (Each node could have multiple successors but just one predecessor)
o Graph (Each node may have multiple successors as well as multiple predecessors)

Note - Array and Linked list are the two basic structures for implementing all other ADTs.

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


1 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List

ww
w.E
asy
En

gin
MODULARITY
Module- A module is a self-contained component of a larger software system.Each module is a logical unit and does
a specific job. Its size kept small by calling other modules.

eer
Modularity is the degree to which a system's components may be separated and recombined. Modularity refers to
breaking down software into different parts called modules.
▪ Advantages of modularity
o It is easier to debug small routines than large routines.
o Modules are easy to modify and to maintain.
ing
o Modules can be tested independently.
o Modularity provides reusability. .ne
o It is easier for several people to work on a modular program simultaneously.

ABSTRACT DATA TYPE


t
What is Abstract Data Type (ADT)?
▪ ADT is a mathematical specification of the data, a list of operations that can be carried out on that data. It
includesthe specification of what it does, but excludes the specification of how it does. Operations on set ADT:
Union, Intersection, Size and Complement.
▪ The primary objective is to separate the implementation of the abstract data types from their function. The
program must know what the operations do, but it is actually better off not knowing how it is done. Three most
common used abstract data types are Lists, Stacks, and Queues.
▪ ADT is an extension of modular design. The basic idea is that the implementation of these operations is written
once in the program, and any other part of the program that needs to perform an operation on the ADT can do so
by calling the appropriate function. If for some reason implementation details need to change, it should be easy to
do so by merely changing the routines that perform the ADT operations. This change, in a perfect world, would be
completely transparent to the rest of the program.
▪ Examples of ADT: Stack, Queue, List, Trees, Heap, Graph, etc.
▪ Benefits of using ADTs or Why ADTs
Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net
2 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List
o Code is easier to understand. Provides modularity and reusability.
o Implementations of ADTs can be changed without requiring changes to the program that uses the ADTs.
LIST ADT
▪ List is a linear collection of ordered elements.The general form of the list of size N is: A0, A1, …, AN-1
o Where A1 - First element
AN - Last element
N - Size of the list
o If the element at position 'i' is Ai then its successor is Ai+1 and its predecessor is Ai-1.
▪ Various operations performed on a List ADT
o Insert (X,5) - Insert the element X after the position 5.
o Delete (X) - The element X is deleted.
o Find (X) - Returns the position of X
o Next (i) - Returns the position of its successor element i+1.
o Previous (i) - Returns the position of its Predecessor element i-1.
o PrintList - Displays the List contents.
o MakeEmpty - Makes the List empty.

▪ ww
Implementation of List ADT

w.E
o Array implementation
o Linked List implementation
o Cursor implementation


asyARRAY IMPLEMENTATION OF LIST ADT
An array is a collection of homogeneous data elements described by a single name. Each element of an array is
referenced by a subscripted variable or value, called subscript or index enclosed in parenthesis. In array

En
implementation, elements of list are stored in contiguous cells of an array. FindKth operation takes constant time.
PrintList, Find operations take linear time.

▪ gin
Advantages - Searching an array for an individual element can be very efficient - Fast, random access of elements.
Limitations - Array implementation has some limitations such as

eer
1. Maximum size must be known in advance, even if it is dynamically allocated.
2. The size of array can’t be changed after its declaration (static data structure). i.e., the size is fixed.
3. Data are stored in continuous memory blocks.

ing
4. The running time for Insertion and deletion of elements is so slow. Inserting and deletion requires shifting other
data in the array. For example, inserting at position 0 requires first pushing the entire array down one spot to

.ne
make room, whereas deleting the first element requires shifting all the elements in the list up one, so the wor st
case of these operations is O(n). On average, half the list needs to be moved for either operation, so linear tim e
is still required.
5. Memory is wasted, as the memory remains allocated to the array throughout the program execution even few
nodes are stored.
t

Deleting an item

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


3 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List

Type Declarations
#define Max 10
int A[Max],N;
Routine to insert an Element in the specified position
void insert(int x, int p, int A[], int N)
{
int i;
If(p==N)
printf(“Array Overflow”);
else
{
for(i=N-1;i>=p-1;i--)
A[i+1]=A[i];
A[p-1]=x;
N=N+1;

ww }
}

w.E
Routine to delete an Element in the specified
int deletion(int p, int A[],int N)
{
int Temp;
If(p==N) asy
Temp=A[p-1];
else En
{
Temp=A[p-1]; gin
For(i=p-1;i<=N-1;i++)
A[i]=A[i+1];
eer
ing
}
N=N-1;
return Temp;
}
.ne
Find Routine
void Find (int X)
{
int i,f=0;
t
for(i=0;i<N;i++)
if(a[i]==x)
{
f=1;
break;
}
if (f==1)
printf(“Element found”);
else
printf(“Element not found”);
}

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


4 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List

STACK
➢ Definition
Stack is alinear list in which elements are added and removed from only one end, called the top.It is a "last in,
first out" (LIFO) data structure. At the logical level, a stack is an ordered group ofhomogeneous items or
elements.Because items are added and removed only from the top of the stack, the last element to be added is the first
to be removed. Stacks are also referred as "piles" and "push-down lists".

ww
w.E
➢ Operations on stacks
asy
▪ Push - Inserts new item to the top of the stack. After the push, the new item becomes the top.

En
▪ Pop - Deletes top item from the stack. The next older item in the stack becomes the top.
▪ Top - Returns a copy of the top item on the stack, but does not delete it.
▪ MakeEmpty - Sets stack to an empty state.
gin
▪ Boolean IsEmpty - Determines whether the stack is empty. IsEmpty should compare top with -1.

eer
▪ Boolean IsFull - Determines whether the stack is full. IsFull should compare top with MAX_ITEMS - 1.

➢ Conditions

ing
▪ Stack overflow - The condition resulting from trying to push an element onto a full stack.
▪ Stack underflow - The condition resulting from trying to pop an element from an empty stack.

.ne
t

New item pushed on Stack

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


5 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List

Two items popped from Stack

APPLICATIONS OF STACKS

▪ ww
Recursion - Example, Factorial, Tower of Hanoi.
Balancing Symbols, i.e., finding the unmatched/missing parenthesis. For example, ((A+B)/C and (A+B)/C). Compilers
often use stacks to perform syntax analysis of language statements.



w.E
Conversion of infix expression to postfix expression and decimal number to binary number.
Evaluation of postfix expression.
Backtracking- For example, 8-Queens problem.

asy
Function calls - When a call is made to a new function, all the variables local to the calling routine need to be save d
by the system, since otherwise the new function will overwrite the calling routine's variables. Similarly the current

En
location in the routine must be saved so that the new function knows where to go after it is done. For example, th e
main program calls operation A, which in turn calls operation B, which in turn calls operation C. When C finishes,

gin
control returns to B; when B finishes, control returns to A; and so on. The call-and-return sequence is essentially a
LIFO sequence, so a stack is the perfect structure for tracking it.

➢ Implementations of stack
1. Array implementation of stack eer
2. Linked list implementation of stack
ing
➢ Array implementation of stack

.ne
Stack can be represented using one dimensional array and it is probably the more popular solution.Here the

t
stack is of fixed size. That is maximum limit for storing elements is specified. Once the maximum limit is reached, it is not
possible to store the elements into it. So array implementation is not flexible and not an efficient method when resource
optimization is concerned.

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


6 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List
Push and Pop operation

Array implementation of Stack


#include<stdio.h>
#include<conio.h>
#define MAX 5

void push();
void pop();
void display();
int stack[MAX], top=-1, item;

void push()
{

ww
if(top == MAX-1)
printf("Stack is full");
else
{
w.E
printf("Enter item: ");
scanf("%d",&item);
top++;
stack[top] = item; asy
}
printf("Item pushed = %d", item);
En
}
gin
void pop()
{
eer
ing
if(top == -1)
printf("Stack is empty");
else
{
item = stack[top]; .ne
}
}
top--;
printf("Item popped = %d", item);
t
void display()
{
int i;
if(top == -1)
printf("Stack is empty");
else
{
for(i=top; i>=0; i--)
printf("\n %d", stack[i]);
}
}

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


7 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List

QUEUE (LINEAR QUEUE)


➢ Definition
A queue is an ordered group of homogeneous items or elements, in which new elements are added at one end
(the “rear”) and elements are removed from the other end (the “front”). It is a "First in, first out" (FIFO) linear data
structure. Example, a line of students waiting to pay for their textbooks at a university bookstore.

ww
➢ Types of Queues
w.E
asy
There are three major variations in a simple queue. They are
▪ Linear queue
▪ Circular queue
▪ Double ended queue (Deque)
En
o Input restricted deque
o Output restricted deque
▪ Priority queue gin
➢ Operations on Queue eer
▪ Enqueue -Insertsan itemat the rear end of the queue.
▪ Dequeue- Deletesan item at the front end of the queue and returns.
ing
➢ Conditions
▪ Queue overflow - The condition resulting from trying to enqueue an element onto a full Queue. .ne
▪ Queue underflow - The condition resulting from trying to dequeue an element from an empty Queue.

➢ Implementation of Queue
t
1. Array implementation
2. Linked list implementation
o Array and linked list implementations give fast O(1) running times for every operation

➢ Array implementation of Linear Queue

0 1 2 3 4
Empty Queue F = R = -1
10
0 1 2 3 4
^^

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


8 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List
FR
After Enqueue (10)

10 3
0 1 2 3 4
^ ^
F R
After Enqueue (3)
10 3 41
0 1 2 3 4
^ ^

ww F R

w.E After Enqueue (41)


3 41

asy 0 1
^
2
^
3 4

En
F R

3 41 gin
After Dequeue ()
76
0 1 2 3 4
eer
^
F
^
R ing
After Enqueue (76)
.ne
0
3
1
^
41
2
76
3
66
4
^
t
F R
After Enqueue (66)
41 76 66
0 1 2 3 4
^ ^
F R
After Dequeue ()
▪ There is one potential problem with array implementation. From the above queue, now if we attempt to add more
elements, even though 2 queue cells are free, the elements cannot be inserted. Because in a queue, elements are

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


9 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List
always inserted at the rear end and hence rear points to last location of the queue array Q[4]. That is queue is full
(overflow condition) though it is empty.
▪ The simple solution is that whenever front or rear gets to the end of the array, it is wrapped around to the
beginning. This is known as a circular array implementation.
Array implementation of Linear Queue
#include <stdio.h>
#include<conio.h>

#define MAX 3

void enqueue();
void dequeue();
void display();

int queue[MAX], rear=-1, front=-1, item;

ww
void enqueue()
{

else w.E
if(rear == MAX-1)
printf("Queue is full");

asy
printf("Enter item : ");
scanf("%d", &item);

En
if (rear == -1 && front == -1)
rear = front = 0;
else
rear = rear + 1; gin
queue[rear] = item;
printf("Item enqueued : %d", item);
eer
ing
}
}

void dequeue()
{ .ne
if(front == -1)
printf("Queue is empty");
else
{
t
item = queue[front];
if (front == rear)
front = rear = -1;
else
front = front + 1;
printf("Item dequeued : %d", item);
}
}

void display()
{
int i;
if(front == -1)

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


10 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List
printf("Queue is empty");
else
for(i=front; i<=rear; i++)
printf("%d ", queue[i]);
}
Circular Queue

▪ In circular queues the elements Q[0],Q[1],Q[2] .... Q[n – 1] is represented in a circularfashion with Q[1] following
Q[n]. A circularqueue is one in which the insertion of a newelementis done at the very first location of the queue if
the last location at the queue isfull.
▪ Initially Front = Rear = -1. That is, front and rear are at the same position.
▪ At any time the position of the element to be inserted will be calculated by therelation: Rear = (Rear + 1) % SIZE
▪ After deleting an element from circular queue the position of the front end is calculatedby the relation: Front=
(Front + 1) % SIZE.
▪ After locating the position of the new element to be inserted, rear, compare it withfront. If Rear = Front, the queue
is full and cannot be inserted anymore.

ww
▪ No of elements in a queue = (Rear – Front + 1) % N
Deque - Double Ended QUEeue
➢ Definition

w.E
A deque is a homogeneous list in which inserted and deleted operations are performed at either ends of the
queue. That is, we can add a new element at the rear or front end and also we can remove an element from both fro nt

asy
and rear end. Hence it is called double ended queue. The most common ways of representing deque are: doubly linked
list, circular list.

En
gin
eer
➢ Types of deques
1. Input restricted deque
ing
.ne
2. Output restricted deque

✓ An input restricted deque is a deque, which allows insertion at only 1 end, rear end, but allows deletion at both
ends, rear and front end of the lists.
✓ An output-restricted deque is a deque, which allows deletion at only one end, front end, but allows insertion at
both ends, rear and front ends, of the lists.

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


11 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List

Priority Queue
➢ Definition
▪ Priority Queue is a queue where each element is assigned a priority. The priority may implicit (decided by its value)
or explicit (assigned). In priority queue, the elements are deleted and processed by following rules.
o An element of higher priority is processed before any element of lower priority.
o Two elements with the same priority are processed according to the order in which they were inserted to
the queue.
▪ Example for priority queue:
o In a telephone answering system, calls are answered in the order in which they are received;
o Hospital emergency rooms see patients in priority queue order; the patient with the most severe injuries
sees the doctor first.

ww
w.E Queue of people with priority

▪ asy
A node in the priority queue will contain Data, Priority and Next field. Data field will store the actual information;
Priority field will store its corresponding priority of the data and Next will store the address of the next node.
When an element is inserted into the priority queue, it will check the priority of the element with the element(s)

En
present in the linked list to find the suitable position to insert. The node will be inserted in such a way that the da ta
in the priority field(s) is in ascending order. We do not use rear pointer when it is implemented using linked list,

gin
because the new nodes are not always inserted at the rear end.

➢ Types of priority queues

eer
1. Ascending priority queue - It is a queue in which items can be inserted arbitrarily (in any order) and from which only

ing
the smallest item can be deleted first.
2. Descending priority queue - It is a queue in which items can be inserted arbitrarily (in any order) and from which
only the largest item can be deleted first.

Applications of queue .ne



printer are placed on a queue.
t
When jobs are submitted to a printer, they are arranged in order of arrival. Thus, essentially, jobs sent to a line

Virtually every real-life line is (supposed to be) a queue. For instance, lines at ticket counters are queues, because
service is first-come first-served.
▪ Another example concerns computer networks. There are many network setups of personal computers in which the
disk is attached to one machine, known as the file server. Users on other machines are given access to files on a first-
come first-served basis, so the data structure is a queue.
▪ Calls to large companies are generally placed on a queue when all operators are busy.
▪ There are several algorithms that use queues to solve problems easily. For example, BFS, Binary tree traversal etc.
▪ Round robin techniques for processor scheduling is implemented using queue.

LINKED LIST
Definition
Linked list is adynamic data structure which is an ordered collection of
homogeneous dataelements called nodes, in which each element contains two parts:
data or Info and one or more links. The data holds the application data to be
processed. The link contains (the pointer) the address of the next element in the list.

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


12 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List

Why Linked List?


▪ Even though searching an array for an individual element can be very efficient, array has some limitations. So arrays
are generally not used to implement Lists.

Advantages of Linked List


1. Linked list are dynamic data structures - The size is not fixed. They can grow or shrink during the execution of a
program.
2. Efficient memory utilization - memory is not pre-allocated. Memory is allocated, whenever it is required and it is de-
allocated whenever it is not needed. Data are stored in non-continuous memory blocks.
3. Insertion and deletion of elements are easier and efficient. Provides flexibility. No need to shift elements of a linked
list to make room for a new element or to delete an element.

Disadvantages of Linked List


1. More memory - Needs space for pointer (link field).
2. Accessing arbitrary element is time consuming. Only sequential search is supported not binary search.

ww
Operations on Linked List

w.E
The primitive operations performed on the linked list are as follows
1. Creation- This operation is used to create a linked list. Once a linked list is created with one node, insertion
operation can be used to add more elements in a node.

inserted,
asy
2. Insertion- This operation is used to insert a new node at any specified location in the linked list. A new node may b e

✓ At the beginning of the linked list,


✓ At the end of the linked list,
En
✓ At any specified position in between in a linked list.

gin
3. Deletion- This operation is used to delete an item (or node) from the linked list. A node may be deleted from the,
✓ Beginning of a linked list,
✓ End of a linked list,
✓ Specified location of the linked list.
eer
4. Traversing - It is the process of going through all the nodes from one end to another end of a linked list. In a singly

ing
linked list we can visit the nodes only from left to right (forward traversing). But in doubly linked list forward and
backward traversing is possible.
5. Searching- It is the process finding a specified node in a linked list.
.ne
6. Concatenation- It is the process of appending the second list to the end of the first list. Consider a list A having n

After concatenation A will contain (name) nodes.

Types of linked list


t
nodes and B with m nodes. Then the operation concatenation will place the 1st node of B in the (n+1) the node in A.

1. Singlylinked list or Linear list or One-waylist


2. Doubly linked list or Two-way list
3. Circular linked list
4. Doubly circular linked list

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


13 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List

SINGLY LINKED LIST


➢ Definition
In singly linked list, each element (except the first one) has a unique predecessor, and each element (except the
last one) has a unique successor. Each node contains two parts: data or Info and link. The data holds the application
data to be processed. The link contains the address of the next node in the list. That is, each node has a single pointer to
the next node. The last node contains a NULL pointer indicating the end of the list.

➢ SentinelNode
▪ It is also called as Header nodeor Dummy node.
▪ Advantages

ww
o Sentinel node is used to solve the following problems
✓ First, there is no really obvious way to insert at the front of the list from the definitions given.
✓ Second, deleting from the front of the list is a special case, because it changes the start of the list; careless

w.E
coding will lose the list.
✓ A third problem concerns deletion in general. Although the pointer moves above are simple, the deletion
algorithm requires us to keep track of the cell before the one that we want to delete.
▪ Disadvantages
o It consumes extra space.
asy
➢ Insertion
a. Creating a newnode from empty List En
gin
eer
b. Inserting a node to the front of list ing
.ne
t
c. Inserting a node in the middle

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


14 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List

d. Inserting a node to the end of list

ww
➢ Deletion
a. Inserting a node to the front of list

w.E
asy
En
gin
b. Deleting the middle node
eer
ing
.ne
t
c. Deleting the last node

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


15 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List

Singly linked list implementation


Type Declarations
struct node
{
int data;
struct node *next;
}*head=NULL:
typedef struct Node *position;

Routine to check whether the List is empty


/* Returns 1 if List is empty */
int IsEmpty (position head)

ww {
if (head->next == NULL)

w.E
}
return(1);

asy
En
Routine to check whether the current position is last
/* Returns 1 if P is the last position in L */
int IsLast (position p)
{ gin
if (p->Next == NULL)
return(1);
eer
}

ing
.ne
Find Routine
/* Returns the position of X in L; NULL if not found */
Position Find (int X)
{
t
position p;
P = head->next;
while( (p!= NULL) && (p->data != X) )
p = p->next;
return P;
}

FindPrevious Routine
/* Returns the previous position of X in L */

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


16 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List
position FindPrevious (int X)
{
position P;
P = head;
while( (P->Next!= NULL) && (P->Next->data != X) )
P = P->Next;
return P;
}

FindNext Routine
/* Returns the position of X in L; NULL if not found */
Position Find (int X)

ww {
position p;
P = head->next;

w.E while( (p!= NULL) && (p->data != X) )


p = p->next;
return P->next;
}
asy
En
void traversal () gin
{
position p; eer
P = head->next;
while( p!= NULL)
ing
{
printf(p->data);
p = p->next; .ne
}
}
t
Insertion
Inserting a node to the front of list

Insert at Beginning
void Insert_beg (int X)
{
position NewNode;
NewNode = malloc (sizeof(struct Node));
Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net
17 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List
if(NewNode != NULL)
{
NewNode->data = X;
NewNode->next = L->Next;
head->next = NewNode;
}
}

b.Inserting a node in the middle

ww
Insertion at Middle
/* Insert element X after position P */
void Insert_mid (int X, position P)
{
w.E
position NewNode;
NewNode = malloc (sizeof(struct Node));
if(NeWNode != NULL)
{ asy
NewNode->data = X;
NewNode->next = P->next;
En
}
P->next = NewNode;
gin
eer
}
c.Inserting a node to the end of list

ing
.ne
t
Insert at Last
void Insert_last (int X)
{
position NewNode,P;
NewNode = malloc (sizeof(struct Node));
if(NewNode != NULL)
{
while(P->next!=NULL)
P = P->next;
NewNode->data = X;
NewNode->next = NULL;
P->next = NewNode;
}

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


18 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List
}

➢ Deletion
Deleting a node to the front of list

Delete at Beginning
void Delete_beg ()
{
position TempCell;

{
ww
if(head->next!=NULL)

TempCell = head->next;

}
w.E
head->next = TempCell ->next;
free(TempCell);

Deleting the middle node


asy
En
gin
eer
ing
Delete at Middle Routine
void Delete (int X)
{
position P, TempCell;
P = FindPrevious(X); .ne
}
TempCell = P->next;
P->Next = TempCell ->Next;
free(TempCell);
t
Deleting the last node

Delete at Last
void Delete_last ()
{
position TempCell,P;
while(P->next->next!=NULL)
Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net
19 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List
P = P->next;
TempCell = P->next;
P->next = NULL;
free(TempCell);
}

CIRCULAR LINKED LIST


➢ Why circular linked list? Or advantages over singly linked list
▪ With a singly linked list structure, given a pointer to a node anywhere in the list, we can access all the nodes that
follow but none of the nodes that precede it. We must always have a pointer to the beginning of the list to be able
to access all the nodes in the list.In a circular linked list, every node is accessible from a given node.
▪ In deletion of singly linked list, to find the predecessor requires that a search be carried out by chaining through the
nodes from the first node of the list. But this requirement does not exist for a circular list, since the search for the
predecessor of node X can be initiated from X itself.
▪ Concatenation and splitting becomes more efficient.

ww
➢ Disadvantages
▪ The circular linked list requires extra care to detect the end of the list. It may be possible to get into an infinite loo p.

w.E
So it needs a header node to indicate the start or end of the list.

➢ Definition

asy
▪ A circular linked list is one, which has no beginning and no end. Circular linked list is a list in which every node has a
successor; the "last" element is succeeded by the "first" element. We can start at any node in the list and traverse
the entire list.
En
gin
eer
➢ Definition
DOUBLY LINKED LIST
ing
▪ Doubly linked list is a linked list in which each node is linked to
both its successor and its predecessor. In a doubly linked list, the .ne
nodes are linked in both directions. Each node of a doubly linked
list contains three parts:
o Info: the data stored in the node
o Next/FLink: the pointer to the following node.
t
o Back/BLink: the pointer to the preceding node

➢ Why doubly linked list?


▪ In singly linked list, it is difficult to perform traversing the list in reverse.
▪ To delete a node, we need find its predecessor of that node.

➢ Advantages
▪ Traversing in reverse is possible.
▪ Deletion operation is easier, since it has pointers to its predecessor and successor.
Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net
20 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List
▪ Finding the predecessor and successor of a node is easier.

➢ Disadvantages
▪ A doubly linked list needs more operations while inserting or deleting and it needs more space (to store the extra
pointer). There are more pointers to keep track of in a doubly linked list. For example, to insert a new node after a
given node, in a singly linked list, we need to change two pointers. The same operation on a doubly linked list
requires four pointer changes.

DOUBLY CIRCULAR LINKED LIST


➢ Why doubly circular linked list?
The aim of considering doubly circular linked list is to simplify the insertion and deletion operations performed on
doubly linked list.

➢ Definition
A circular linked list is one, which has no beginning and no end. A doubly circular linked list is a doubly linked list with

ww
circular structure in which the last node points to the first node and the first node points to the last node and there are
two links between the nodes of the linked list. In doubly circular linked list, the left link of the leftmost node contains the

w.E
address of the rightmost node and the right link of the rightmost node contains the address of the leftmost node.

asy
En
gin
A Doubly Linked List

APPLICATIONS OF LINKED LIST eer


ing
All kinds of dynamic allocation related problems can be solved using linked lists. Some of the applications are given
below:
1. Polynomial ADT
2. Radix sort or Card sort
.ne
t
3. Multi-list
4. Stacks and Queues

Linked list implementation of stack


The limitations of array implementation can be overcome by dynamically implementing (is also called linked list
representation) the stack using pointers.In linked list implementation, the stack does not need to be of fixed size.
Insertions and deletions are done more efficiently. Memory space also not wasted, because memory space is allocated
only when it is necessary (when an element is pushed) and is de-allocated when the element is deleted.

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


21 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List

Push operation

Pop operation

Linked list implementation of Stack

ww
void push(int x);
void pop();
void display();

struct node
{
w.E
int data;
struct node *next; asy
} *top = NULL;
En
typedef truct node * position;
gin
eer
void push(int x)
{
position p;
p =(struct node *)malloc(sizeof(struct node));
if (p == NULL) ing
printf("Memory allocation error \n");
else
.ne
{
if (top == NULL)
{
top =(struct node *)malloc(sizeof(struct node));
t
p->data=x;
p->next = NULL;
top->next = p;
}
else
{
p->data=x;
p->next = top->next;
top->next=p;
}

}
}

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


22 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List

void pop()
{
position p;
p = top->next;

if (top == NULL)
printf("Stack is empty");
else
{
top->next= top->next->next;
printf("\n Popped value : %d\n", p->data);
free(p);
}
}

ww
void display()
{
struct node *p;
if (top == NULL)
w.E
printf("Stack is empty");
else
{
p = top; asy
while(p != NULL)
{ En
printf("\n%d", p->data);
p = p->next; gin
}
}
eer
ing
}

Linked list implementation of Linear Queue

.ne
t

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


23 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List
Linked list implementation of Linear Queue
struct node
{
int data;
struct node *next;
} *front = NULL, *rear=NULL;

typedef truct node * position;

void enqueue(int x);


void dequeue();
void display();
int item;

struct node
{

ww
int data;
struct node *next;
} *top = NULL;

w.E
typedef truct node * position;

void dequeue() asy


{
En
position p;
p = front->next; gin
if (front == NULL)
eer
ing
printf("Queue is empty\n");
else
{
printf("\n Dequeued value : %d\n", p->data);
front->next=front->next->next; .ne
}
}
free(p);
t
void display()
{
position p;
p = front->next;

if (front == NULL)
printf("Queue is empty\n");
else
{
printf("Queue elements are : \n");
while (p != NULL)
{

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


24 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List
printf("%d ",p->data);
p = p->next;
}
}

APPLICATIONS OF STACKS
▪ Recursion - Example, Factorial, Tower of Hanoi.
▪ Balancing Symbols, i.e., finding the unmatched/missing parenthesis. For example, ((A+B)/C and (A+B)/C). Compilers
often use stacks to perform syntax analysis of language statements.
▪ Conversion of infix expression to postfix expression and decimal number to binary number.
▪ Evaluation of postfix expression.
▪ Backtracking- For example, 8-Queens problem.
▪ Function calls - When a call is made to a new function, all the variables local to the calling routine need to be saved

ww
by the system, since otherwise the new function will overwrite the calling routine's variables. Similarly the current
location in the routine must be saved so that the new function knows where to go after it is done. For example, th e

w.E
main program calls operation A, which in turn calls operation B, which in turn calls operation C. When C finishes,
control returns to B; when B finishes, control returns to A; and so on. The call-and-return sequence is essentially a
LIFO sequence, so a stack is the perfect structure for tracking it.

asy
Conversion of infix expression into postfix expression
1. Scan the infix expression from left to right. Repeat Steps 3 to 6 for each element of expression until the stack is
empty.
En
2. If an operand is encountered, add it to the postfix expression.

gin
3. If an opening parenthesis is encountered, push it onto the stack and do not remove it until closing parenthesis is
encountered.
4. If an operator 'op' is encountered, then
eer
a. Repeatedly pop from stack and add each operator (on the top of stack), which has the same precedence as,
or higher precedence than 'op'.
b. Add 'op' to stack.
5. If a closing parenthesis is encountered, then ing
.ne
a. Repeatedly pop from stack and add to postfix expression (on the top of stack) until anopening parenthesis is
encountered.

Operator precedence
( Highest
t
b. Remove the opening parenthesis from the stack. [Do not add the opening parenthesis to postfix expression.]

^ -
*, / -
+, - Least

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


25 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List

ww
w.E
asy
En
gin
eer

1.
Evaluation of postfix expression
ing
Scan the postfix expression from left to right and repeat steps 2 & 3 for each element of postfix expression.
2.
3.
If an operand is encountered, push it onto the stack.
If an operator 'op' is encountered, .ne
a. Pop two elements from the stack, where A is the top element and B is the next top element.
b. Evaluate B 'op' A.
c. Push the result onto stack.
4. The evaluated value is equal to the value at the top of the stack.
t

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


26 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List

ww
w.E
asy
➢ Balancing parenthesis En
gin
▪ One common programming problem is unmatched parenthesis in an algebraic expression. When parentheses are
unmatched, two types of errors can occur:
o Opening parenthesis can be missing. For example, [A+B]/C}.
o Closing parenthesis can be missing. For example, {(A+B)/C.
eer
▪ The steps involved in checking the validity of an arithmetic expression
1. Scan the arithmetic expression from left to right.
2. If an opening parenthesis is encountered, push it onto the stack. ing
3. If a closing parenthesis is encountered, the stack is examined.
.ne
a. If the stack is empty, the closing parenthesis does not have an opening parenthesis. So the expression is
invalid.
t
b. If the stack is not empty, pop from the stack and check whether the popped item corresponds to the closing
parenthesis. If a match occurs, continue. Otherwise, the expression is invalid.
4. When the end of the expression is reached, the stack must be empty; otherwise one or more opening parenthesis
does not have corresponding closing parenthesis. So the expression is invalid.

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


27 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List

ww
w.E
asy
En
gin
eer
ing
.ne
➢ Polynomial ADT
t
Polynomials are expressions containing terms with non-zero coefficients and exponents. Linked list is generally used to
represent and manipulate single variable polynomials. Different operations, such as addition, subtraction, division and
multiplication of polynomials can be performed using linked list. In this representation, each term/element is referred as
a node. Each node contains three fields namely,
1. Coefficient - Holds value of the coefficient of a term.
2. Exponent - Holds exponent value of a term.
3. Link - Holds the address of the next term.

For example,

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


28 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List

ww
➢ Multi-list

w.E
Multi-list is the most complicated applications of linked list. It is useful to maintain student registration in a
university, employee involvement in different projects etc. The student registration contains two reports. The first
report lists the registration for each class (C) and the second report lists, by student, the classes that each student (S) is

asy
registered for. In this implementation, we have combined two lists into one. All lists use a header and are circular.
Circular list saves space but does so at the expense of time.

En
gin
eer
ing
.ne
Polynomial Addition
t
Type Declaration:
struct node
{
int coeff;
int pow;
struct node *next;
}*poly1=NULL,*poly2=NULL,*poly=NULL;

void polyadd(struct node *poly1,struct node *poly2,struct node *poly)


{
while((poly1->next !=NULL)&& (poly2->next!=NULL))
{
if(poly1->pow > poly2->pow)
Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net
29 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly1=poly1->next;
}
else if(poly1->pow<poly2->pow)
{
poly->pow=poly2->pow;
poly->coeff=poly2->coeff;
poly2=poly2->next;
}
else
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff+poly2->coeff;
poly1=poly1->next;

} ww
poly2=poly2->next;

w.E
poly->next=(struct node *)malloc(sizeof(struct node));
poly=poly->next;
poly->next=NULL;
}
while(poly1->next !=NULL)
{ asy
poly->pow=poly1->pow; En
poly->coeff=poly1->coeff;
poly1=poly1->next; gin
}
while(poly2->next!=NULL)
{ eer
poly->pow=poly2->pow;
poly->coeff=poly2->coeff; ing
}
poly2=poly2->next;
.ne
}
PART A
1. Why do we need ADT for implementing data structures? Or Benefits of ADT.
▪ Code is easier to understand.
t
▪ Provides modularity and reusability.
▪ Implementations of ADTs can be changed without requiring changes to the program that uses the ADTs.

2. What is an ADT? What are all concerned and not concerned in an ADT? Give example.
▪ ADT is a mathematical specification of the data, a list of operations that can be carried out on that data. It includes
the specification of what it does, but excludes the specification of how it does. Operations on set ADT: Union,
Intersection, Size and Complement.
▪ Examples of ADT: Stack, Queue, List, Trees, Heap, Graph, etc.

3. Define a linear and non-linear data structure.


▪ Linear data structure- only two elements are adjacent to each other. (Each node/element has a single successor)
o Restricted list (Addition and deletion of data are restricted to the ends of the list)
✓ Stack (addition and deletion at top end)

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


30 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List
✓ Queue (addition at rear end and deletion from front end)
o General list (Data can be inserted or deleted anywhere in the list: at the beginning, in the middle or at the end)
▪ Non-linear data structure- One element can be connected to more than two adjacent elements.(Each node/element
can have more than one successor)
o Tree (Each node could have multiple successors but just one predecessor)
o Graph (Each node may have multiple successors as well as multiple predecessors)

4. Define List ADT with example.


▪ List is a linear collection of ordered elements. The general form of the list of size N is: A0, A1, …, AN-1
o Where A1 - First element
AN - Last element
N - Size of the list
o If the element at position 'i' is Ai then its successor is Ai+1 and its predecessor is Ai-1.

5. Which operations are supported by the list ADT?


▪ Various operations performed on a List ADT

ww
o Insert (X,5)
o Delete (X)
- Insert the element X after the position 5.
- The element X is deleted.
o Find (X)
o Next (i)
o Previous (i) w.E
- Returns the position of X
- Returns the position of its successor element i+1.
- Returns the position of its Predecessor element i-1.
o PrintList
o MakeEmpty
asy
- Displays the List contents.
- Makes the List empty.

En
6. What is the advantage linked list over arrays?. Mention their relative advantages and disadvantages?
▪ Advantages of Array

gin
o Searching an array for an individual element can be very efficient,
▪ Advantages of Linked List

program.
eer
o Linked list are dynamic data structures - The size is not fixed. They can grow or shrink during the execution of a

o Efficient memory utilization - memory is not pre-allocated. Memory is allocated, whenever it is required and it is

ing
de-allocated whenever it is not needed. Data are stored in non-continuous memory blocks.
o Insertion and deletion of elements are easier and efficient. Provides flexibility. No need to shift elements of a
linked list to make room for a new element or to delete an element.
▪ Disadvantages of Linked List .ne
o More memory - Needs space for pointer (link field).
o Accessing arbitrary element is time consuming. Only sequential search is supported not binary search.
7. What are the advantages of doubly linked list over singly linked list?
t
▪ In singly linked list, it is difficult to perform traversing the list in reverse. To delete a node, we need find its
predecessor of that node.

8. List certain applications of lists.


▪ All kinds of dynamic allocation related problems can be solved using linked lists. Some of the applications are given
below:
o Polynomial ADT
o Radix sort or Card sort
o Multi-list
o Stacks and Queues

9. What are the two important features present in a pointer implementation of linked list?
▪ The two important features present in a pointer implementation of linked list are as follows:

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


31 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List
1. The data are stored in a collection of structures. Each structure contains data and a pointer to the next
structure.
2. A new structure contains data from the system’s global memory by a call to malloc and released by a call to free.

10. Write operations that can be done on stack?


▪ Push - Inserts new item to the top of the stack. After the push, the new item becomes the top.
▪ Pop - Deletes top item from the stack. The next older item in the stack becomes the top.
▪ Top - Returns a copy of the top item on the stack, but does not delete it.
▪ MakeEmpty - Sets stack to an empty state.
▪ Boolean IsEmpty - Determines whether the stack is empty. IsEmpty should compare top with -1.
▪ Boolean IsFull - Determines whether the stack is full. IsFull should compare top with MAX_ITEMS - 1.

11. What are the conditions that followed in the array implementation of stack?
▪ Stack overflow - The condition resulting from trying to push an element onto a full stack.
▪ Stack underflow - The condition resulting from trying to pop an element from an empty stack.

12.
▪ ww
Mention any four applications of stack.
Recursion - Example, Factorial, Tower of Hanoi.



Balancing Symbols,

w.E
Conversion of infix expression to postfix expression and decimal number to binary number.
Evaluation of postfix expression.

13.

What is circular queue?
asy
Backtracking- For example, 8-Queens problem.

In circular queues the elements Q[0],Q[1],Q[2] .... Q[n – 1] is represented in a circular fashion with Q[1] following

En
Q[n]. A circular queue is one in which the insertion of a new element is done at the very first location of the queue if
the last location at the queue is full.

14. Why is circular queue better than standard linear queue? gin
eer
▪ There is one potential problem in linear queue with array implementation. Sometimes if we attempt to add more
elements, even though queue cells are free, the elements cannot be inserted. Because in a queue, elements are
always inserted at the rear end and if the rear points to last location of the queue array. That is queue is full
(overflow condition) though it is empty.
15. What is deque? ing
.ne
▪ A deque is a homogeneous list in which inserted and deleted operations are performed at either ends of the queu e.
That is, we can add a new element at the rear or front end and also we can remove an element from both front an d
rear end. Hence it is called double ended queue. The most common ways of representing deque are: doubly linked
list, circular list.
16. What is the difference between a stack and a Queue?
Stack Queue
t
✓ Stack is a restricted ordered list where in all ✓ Queue is a restricted ordered list where in all
insertions and deletions are done at one end insertions are done at rear end and deletions
called top. are done at front end.
✓ Stack is called as LIFO structure. ✓ Queue is called as FIFO structure.
✓ To insert an element into the stack top is ✓ To insert an element into the queue rear end
incremented by 1. is incremented by 1.
✓ To delete an element from the stack top is ✓ To delete an element from the queue front
decremented by 1. end is incremented by 1.
✓ Stack full condition: Top = MAX - 1 ✓ Queue full condition : Rear = MAX – 1
✓ Stack empty condition: Top = - 1 ✓ Queue empty condition : Front > Rear

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


32 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit III– Linear Structures-List

17. Mention any two applications of queue.


▪ Calls to large companies are generally placed on a queue when all operators are busy.
▪ There are several algorithms that use queues to solve problems easily. For example, BFS, Binary tree traversal etc.
▪ Round robin techniques for processor scheduling is implemented using queue

PART B
1. Explain the array and linked list implementation of stack.
2. Explain the array and linked list implementation of queue.
3. Explain how stack is applied for evaluating an arithmetic expression.
4. Explain the applications of stack, queue and linked list.
5. Explain polynomial addition using Linked list.

ww
w.E
asy
En
gin
eer
ing
.ne
t

Dr.S.Thanga Ramya & Mrs.D.Praveena EasyEngineering.net


33 Downloaded From : www.EasyEngineering.net
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures

UNIT IV
NON-LINEAR DATA STRUCTURES

Syllabus:

Trees – Binary Trees – Binary tree representation and traversals –Binary Search Trees – Applications of
trees. Set representations – Union-Find operations. Graph and its representations – Graph Traversals.
TREES STRUCTURE
Definition:
Tree is a non-linear data structure. It organized the data in hierarchical manner. A tree is a finite set of one
or more nodes such that there is a specially designated node called the root node and root node can have zero
or more sub trees T1,T2,T3,……………..,Tn. Each of whose roots are connected by a directed edge from root R.
Tree is collection of nodes in which the first node is called root and root has many number of sub tree T1,

ww
T2, T3………..… Tn.

w.E
asy
En
gin
eer
Terms:
1. Root ing
A node which does not have a parent is called as root node.
2. Node
.ne
Each data element in the tree is called as node.
3. Leaf node
A node which does not have any children is called leaf node.
4. Siblings
t
A child of same parent is called sibling.
5. Path
A path from node n1 to nk is defined has sequence of nodes n1, n2, n3………nk. Such that ni is a parent
of ni +1.Example: A->B->E->J
6. Length for a path
Number of edges in the path.
Example: Consider path from A to J is 3
7. Degree
Number of sub trees of the node is called degree.
8. Level
Root is at level 1 then i+s children are at level 2+1
Example: level
9. Depth
Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net
1
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures
For any node n, the depth n is length of unique path from root to n.
10. Height
For any node n, the height of node n is the length of longest path from n to left.
11. Forest
Collection of tree node is known as forest.

BINARY TREE ADT

Definition: -

Binary Tree is a special type of tree in which no node can have most two children. Typically, child nodes
of a binary tree on the left is called left child and node on right is called right child. Maximum number of nodes

ww
w.E
asy
at level i of a binary tree is 2i-1.
En
gin
A simple binary tree of size 9 and height 3, with a root node whose value is 2. The above tree is neither
a sorted nor a balanced binary tree
Representation of tree.
1. Sequential representation or array representation.
2. Linked representation. eer
1. Sequential representation or array representation.
ing
The elements are represented using arrays. For any element in position i, the left child is in position 2i,
the right child is in position (2i + 1), and the parent is in position (i/2).
.ne
t

A B C D E F G

0 1 2 3 4 5 6

Array representation of Binary Tree

2. Linked representation
Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net
2
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures

The elements are represented using pointers. Each node in linked representation has three fields, namely,
* Pointer to the left subtree
* Data field
* Pointer to the right subtree

ww Linked representation of Binary Tree

w.E
Routine of creating tree using linked list.
struct tree
{
int data;
struct tree *leftchild; asy
struct tree *rightchild;
}; En
Recursive Traversals of Tree
gin
Traversing means visiting each node at once. Tree traversal is a method for visiting all the nodes in the
tree exactly once.
There are three types of tree traversal techniques, namely eer
1. Inorder Traversal or symmetric order
2. Preorder Traversal or depth-first order ing
3. Postorder Traversal
.ne
Inorder Traversal
The inorder traversal of a binary tree is performed as
* Traverse the left subtree in inorder
* Visit the root
t
* Traverse the right subtree in inorder.
Recursive Routine for Inorder Traversal
void Inorder (Tree T)
{
if (T!=NULL)
{
Inorder (T->left);
printf(“%d”,T->data);
Inorder (T->right);
}
}
Preorder Traversal

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


3
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures
The preorder traversal of a binary tree is performed as follows,
* Visit the root
* Traverse the left subtree in preorder
* Traverse the right subtree in preorder.

Recursive Routine for Preorder Traversal


void Preorder (Tree T)
{
if (T ! = NULL)
{
printf(“%d”,T->data);
Preorder (T ->left);
Preorder (T ->right);
}

ww Postorder Traversal
The postorder traversal of a binary tree is performed by the following steps.

w.E
* Traverse the left subtree in postorder.
* Traverse the right subtree in postorder.
* Visit the root.

asy
Recursive Routine for Postorder Traversal
void Postorder (Tree T)
{
if (T ! = NULL) En
{
Postorder (T ->Left); gin
Postorder (T ->Right);
printf(“%d”,T->data);
eer
}

EXPRESSION TREE
ing
.ne
An expression tree is tree in which left nodes have the operands and interior node have the operators.
Like binary tree, expression tree can also be travesed by inorder, preorder and postorder traversal.
Example:
(A+B)*(C-D) t
*

+ -

A B C D
Constructing an Expression Tree
Let us consider postfix expression given as an input for constructing an expression tree by performing the
following steps:
Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net
4
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures
1. Read one symbol at a time from the postfix expression and then scan the expression from left to right
manner.
2. Check whether the symbol is an operand or operator.
a. If the symbol is an operand, create a one - node tree and push a pointer on to the stack.
b. If the symbol is an operator pop two pointers from the stack namely T1 and T2 and form a new tree
with root as the operator and T2 as a left child and T1 as a right child. A pointer to this new tree is
then pushed onto the stack.
3. Repeated the above steps until reach the end of the expression.
4. The final pointer in the stack is complete expression tree.
Example:
ABC*+DE*F+G*+

BINARY SEARCH TREE OR SEARCH TREE ADT


Definition: -
When we place constraints on how data elements can be stored in the tree, the items must be stored

ww
in such a way that the key values in left subtree of the root less than the key value of the root, and then the
key values of all the node in the right subtree of the root are greater than the key values of the root. When

w.E
this relationship holds in the entire node in the tree then the tree is called as a binary search tree.
The property that makes a binary tree into a binary search tree. That is every node X in the tree, the
values of all the keys in its left subtree are smaller than the key value in X, and the values of all the keys in its

asy
right subtree are larger than the key value in X.
Example:

En
gin
eer
ing
.ne
Operations of BST.
1. Insertion
2. Deletion
t
3. Find
4. Find min
5. Find max
6. Retrieve

Notes: when you’re constructing the binary tree the given elements are read from first.
Example:

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


5
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures

ww
w.E
asy
En
struct treenode gin
{
int data; eer
struct treenode *left;
struct treenode *right; ing
};
Routine for perform find. .ne
struct treenode * find(struct treenode *T,int x)
{
t
if(T==NULL)
return NULL;
else if(x<T->data)
return find(T->left,x);
else if(x>T->data)
return find(T->right,x);
else
return T;
}
Routine for perform insertion.
struct treenode* insert(struct treenode *t,int x)
{
if(t==NULL)

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


6
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures
{
t=(struct treenode *)malloc(sizeof(struct treenode));
t->data=x;
t->left=t->right=NULL;
return t;
}
else if(x<t->data)
t->left=insert(t->left,x);
else if(x>t->data)
t->right=insert(t->right,x);
return t;
}

ww
w.E
asy
En
gin
eer
ing
.ne
t
Routine for perform deletion
struct treenode * findmin(struct treenode *t)
{
if(t==NULL)
return NULL; /* There is no element in the tree */
else if(t->left==NULL) /* Go to the left sub tree to find the min element */
return t;
else
return findmin(t->left);

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


7
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures
}

struct treenode* deletion(struct treenode *t,int x)


{
struct treenode *temp;
if(t==NULL)
printf("Element not found\n");
else if(x < t->data )
t->left = deletion (t->left,x);
else if(x > t->data )
t->right = deletion (t->right,x);
else if(T->right && T->left)
{
/* Here we will replace with minimum element in the right sub tree */
temp = findmin(t->right);

ww t->data = temp->data ;
/* As we replaced it with some other node, we have to delete that node */

}
else
w.E
t->right = deletion (t->right,t->data);

{
asy
/* If there is only one or zero children then we can directly remove it from the tree and connect its
parent to its child */
temp = T; En
if(t->left==NULL)
t = t->right; gin
else if(T->right == NULL)
t = t->left;
eer
}
return T;
free(temp); /* temp is longer required */
ing
}
.ne
void inorder(struct treenode *t)
{
if(t!=NULL)
t
{
inorder(t->left);
printf("%d \t",t->data);
inorder(t->right);
}
}
Applications of Tree
1. Manipulate hierarchical data.
2. Make information easy to search 3. Manipulate sorted lists of data.
4. As a workflow for compositing digital images for visual effects.
5. Router algorithms

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


8
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures
DIFFERENCE BETWEEN BINARY AND BINARY SEARCH TREES:

BINARY TREE BINARY SEARCH TREE

It is a tree with only two


It is also a tree with only two children.
children
It has no restrictions regarding In this the left child is lesser than the parent and the right
its children child is greater than the parent

THE DISJOINT SET ADT


A disjoint set data structure keeps note of a set of non-overlapping subsets. It is a data structure that
helps us solve the dynamic equivalence problem.
Various Representations Of Disjoint Set Adt
Array Representation
Linked List Representation

ww
w.E
asy
En
Array Representation
gin
Linked List Representation

Array Representation
eer
This representation assigns one position for each element. Each position stores the element and an index to

ing
the representative. To make the Find-Set operation fast we store the name of each equivalence class in the
array. Thus the find takes constant time, O(1). Assume element a belongs to set i and element b belongs to set
j. When we perform Union(a,b) all j’s have to be changed to i’s. Each union operation unfortunately takes Ɵ(n)
time. So for n-1 unions the time taken is Ɵ(n2 ).
Tree Representation .ne
A tree data structure can be used to represent a disjoint set ADT. Each set is represented by a tree. The
elements in the tree have the same root and hence the root is used to name the set.
Operations
t
1. Find
2. Union
The trees do not have to be binary since we only need a parent pointer.
Make-set (DISJ_SET S )
int i;
for( i = N; i > 0; i-- )
p[i] = 0;
Initially, after the Make-set operation, each set contains one element. The Make-set operation takes O(1)
time. set_type
Find-set( element_type x, DISJ_SET S )
if( p[x] <= 0 )
return x;
else

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


9
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures
return( find( p[x], S ) );
The Find-Set operation takes a time proportional to the depth of the tree. This is inefficient for an unbalanced
tree
void Union( DISJ_SET S, set_type root1, set_type root2 )
p[root2] = root1;
The union operation takes a constant time of O(1)

ww
w.E
asy
En
gin
eer
ing
.ne
t

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


10
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures

ww
w.E
asy
En
gin
eer
ing
.ne
t

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


11
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures

Graphs
Introduction to graphs
A graph is a data structure that is used to represent a relational data e.g. a set of terminal in network
or roadmap of all cities in a country. Such complex relationship can be represented using graph data structure.
A graph is a structure made of two components, a set of vertex V and the set of edges E. Therefore, a graph is
G= (V, E) where G is graph. The graph may be directed or undirected. Vertices are referred to as nodes and the
arc between the nodes are referred to as Edges.

ww
w.E
asy
Terms associated with graphs
1. Directed graph En
gin
A directed graph G is also called digraph which is the same as multigraph expect that each edges e in g is
assigned a direction or in other words each edge in G is identified with an order pair(U,V) of node in G
rather than an unordered pair
eer
2. Undirected graph

ing
An undirected graph g is a graph in which each edge e is not assigned a direction.

.ne
t

3. Connected graph
A graph is called connected if there is a path from any vertex to any other vertex.
Strongly Connected Graph If there is a path from every vertex to every other vertex in a directed graph
then it is said to be strongly connected graph. Otherwise, it is said to be weakly connected graph.
4. Multiple edges
5. Distinct edges e and e` are called multiple edges if they connected the same and point.

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


12
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures
Ex: e=(U,V) then e`=(U,V)
6. Loop
An edges e is called loop if it has identical and points.
E=(U,U)
7. Path
A path is a sequence of distinct vertices, each adjacent to the next. The length of such a path is number of
edges on that path.
8. Cycle
A path from a node to itself is called cycle. Thus, a cycle is a path in which the initial and final vertices are
same.
Acyclic Graph A directed graph which has no cycles is referred to as acyclic graph. It is abbreviated as DAG
[Directed Acyclic Graph]
Note: a graph need not be a tree but a tree must be graph
9. Degree, incidence and adjacent
A vertex V is incident to an edges e if V is one of the two vertices in the order pair of vertices that

ww
constitute e.
The degree of a vertex is the number of edges incident to it.

w.E
The indegree of vertex V is the number of edges that have V as head and the outdegree of vertex V is
number of edges that have v as the tail.
A vertex V is adjacent to vertex U if there is an edge from U to V. if V is adjacent to U,V is called a

asy
successor of U, and U a predecessor of V.
10. Weighted graph

En
A weighted graph is a graph in which edges are assigned weighted. Weights of an edge are called as cost.
11. complete graph

gin
If there is an edges from each vertices to all other vertices in graph is called as completed graph.
Graph and its representations
Graph is a data structure that consists of following two components:
1. A finite set of vertices also called as nodes. eer
ing
2. A finite set of ordered pair of the form (u, v) called as edge. The pair is ordered because (u, v) is not same as (v, u) in
case of directed graph(di-graph). The pair of form (u, v) indicates that there is an edge from vertex u to vertex v. The

.ne
edges may contain weight/value/cost.
Graphs are used to represent many real life applications: Graphs are used to represent networks. The networks
may include paths in a city or telephone network or circuit network. Graphs are also used in social networks like
linkedIn, facebook. For example, in facebook, each person is represented with a vertex (or node). Each node is a
structure and contains information like person id, name, gender and locale. See this for more applications of graph.
Following is an example undirected graph with 5 vertices.
t

Following two are the most commonly used representations of graph.


1. Adjacency Matrix
2. Adjacency List
There are other representations also like, Incidence Matrix and Incidence List. The choice of the graph representation is
situation specific. It totally depends on the type of operations to be performed and ease of use.
Adjacency Matrix:
Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let the 2D array be adj[][], a
Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net
13
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures
slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j. Adjacency matrix for undirected graph is always
symmetric. Adjacency Matrix is also used to represent weighted graphs. If adj[i][j] = w, then there is an edge from vertex
i to vertex j with weight w.
The adjacency matrix for the above example graph is:

Adjacency Matrix Representation of the above graph

ww
Pros: Representation is easier to implement and follow. Removing an edge takes O(1) time. Queries like whether there is
an edge from vertex ‘u’ to vertex ‘v’ are efficient and can be done O(1).

w.E
Cons: Consumes more space O(V^2). Even if the graph is sparse(contains less number of edges), it consumes the same
space. Adding a vertex is O(V^2) time.

Adjacency List:
asy
An array of linked lists is used. Size of the array is equal to number of vertices. Let the array be array[]. An entry array[i]

En
represents the linked list of vertices adjacent to the ith vertex. This representation can also be used to represent a
weighted graph. The weights of edges can be stored in nodes of linked lists. Following is adjacency list representation of

gin
the above graph.

eer
ing
.ne
Adjacency List Representation of the above Graph
t
Data Structure - Breadth First Traversal
Breadth First Search (BFS) algorithm traverses a graph in a breadthward motion and uses a queue to
remember to get the next vertex to start a search, when a dead end occurs in any iteration.

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


14
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures

ww
w.E
As in the example given above, BFS algorithm traverses from A to B to E to F first then to C and G lastly to D. It
employs the following rules.
asy


En
Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in a queue.
Rule 2 − If no adjacent vertex is found, remove the first vertex from the queue.

gin
Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.

eer
void BFS(int v1)
{
front=rear=-1;
for(int i = 0; i < n; i++)
visited[i] = 0; ing
visited[v1] = 1;
Q[++rear]=v1;
.ne
while(front!=rear())
{
v1 = Q[++front};
printf(“%d “, v1);
t
// Get all adjacent vertices of the dequeued vertex v1
// If a adjacent has not been visited, then mark it visited
// and enqueue it
for(int v2=0;v2<n;v2++)
{
if(g[v1][v2]==1&&visited[v2]==0)
{
visited[v2] = 1;
Q[++rear]=v2;
}
}
}
}

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


15
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures
Step Traversal Description

1. Initialize the queue.

ww
We start from visiting S (starting node), and mark
2.
it as visited.

w.E
asy
En We then see an unvisited adjacent node from S.
In this example, we have three nodes but
3.
gin
alphabetically we choose A, mark it as visited and
enqueue it.

eer
ing
.ne
4.
mark it as visited and enqueue it. t
Next, the unvisited adjacent node from S is B. We

Next, the unvisited adjacent node from S is C. We


5.
mark it as visited and enqueue it.

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


16
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures

Now, S is left with no unvisited adjacent nodes.


6.
So, we dequeue and find A.

From A we have D as unvisited adjacent node.


7.
We mark it as visited and enqueue it.

ww
w.E
asy
At this stage, we are left with no unmarked (unvisited) nodes. But as per the algorithm we keep on dequeuing
in order to get all unvisited nodes. When the queue gets emptied, the program is over.

Data Structure - Depth First Traversal En


gin
Depth First Search (DFS) algorithm traverses a graph in a depthward motion and uses a stack to remember to

eer
get the next vertex to start a search, when a dead end occurs in any iteration.

ing
.ne
t

As in the example given above, DFS algorithm traverses from A to B to C to D first then to E, then to F and
lastly to G. It employs the following rules.

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


17
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures
 Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a stack.
 Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack. (It will pop up all the vertices
from the stack, which do not have adjacent vertices.)
 Rule 3 − Repeat Rule 1 and Rule 2 until the stack is empty.

void dfs( Vertex v )


{
v.visited = true;
for each Vertex w adjacent to v if( !w.visited )
dfs( w );
}

Figure Template for depth-first search (pseudocode)

Step
ww Traversal Description

w.E
1.
asy Initialize the stack.

En
gin
eer
ing
Mark S as visited and put it onto the stack.
Explore any unvisited adjacent node from S. We
2.
.ne
have three nodes and we can pick any of them.
For this example, we shall take the node in an
alphabetical order.
t
Mark A as visited and put it onto the stack.
Explore any unvisited adjacent node from A. Both
3.
S and D are adjacent to A but we are concerned
for unvisited nodes only.

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


18
Downloaded From : www.EasyEngineering.net
EC8393 –Fundamentals of Data Structures in C | III sem ECE Unit IV–Non- Linear Structures

Visit D and mark it as visited and put onto the


stack. Here, we have B and C nodes, which are
4.
adjacent to D and both are unvisited. However,
we shall again choose in an alphabetical order.

We choose B, mark it as visited and put onto the


5.
ww stack. Here B does not have any unvisited
adjacent node. So, we pop B from the stack.

w.E
asy
En
6. gin
We check the stack top for return to the previous
node and check if it has any unvisited nodes.

eer
Here, we find D to be on the top of the stack.

ing
.ne
7.
t
Only unvisited adjacent node is from D is C now.
So we visit C, mark it as visited and put it onto the
stack.

As C does not have any unvisited adjacent node so we keep popping the stack until we find a node that has an
unvisited adjacent node. In this case, there's none and we keep popping until the stack is empty.

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


19
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V
UNIT V
SEARCHING and SORTING ALGORITHMS
Syllabus

Linear Search – Binary Search. Bubble Sort, Insertion sort – Merge sort – Quick sort – Hash tables – Overflow
handling.

SEARCHING

 Linear Search
 Binary Search

Linear Search
A linear search scans one item at a time, without jumping to any item.
#include<stdio.h>

ww
{
int main()

w.E
int a[20],n,x,i,flag=0;
printf("How many elements?");
scanf(“%d”,&n);

asy
printf("\nEnter elements of the array\n");
for(i=0;i<n; i++)
scanf(“%d”,&a[i]);

En
printf("\nEnter element to search:");
scanf(“%d”,&x);
for(i=0;i<n;i++)
{
gin
{
if(a[i]==x)
eer
flag=1;
break; ing
}
}
.ne
if(flag)

else
printf("\nElement is found at position %d ",i+1); t
printf("\nElement not found");
return 0;
}
The worst case complexity is O(n), sometimes known an O(n) search
Time taken to search elements keep increasing as the number of elements are increased.

Binary Search

A binary search however, cut down your search to half as soon as you find middle of a sorted list.

The middle element is looked to check if it is greater than or less than the value to be searched.Accordingly,
search is done to either half of the given list

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


1
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V
#include<stdio.h>

int main()
{
int n,i,a[100],f=0,l,h;
printf("Enter the no. of Elements:");
scanf(“%d”,&n);
printf("\nEnter Elements of Array in Ascending order\n");
for(i=0;i<n;++i)
{
scanf(“%d”,&a[i]);
}
printf("\nEnter element to search:");
scanf(“%d”,&e);
l=0;

ww
h=n-1;
while(l<=h)
{
w.E
m=(l+h)/2;
if(e==a[m])
{
f=1; asy
}
break;
En
else
if(e>a[m]) gin
l=m+1;
else
eer
}
h=m-1;
ing
.ne
if(f==1)
cout<<"\nElement found at position "<<m+1;
else

}
cout<<"\nElement is not found....!!!";
return 0; t
Differences

 Input data needs to be sorted in Binary Search and not in Linear Search
 Linear search does the sequential access whereas Binary search access data randomly.
 Time complexity of linear search -O(n) , Binary search has time complexity O(log n).
 Linear search performs equality comparisons and Binary search performs ordering comparisons

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


2
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V
SORTING
Sorting is linear ordering of list of items. Different types of sorting are

1. Bubble Sort
2. Insertion sort
3. Merge sort
4. Quick sort

BUBBLE SORT ALGORITHM

Bubble Sort is a simple algorithm which is used to sort a given set of n elements provided in form of an
array with n number of elements. Bubble Sort compares all the element one by one and sort them based on
their values.

ww
If the given array has to be sorted in ascending order, then bubble sort will start by comparing the first
element of the array with the second element, if the first element is greater than the second element, it
will swap both the elements, and then move on to compare the second and the third element, and so on. Th is

w.E
process will be repeated for n-1 times.(n- total elements)
It is known as bubble sort, because with every complete iteration the largest element in the given

asy
array, bubbles up towards the last place or the highest index, just like a water bubble rises up to the water
surface.

En
Sorting takes place by stepping through all the elements one-by-one and comparing it with the
adjacent element and swapping them if required.
Bubble Sort: gin
#include <stdio.h>
void bubbleSort(int arr[], int n) eer
{
int i, j, temp; ing
for(i = 0; i < n; i++)
{
.ne
for(j = 0; j < n-i-1; j++)
{
if( arr[j] > arr[j+1])
{
t
// swap the elements
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

// print the sorted array


printf("Sorted Array: ");
for(i = 0; i < n; i++)
{
printf("%d ", arr[i]);
Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net
3
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V
}
}

int main()
{
int arr[100], i, n, step, temp;
printf("Enter the number of elements to be sorted: ");
scanf("%d", &n);
for(i = 0; i < n; i++)
{
printf("Enter elements\n");
scanf("%d", &arr[i]);
}
// call the function bubbleSort
bubbleSort(arr, n);

ww
return 0;
}
w.E
Example: Let's consider an array with values {5, 1, 6, 2, 4, 3}

asy
En
gin
eer
ing
.ne
t

As shown above, after the first iteration, 6 is placed at the last index, which is the correct position for it.
Similarly after the second iteration, 5 will be at the second last index, and so on.

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


4
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V
INSERTION SORTING

1. It is a simple Sorting algorithm which sorts the array by shifting elements one by one. Following are
some of the important characteristics of Insertion Sort.
2. It has one of the simplest implementation
3. It is efficient for smaller data sets, but very inefficient for larger lists.
4. Insertion Sort is adaptive, that means it reduces its total number of steps if given a partially sorted list,
hence it increases its efficiency.
5. It is better than Selection Sort and Bubble Sort algorithms.
6. Its space complexity is less, like Bubble Sorting, insertion sort also requires a single additional memory
space.
7. It is Stable, as it does not change the relative order of elements with equal keys
How Insertion Sorting Works

ww
w.E
asy
En
gin
eer
ing
.ne
INSERTION SORT ROUTINE
t
void insert(int a[],int n)
{
int i,j,temp;
for(i=0;i<n;i++)
{
temp=a[i];
for(j=0;j>0&&a[j-1]>temp;j--)
a[j]=a[j-1];
a[j]=temp;
}
}

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


5
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V
Complexity Analysis of Insertion Sorting
Worst Case Time Complexity : O(n2)
Best Case Time Complexity : O(n)
Average Time Complexity : O(n2)
Space Complexity : O(1)

QUICK SORT ALGORITHM

Quick Sort, as the name suggests, sorts any list very quickly. Quick sort is not stable search, but it is very fast
and requires very less aditional space. It is based on the rule of Divide and Conquer(also called partition-
exchange sort). This algorithm divides the list into three main parts :

1. Elements less than the Pivot element


2. Pivot element
3.
ww
Elements greater than the pivot element

w.E
In the list of elements, mentioned in below example, we have taken 25 as pivot. So after the first pass, the list
will be changed like this.

6 8 17 14 25 63 37 52
asy
En
Hence after the first pass, pivot will be set at its position, with all the elements smaller to it on its left and all
the elements larger than it on the right. Now 6 8 17 14 and 63 37 52 are considered as two separate lists, and

gin
same logic is applied on them, and we keep doing this until the complete list is sorted.

eer
ing
.ne
t

How Quick Sorting Works

void qsort(int arr[], int left, int right)


{
int i,j,pivot,tmp;
if(left<right)

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


6
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V
{
pivot=left;
i=left+1;
j=right;
while(i<j)
{
while(arr[i]<=arr[pivot] && i<right)
i++;
while(arr[j]>arr[pivot])
j--;
if(i<j)
{
tmp=arr[i];
arr[i]=arr[j];
arr[j]=tmp;

}
}
ww
tmp=arr[pivot];
arr[pivot]=arr[j];
arr[j]=tmp;
w.E
qsort(arr,left,j-1);
qsort(arr,j+1,right); asy
}
}
En
gin
Complexity Analysis of Quick Sort
Worst Case Time Complexity : O(n2)
eer
Best Case Time Complexity : O(n log n)
Average Time Complexity : O(n log n)
ing
.ne
Space Complexity : O(n log n)

Space required by quick sort is very less, only O(n log n) additional space is required.

t
Quick sort is not a stable sorting technique, so it might change the occurence of two similar elements
in the list while sorting.

MERGE SORT ALGORITHM

Merge Sort follows the rule of Divide and Conquer. But it doesn't divides the list into two halves. In merge sort
the unsorted list is divided into N sublists, each having one element, because a list of one element is
considered sorted. Then, it repeatedly merge these sublists, to produce new sorted sublists, and at lasts one
sorted list is produced.

Merge Sort is quite fast, and has a time complexity of O(n log n). It is also a stable sort, which means the
"equal" elements are ordered in the same order in the sorted list.

How Merge Sort Works

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


7
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V

ww
w.E
asy
Like we can see in the above example, merge sort first breaks the unsorted list into sorted sublists, and then

En
keep merging these sublists, to finlly get the complete sorted list.

gin
Sorting using Merge Sort Algorithm
eer
#include<stdio.h>
#include<conio.h> ing
void merge(int [],int ,int ,int );
void part(int [],int ,int );
.ne
int main()
{
int arr[30];
int i,size;
t
printf("\n\t------- Merge sorting method -------\n\n");
printf("Enter total no. of elements : ");
scanf("%d",&size);
for(i=0; i<size; i++)
{
printf("Enter %d element : ",i+1);
scanf("%d",&arr[i]);
}
part(arr,0,size-1);
printf("\n\t------- Merge sorted elements -------\n\n");
for(i=0; i<size; i++)
printf("%d ",arr[i]);
getch();
Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net
8
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V
return 0;
}

void part(int arr[],int min,int max)


{
int mid;
if(min<max)
{
mid=(min+max)/2;
part(arr,min,mid);
part(arr,mid+1,max);
merge(arr,min,mid,max);
}
}

ww
void merge(int arr[],int min,int mid,int max)
{
int tmp[30];
int i,j,k,m;
i=min;
w.E
j=mid+1;k=0;
while(i<=mid && j<=max ) asy
{
if(arr[i]<=arr[j]) En
tmp[k++]=arr[i++];
else gin
}
tmp[k++]=arr[j++];
eer
while(i<=mid)
tmp[k++]=arr[i++];
ing
.ne
while(j<=max)
tmp[k++]=arr[j++];
for(k=min; k<=max; k++)

}
arr[k]=tmp[k];

Complexity Analysis of Merge Sort


t
Worst Case Time Complexity : O(n log n)
Best Case Time Complexity : O(n log n)
Average Time Complexity : O(n log n)
Space Complexity : O(n)

Time complexity of Merge Sort is O(n Log n) in all 3 cases (worst, average and best) as merge sort always
divides the array in two halves and take linear time to merge two halves.It requires equal amount of
additional space as the unsorted list. Hence its not at all recommended for searching large unsorted lists.It is
the best Sorting technique for sorting Linked Lists.

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


9
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V

HASHING
Hashing
Hashing is a process which uses a function to get the key and using the key it quickly identifies the
record, without much strain. The values returned by a hash function are called hash values. Hash table is data
structure in which key values are place in array location

Hash Table

The hash table data structure is an array of some fixed size, containing the keys. A key is a value associated

ww
with each record.

w.E
There are two types of hashing :
1. Static hashing: In static hashing, the hash function maps search-key values to a fixed set of
locations.

asy
2. Dynamic hashing: In dynamic hashing a hash table can grow to handle more items. The associated hash
function must change as the table grows.

En
A hash function, h, is a function which transforms a key from a set, K, into an index in a table of size n:
h: K -> {0, 1, ..., n-2, n-1}

gin
• A key can be a number, a string, a record etc.The size of the set of keys, |K|, to be relatively very large.
It is possible for different keys to hash to the same array location.This situation are called collision and


the colliding keys are called synonyms.
eer
A good hash function should:
· Minimize collisions.
ing
.ne
· Be easy and quick to compute.
· Distribute key values evenly in the hash table.
· Use all the information provided in the key.

Various types of Hash Functions:


Type 1: Truncation Method
t
Type 2: Folding Method
Type 3: Midsquare Method
Type 4: Division Method (Modulo Division)

1 Truncation Method
The Truncation Method truncates a part of the given keys, depending upon the size of the hash table.
1. Choose the hash table size.
2. Then the respective right most or left most digits are truncated and used as hash code| value.
Ex: 123,42,56 Table size = 9

H(123)=1
H(42)=4
H(56)=5

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


10
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V
0
1 123
2
3
4 42
5 56
6
7
8
9

2 Mid square Method :


It is a Hash Function method.
1. Square the given keys.

ww
2. Take the respective middle digits from each squared value and use that as the hash value | address | index
| code, for the respective keys.
H(123)=1 [ 1232 = 15129] 0
2
H(42)=7 [ 42 = 17 64 ]
2
H(56)=3 [ 56 = 3136 ] w.E 1
2
3
123

56

asy 4
5
6
7 En
42
8
9 gin
eer
3 Folding Method:
ing
Partition the key K into number of parts, like K1,K2,.....Kn, then add the parts together and ignore the
carry and use it as the hash
value. H(123)= [ 1+2+3 =6 ]
0 .ne
H(43)= [ 4+3 = 7 ]
H(56)= [ 5+6 = 11 ] 1
2
3
56
t
4
5
6 123
7 43

4 Division Method :
Choose a number m, larger than the number of keys. The number m is usually chosen to be a prime number.
The formula for the division method :
Hash(key)= key % tablesize
Tablesize : 10 20,21,24,26,32,34
H(20)= 20 % 10 = 0
H(21)= 21 % 10 = 1
H(24)=24 % 10 = 4
Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net
11
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V
H(26)= 26 % 10 = 6
H(32) = 32 % 10 = 2
H(34)=34%10=4 34 IS COLLISION

0 20
1 21
2 32
3
4 24
5
6 26
7 42
8
9

ww
Applications
• Database systems: Specifically, those that require efficient random access. Generally, database

w.E
systems try to optimize between two types of access methods: sequential and random. Hash tables are
an important part of efficient random access because they provide a way to locate data in a constant
amount of time.

asy
• Symbol tables: The tables used by compilers to maintain information about symbols from a program.
Compilers access information about symbols frequently. Therefore, it is important that symbol tables
be implemented very efficiently.
En
• Data dictionaries: Data structures that support adding, deleting, and searching for data. Although the

gin
operations of a hash table and a data dictionary are similar, other data structures may be used to
implement data dictionaries. Using a hash table is particularly efficient.

eer
• Network processing algorithms: Hash tables are fundamental components of several network
processing algorithms and applications, including route lookup, packet classification, and network
monitoring.
• Browser Cashes: Hash tables are used to implement browser cashes. ing
HASH COLLISION: .ne
produce identical outputs.

COLLISION RESOLUTION TECHNIQUES


t
A hash collision or hash clash is a situation that occurs when two distinct inputs into a hash function

The techniques are:

Closed Addressing
1. Separate Chaining.
Open Addressing
2. Linear Probing.
3. Quadratic Probing.
4. Double Hashing.
Dynamic Hashing
5. Rehashing.
6. Extendable Hashing.
7. Linear Hashing.
Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net
12
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V
1 Separate Chaining

It is to keep a list of all elements that hash to the same value. An alternative to open addressing as a method
of collision resolution is separate chaining hashing. This uses an array as the primary hash table, except that
the array is an array of lists of entries, each list initially being empty.
If in a set of elements, if an element hashes to the same value as that of an already inserted element then
we have a collision and We need to resolve it. In separate chaining ,each slot of the bucket array is a pointer to
a linked list that contains key-value pairs that are hashed to the same location. It is otherwise called as direct
chaining or simply chaining. An array of linked list implementation is used here.

ww
w.E
asy
En
gin
SEPARATE CHAINING PROCEDURE :
eer
TO FIND AN ELEMENT
ing
 To perform a Find, we use the hash function to determine which list to traverse.
 We then traverse it in normal manner, returning the position where the item is found. .ne
 Finding an element in separate chaining is very much similar to the find operation performed in the
case of lists.

If the ElementType is a string then a comparison and assignment must be done with strcmp and strcpy
t
respectively.
TO INSERT AN ELEMENT
 To perform an Insert, we traverse down the appropriate list to check whether the element is already in
place .
 If it is new then it is either inserted at the front or at the end.
 If the item to be inserted is already present, then we do not perform any operation; otherwise we
place it at the front of the list. It is similar to the insertion Operation that takes place in the case of
linked lists.
 The disadvantage is that it computes the hash function twice.

TO DELETE AN ELEMENT:
 To delete we find the cell P prior to the one containing the element to be deleted.

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


13
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V
 Make the cell P to point to the next cell of the element to be deleted.
 Then free the memory space of the element to be deleted.

PROGRAM
HEADER FILE FOR SEPARATE CHAINING
Typedef int elementtype;
Typedef struct listnode *position;
Typedef struct hashtbl *hashtable;
Typedef position list;
Struct hashtbl
{
int tablesize;
list *thelists;
};

ww
IMPLEMENTATION OF SEPARATE CHAINING
The Lists will be an array of list.
Struct listnode
{
Elementtype element;
w.E
Position next;
}; asy
Hashtable initialize table(int tablesize)
{ En
Hashtable H;
int i; gin
/ *Allocate Table * /
H=malloc(sizeof(struct hashtable));
eer
If(H==NULL)
Fatalerror(“Out of Space”);
H-->tablesize=nextprime(tablesize);
ing
/*Allocate array of list */
H-->thelist=malloc(sizeof(list)*H-->tablesize); .ne
If(H-->thelist==NULL)
Fatalerror(“Out of Space”);
/*Allocate list header */
t
For(i=0;i<H-->tablesize;i++)
{
H-->thelists[i]=malloc(sizeof(struct listnode));
If(H-->thelists[i]==NULL)
Fatalerror(“Out of Space”);
Else
H-->thelists[i]-->next=NULL;
}
return H;
}
Hash(char *key, int tablesize)
{
int hashvalue=0;

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


14
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V
while(*key!=’\0’)
hashvalue=hashvalue+ *key++;
return(hashvalue % tablesize);
}
Position find(Elementtype key, hashtable H)
{
Position P;
List L;
L=H-->thelists(Hash(key,H-->tablesize));
P=L-->next;
While(P!=NULL && P-->element ! =key)
P=P-->next;
Return P;
}
Void insert(elementtype key, hashtable H)
{
ww
Position pos,newcell;
List L;
Pos=find(key,H);
If(pos==NULL)
w.E
{
asy
Newcell=malloc(sizeof(struct listnode));
If(newcell==NULL)
Fatalerror(“Out of Space”); En
else
{ gin
L=H-->thelists(hash(key,H-->tablesize));
Newcell-->next=L-->next;
eer
Newcell-->element=key;
L-->next=Newcell;
ing
.ne
}
}
}

ADVANTAGES:
 Separate chaining is used when memory space is a concern.
t
 It can be very easily implemented.
DISADVANTAGES:
 It requires pointers which causes the algorithm to slow down a bit.
 Unevenly distributed keys-long lists-search time increases.
Open Addressing
In an open addressing hashing system, if a collision occurs, alternative cells are tried until an empty cell is
found.
A bigger table is needed for open addressing hashing, than for separate chaining.
Types of Open Addressing :
1. Linear Probing.
2. Quadratic Probing.
3. Double Hashing.

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


15
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V
Linear Probing
It is a kind of Open Addressing. In Linear probing, F is a linear function of i, typically F(i)=i. In linear probing, the
position in which a key can be stored is found by sequentially searching all positions starting from the position
calculated by the hash function until an empty cell is found.
If the end of the table is reached and no empty cell have been found, then the search is continued from the
beginning of the table. It has a tendency to create cluster in the table.
In linear probing we get primary clustering problem. Primary Clustering Problem
If the Hashtable becomes half full and if a collision occurs, it is difficult to find an empty location in the hash
table and hence an insertion or the deletion process takes a longer time.
Hash function
hi(key)=(Hash(key)+ F(i)) % Tablesize F(i)=i Hash(key)=key % tablesize
Ex: 89,18,49,58,69
-> Hashtable
0 49
1 58

ww 2
3
69

w.E 4
5
6

asy
7
8 18

1.Hash(89)=89 % 10=9
9
En
2.Hash(18)=18 % 10= 8
3.Hash(49)=49 % 10=9 -> collision occurs for first time i=1 gin
h1(49)= (9+1) % 10=10 % 10 =0
4.Hash(58)= 58 % 10 =8 -> collision occurs for first time i=1 eer
h1(58)= (8+1) % 10 =9 -> collision occurs for first time i=2
h2(58)= (8+2) % 10 =0 -> collision occurs for first time i=3 ing
h3(58)= (8+3) % 10 =1
5.Hash(69)=69%10=9 -> collision occurs for first time i=1 .ne
h1(69)= (9+1) % 10 =9 -> collision occurs for first time i=2
h2(69)= (9+2) % 10 =1 -> collision occurs for first time i=3
h3(69)= (9+3) % 10 =2
Advantage:
t
It does not require pointers.
Disadvantage:
It forms clusters, which degrades the performance of the hash table for storing and retrieving data.
Quadratic Probing
It is a kind of open addressing technique.It is a collision resolution method that eliminates the primary
clustering problem of linear probing.
-> Hash function
hi(key)=(Hash(key)+ F(i)) % Tablesize
F(i)=i2 Hash(key)=key % tablesize
-> Hashtable Ex: 89,18,49,58,69
0 49
1 58

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


16
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V
2 69
3
4
5
6
7 18
8 89
9

1.Hash(89)=89 % 10=9
2.Hash(18)=18 % 10= 8
3.Hash(49)=49 % 10=9 -> collision occurs for first time i=1
h1(49)= (9+12) % 10=10 % 10 =0
4.Hash(58)= 58 % 10 =8 -> collision occurs for first time i=1

ww
h1(58)= (8+12) % 10 =9 -> collision occurs for first time i=2
h2(58)= (8+22) % 10 =2
5.Hash(69)=69%10=9 -> collision occurs for first time i=1

h2(69)= (9+22) % 10 =3
Secondary Clustering:
w.E
h1(69)= (9+12) % 10 =9 -> collision occurs for first time i=2

asy
Elements that Hash to the same position will probe the same alternative cells. This is known as secondary clustering.
Double Hashing

En
Double hashing is a technique which belongs to open addressing. Open addressing is a collision resolution
technique which uses the concept of linked lists. Open addressing handles collision by trying out all the

gin
alternative cells until an empty cell is found. Collision is said to have occurred if there exists this situation.i.e.,
If an element inserted hashes to the same value as that of an already inserted element, then there is collision
PROCEDURE:
eer
 Compute the positions where the data elements are to be inserted by applying the first hash
function to it.
 Insert the elements if the positions are vacant. ing
 If there is collision then apply the second hash function.
 Add the two values and insert the element into the appropriate position. .ne
 Number of probes for the data element is 1 if it is inserted after calculating first hash function.
 Number of probes is 2 if it is inserted after calculating second hash function. t
DEFINITION:
It is a collision resolution technique which uses two hash functions to handle collision.
The interval (i.e., the distance it probes) is decided by the second hash function which is independent.

REQUIREMENTS:
The table size should be chosen in such a way that it is prime so that all the cells can be inserted. The second
hash function should be chosen in such a way that the function does not evaluate to zero.i.e., 1 can be added
to the hash function(non-zero). To overcome secondary clustering, double hashing is used. The collision
function is,
hi(key)=(Hash(key)+ F(i)) % Tablesize
F(i) = i * hash2 (X)
Where hash2(X) = R – (X % R) R is a prime number. It should be smaller than the tablesize
Example 1 :

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


17
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V
89, 18, 49, 58, 69,60
0 69
1
2 60
3 58
4
5
6 49
7 18
8 89
9

49
h0(49)=9

58
ww
h1(49) = (9+(1*7)) % 10 = (9+7) % 10 = 16 % 10 = 6

7 – (58 % 7) = 7 – 2 = 5
i=1
w.E
h1(58) = (8+(1*5)) % 10 = 13 % 10 = 3
69
7 – (69 % 7) = 7 – 6 = 1
h1(69) = (9+1) % 10 = 10 % 10 = 0 asy
60
7 – (60 % 7) = 7 – 4 = 3 En
h1(60) = (0+1*3) % 10 = 3
h2(60) = (0+2*3) % 10 = 6 gin
h3(60) = (0+9) % 10 = 9
h4(60)=(0+12)%10=2 eer
APPLICATIONS: ing
 It is used in caches.
 It is used in finding duplicate records. .ne
 Used in finding similar records.
 Finding similar substrings. t
ADVANTAGES:
 No index storage is required.
 It provides rapid updates.

DISADVANTAGES:
 Problem arises when the keys are too small.
 There is no sequential retrieval of keys.
 Insertion is more random.

Re-Hashing:
It is a technique in which the table is re-sized i.e., the size of the table is doubled by creating a new table.
Rehashing is a technique that is used to improve the efficiency of the closed hashing techniques. This can be
done by reducing the running time. If the table gets too full, the running time for the operations will start

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


18
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V
taking too long and inserts might fail for closed hashing with quadratic resolution. This can happen if there are
too many deletions intermixed with insertions. A solution, then, is to build another table that is about twice as
big (with associated new hash function) and scan down the entire original hash table, computing the new hash
value for each (non-deleted) element and inserting it in the new tableRe-Hashing is required when, The table
is completely filled in the case of double-Hashing
The table is half-filled in the case of quadratic and linear probing
The insertion fails due to overflow.
IMPLEMENTATION:
Rehashing can be implemented in
1.Linear probing
2.Double hashing
3.Quadratic probing
 Rehashing can be implemented in several ways with quadratic probing.
 One alternative is to rehash as soon as the table is half full.
 The other extreme is to rehash only when an insertion fails.

ww
 A third, middle of the road, strategy is to rehash when the table reaches a certain load factor.Since
performance does degrade as the load factor increases, the third strategy, implemented with a good

w.E
cutoff, could be best.

Problems:

1. According to linear probing, asy


13, 15, 6, 24, 23 En
0 6 gin
1
2
15
23 eer
3
4
24
ing
5
6 13 .ne
Rehashing
Size=7 double size=14 next prime =17
t
1. 16 % 17 = 6
2. 15 % 17 = 15
3. 23 % 17 = 6
h1(X) = 6 + 1 % 17 = 7
4. 24 % 17 = 7
h1(24) = 7 + 1 % 17 = 8
5. 13 % 17 = 13

0
1
2
3
4
Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net
19
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V
5
6 16
7 23
8 24
9
10
11
12
13 13
14
15 15
16

Advantage:

ww
This technique provides the programmer the flexibility to enlarge the table size if required.
Disadvantages:
Transfer time is more.

Extensible Hashing w.E


Hashing technique for huge data sets asy
– optimizes to reduce disk accesses

En
– each hash bucket fits on one disk block
– better than B-Trees if order is not important
– Table contains
gin
 buckets, each fitting in one disk block, with the data

eer
 a directory that fits in one disk block used to hash to the correct bucket
• Directory - entries labeled by k bits & pointer to bucket with all keys starting with its bits
• Each block contains keys & data matching on the first j  k bits
ing
.ne
• insert(10010)
t

directory for k = 3

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


20
Downloaded From : www.EasyEngineering.net
EC8393–Fundamentals of Data Structures in C | IIIsem ECE UNIT V

insert(11011)

ww
w.E
asy
En
gin
eer
1. Advantages:
o Extendable hashing provides performance that does not degrade as the file grows.
o Minimal space overhead - no buckets need be reserved for future use. Bucket address table only
contains one pointer for each hash value of current prefix length.
2. Disadvantages: ing
o Extra level of indirection in the bucket address table
o Added complexity
.ne
t

Mrs.D.Praveena & Dr.S.Thanga Ramya AP - IT | EASYENGINEERING.NET Downloaded From : www.EasyEngineering.net


21

You might also like