Esoft Metro Campus - Certificate in java basics
(Template - Virtusa Corporate)
Contents:
Structure of a program
Variables & Data types
Constants
Operators
Basic Input/output
Control Structures
Functions
Arrays
Character Sequences
Pointers and Dynamic Memory
Unions
Other Data Types
Input/output with files
Searching
Sorting
Introduction to data structures
Esoft Metro Campus - Certificate in c / c++ programming
1. Certificate in C/C++ Programming
Rasan Samarasinghe
ESOFT Computer Studies (pvt) Ltd.
No 68/1, Main Street, Pallegama, Embilipitiya.
2. Programme Structure
1. Structure of a program
2. Variables & Data types
3. Constants
4. Operators
5. Basic Input/output
6. Control Structures
7. Functions
8. Arrays
9. Character Sequences
10. Pointers and Dynamic Memory
11. Unions
12. Other Data Types
13. Input/output with files
14. Searching
15. Sorting
16. Introduction to data structures
3. C Language Overview
• A general purpose language.
• Originally developed by Dennis M. Ritchie to
develop Unix operating system.
• It is a structured programming language.
• It can handle low level activities.
• It produces efficient programs.
• It can be compiled on variety of platforms.
• A widely used System Programming Language.
4. What you can create with C?
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modem Programs
• Databases
• Language Interpreters
• Utilities
5. What you need to program with C
• C/C++ Compiler
• Text Editor
• Command Prompt
7. C Hello World Example
#include <stdio.h>
int main()
{
printf("Hello world!");
return 0;
}
main.c
8. C Hello World Example
A C program basically consists of:
• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
• Comments
9. Tokens in C
#include <stdio.h>
int main()
{
printf("Hello world!");
return 0;
}
A program consists of tokens is either a keyword, an identifier,
a string literal, a constant or a symbol
12. Comments
Helping text in your program and ignored by the
compiler
//this is a single line comment
/* This is
a multiline
comment */
13. Identifiers
An identifier is a name used to identify a
variable, function or any other user defined item
• Starts with a letter a to z or A to Z or _.
• Followed by zero or more letters, underscores
and digits.
• Does not allow any symbols and spaces.
• Case sensitive.
40. getchar() function
int getchar(void) function reads the next
available character from the screen and returns
it as an integer.
int c;
printf("Enter a value :");
c = getchar();
41. putchar() function
int putchar(int c) function puts the passed
character on the screen and returns the same
character.
printf( "You entered: ");
putchar(c);
42. gets() function
char *gets(char *s) function reads a line from
stdin into the buffer pointed to by s until either
a terminating newline or EOF.
char str[100];
printf("Enter a value :");
gets(str);
43. puts() function
int puts(const char *s) function writes the string
s and a trailing newline to stdout.
printf("You entered: ");
puts(str);
44. scanf() function
int scanf(const char *format, ...) function reads
input from the standard input stream stdin and
scans that input according to format provided.
char str[100];
int i;
printf("Enter a value :");
scanf("%s %d", str, &i);
45. printf() function
int printf(const char *format, ...) function writes
output to the standard output stream stdout
and produces output according to a format
provided.
printf( "nYou entered: %s, %d ", str, i);
49. If… Else if… Else Statement
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition
is true.
}
53. The ? : Operator
Exp1 ? Exp2 : Exp3;
Exp1 is evaluated. If it is true, then Exp2 is
evaluated and becomes the value of the entire
expression.
If Exp1 is false, then Exp3 is evaluated and its
value becomes the value of the expression.
63. Example
int max(int num1, int num2)
{
int result;
if (num1 > num2){
result = num1;
}else{
result = num2;
}
return result;
}
64. Function Declarations
A function declaration tells the compiler about
a function name and how to call the function.
return_type function_name( parameter list );
Ex:
int max(int num1, int num2);
int max(int, int);
65. Calling a Function
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
67. Function call by value
passing arguments to a function copies the
actual value of an argument into the formal
parameter of the function.
68. Function call by value
void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
return;
}
69. Function call by value
#include <stdio.h>
void swap(int x, int y);
int main () {
int a = 100, b = 200;
printf("Before swap, value of a : %dn", a );
printf("Before swap, value of b : %dn", b );
swap(a, b);
printf("After swap, value of a : %dn", a );
printf("After swap, value of b : %dn", b );
return 0;
}
70. Function call by reference
passing arguments to a function copies the
address of an argument into the formal
parameter.
71. Function call by reference
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
return;
}
72. Function call by reference
#include <stdio.h>
void swap(int *x, int *y);
int main ()
{
int a = 100;
int b = 200;
printf("Before swap, value of a : %dn", a );
printf("Before swap, value of b : %dn", b );
swap(&a, &b);
printf("After swap, value of a : %dn", a );
printf("After swap, value of b : %dn", b );
return 0;
}
74. Arrays
• An Array is a data structure which can store a
fixed size sequential collection of elements of
the same type.
• An array is used to store a collection of data.
77. Initializing Arrays
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
If you omit the size of the array, an array just big
enough to hold the initialization is created.
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
79. Multi-dimensional Arrays
C programming language allows multidimensional
arrays.
Here is the general form of a multidimensional
array declaration:
type name[size1][size2]...[sizeN];
83. Accessing Two-Dimensional Array Elements
An element in two dimensional array is accessed
by using row index and column index of the
array.
int val = a[2][3];
84. Passing Arrays as Function Arguments
Formal parameters as a pointer
void myFunction(int *param) { }
Formal parameters as a sized array
void myFunction(int param[10]) { }
Formal parameters as an unsized array
void myFunction(int param[]) { }
85. Return array from function
int * myFunction()
{
static int demo[5] = {20, 40, 50, 10, 60};
return demo;
}
86. Pointer to an Array
double balance[5] = {20.50, 65.00, 35.75, 74.25, 60.00};
double *ptr;
ptr = balance;
int i;
printf("Array values using pointern");
for(i=0; i<=4; i++){
printf("balance[%d] = %.2f n", i, *(ptr+i));
}
printf("Array values using balancen");
for(i=0; i<=4; i++){
printf("balance[%d] = %.2f n", i, *(balance+i));
}
88. C Strings
The string in C programming language is actually
a one-dimensional array of characters which is
terminated by a null character '0'.
89. C Strings
The following declaration and initialization
create a string consisting of the word "Hello“
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'};
Using array initializer
char greeting[] = "Hello";
92. Variable Address
every variable is a memory location and every
memory location has its address defined which
can be accessed using ampersand (&) operator.
int var1;
char var2[10];
printf("Address of var1 variable: %xn", &var1 );
printf("Address of var2 variable: %xn", &var2 );
93. What Are Pointers?
A pointer is a variable whose value is the address
of another variable.
pointer variable declaration:
type *var-name;
95. What Are Pointers?
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to a character
96. How to use Pointers?
1. Define a pointer variable.
2. Assign the address of a variable to a pointer.
3. Access the value at the address available in
the pointer variable.
97. How to use Pointers?
int var = 20;
int *ip;
ip = &var;
printf("Address of var variable: %xn", &var );
printf("Address stored in ip variable: %xn", ip );
printf("Value of *ip variable: %dn", *ip );
98. NULL Pointers in C
int *ptr = NULL;
printf("The value of ptr is : %xn", &ptr );
99. Incrementing a Pointer
int var[] = {10, 100, 200};
int i, *ptr;
ptr = var;
for ( i = 0; i <= 2; i++)
{
printf("Address of var[%d] = %xn", i, ptr );
printf("Value of var[%d] = %dn", i, *ptr );
ptr++;
}
100. Decrementing a Pointer
int var[] = {10, 100, 200};
int i, *ptr;
ptr = &var[2];
for ( i = 2; i > 0; i--)
{
printf("Address of var[%d] = %xn", i, ptr );
printf("Value of var[%d] = %dn", i, *ptr );
ptr--;
}
101. Pointer Comparisons
int var[] = {10, 100, 200};
int i, *ptr;
ptr = var;
i = 0;
while ( ptr <= &var[2] )
{
printf("Address of var[%d] = %xn", i, ptr );
printf("Value of var[%d] = %dn", i, *ptr );
ptr++;
i++;
}
102. Array of pointers
int var[] = {10, 100, 200};
int i, *ptr[3];
for ( i = 0; i <= 2; i++)
{
ptr[i] = &var[i];
}
for ( i = 0; i < 2; i++)
{
printf("Value of var[%d] = %dn", i, *ptr[i] );
}
103. Pointer to Pointer
When we define a pointer to a pointer, the first
pointer contains the address of the second
pointer.
104. Pointer to Pointer
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var;
pptr = &ptr;
printf("Value of var = %dn", var );
printf("Value available at *ptr = %dn", *ptr );
printf("Value available at **pptr = %dn", **pptr);
105. Passing pointers to functions
void getSeconds(long *hours)
{
*hours = *hours * 60 * 60;
return;
}
int main ()
{
long hours;
getSeconds( &hours );
printf("Number of seconds: %dn", hours );
return 0;
}
106. Return pointer from functions
int * getNumber( )
{
static int r[5] = {20, 40, 50, 10, 60};
return r;
}
int main ()
{
int *p;
int i;
p = getNumber();
for ( i = 0; i < 5; i++ )
{
printf("*(p + [%d]) : %dn", i, *(p + i) );
}
return 0;
}
107. Memory Management
• C language provides several functions for memory
allocation and management.
• These functions can be found in the <stdlib.h> header file.
108. Allocating Memory Dynamically
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char *description;
description = malloc(100 * sizeof(char)); // allocating memory dynamically
if(description == NULL){
printf("unable to allocate required memoryn");
}else{
strcpy(description, "my name is khan");
}
printf("description = %s", description);
return 0;
}
109. Resizing and Releasing Memory
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char *description;
description = malloc(10 * sizeof(char)); // allocating memory dynamically
description = realloc( description, 100 * sizeof(char) ); // resizing memory
if(description == NULL){
printf("unable to allocate required memoryn");
}else{
strcpy(description, "my name is khan, and i'm not a terrorist");
}
printf("description = %s", description);
free(description); // releasing memory
return 0;
}
111. Unions
• A union is a special data type available in C
that enables you to store different data types
in the same memory location.
• You can define a union with many members,
but only one member can contain a value at
any given time.
• Unions provide an efficient way of using the
same memory location for multipurpose.
112. Defining a Union
union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
113. Defining a Union
union Data
{
int i;
float f;
char str[20];
} data;
• You can specify one or more union variables but it is
optional.
• The union tag is optional when there are union variable
definition.
114. Assigning values to Union
data.i = 10;
data.f = 220.5;
strcpy( data.str, “Hello world”);
115. Accessing Union Members
union Data data;
printf( "Memory size occupied by data : %dn",
sizeof(data));
printf( "data.i : %dn", data.i);
printf( "data.f : %fn", data.f);
printf( "data.str : %sn", data.str);
117. Structures
• Structure is another user defined data type
which allows you to combine data items of
different kinds.
• Structures are used to represent a record.
118. Defining a Structure
struct [structure tag]
{
member definition;
member definition;
...
member definition;
} [one or more structure variables];
119. Defining a Structure
struct Books
{
char title[50];
char author[50];
char category[100];
int book_id;
} book;
• You can specify one or more structure variables but it is
optional.
• The structure tag is optional when there are structure
variable definition.
120. Assigning values to Structure
struct Books Book1; /* Declare Book1 of type
Book */
strcpy( Book1.title, “Tom Sawyer”);
strcpy( Book1.author, “Mark Twain”);
strcpy( Book1.category, “Novel”);
Book1.book_id = 64954;
122. Structures as Function Arguments
// function definition
void printBook( struct Books book )
{
printf( "Book title : %sn", book.title);
printf( "Book author : %sn", book.author);
printf( "Book category : %sn", book.category);
printf( "Book book_id : %dn", book.book_id);
}
// calling function
printBook( Book1 );
123. Pointers to Structures
//define pointer to structure
struct Books *struct_pointer;
//store the address of a structure variable in the pointer
struct_pointer = &Book1;
//access the members of a structure
struct_pointer->title;
124. Bit Fields
Bit fields offers a better way to utilize the memory
space occupied by a Structure.
125. Bit Field Declaration
struct
{
type [member_name] : width ;
};
• Width is the number of bits in the bit-field.
• The width must be less than or equal to the
bit width of the specified type.
126. Bit Field example
struct
{
unsigned int widthValidated;
unsigned int heightValidated;
} status1;
struct
{
unsigned int widthValidated : 1;
unsigned int heightValidated : 1;
} status2;
printf( "Memory size occupied by status : %dn", sizeof(status));
printf( "Memory size occupied by status2 : %dn", sizeof(status2));
131. Writing a File
// write individual characters to a stream
int fputc( int c, FILE *fp );
// writes the string s to the output stream
referenced by fp
int fputs( const char *s, FILE *fp );
132. Reading a File
// read a single character from a file
int fgetc( FILE * fp );
// reads up to n - 1 characters from the input stream
referenced by fp
char *fgets( char *buf, int n, FILE *fp );
// scans a file according to format provided.
int fscanf(FILE *fp, const char *format, ...)
136. Linear Search
int size = 6;
int points[6] = {20, 50, 30, 60, 10, 80};
int key = 60;
int i;
for(i = 0; i <= size-1; i++){
if(points[i] == key){
printf("Value found at index %d", i);
break;
}
}
if(i == size){
printf("Value not found");
}
137. Binary Search
Binary search is an efficient algorithm for finding
an item from an ordered list of items.
It works by repeatedly dividing in half the portion
of the list that could contain the item, until you've
narrowed down the possible locations to just one.
138. Binary Search
int size = 6;
int points[6] = {10, 20, 30, 40, 50, 60};
int key = 20;
int low = 0, high = size-1;
while(high>=low){
int mid = (low+high)/2;
if(key < points[mid]){
high = mid-1;
}else if(key > points[mid]){
low = mid+1;
}else{
printf("Value found at index %d", mid);
break;
}
}
if(low>high){
printf("Value not found");
}
146. Insertion Sort C Implementation
int abc[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
int c, i, index;
for (c = 1; c <= 8; c++){
index = abc[c];
for (i = c; ((abc[i - 1] > index) && (i>0)); i--){
abc[i] = abc[i - 1];
}
abc[i] = index;
}
147. Comparison of Sorting Algorithms
Bubble Sort Selection Sort Insertion Sort
Data structure Array Array Array
Worst case
performance
O(n2) О(n2) О(n2)
Best case
performance
O(n) О(n2) O(n)
Average case
performance
O(n2) О(n2) О(n2)
Worst case space
complexity
O(1) auxiliary О(n) total, O(1)
auxiliary
О(n) total, O(1)
auxiliary
Comparison Exchange two adjacent
elements if they are out
of order. Repeat until
array is sorted. This is a
slow algorithm.
Find the largest
element in the array,
and put it in the
proper place. Repeat
until array is sorted.
This is also slow.
Scan successive
elements for out of
order item, and then
insert the item in the
proper place. Sort
small array fast, big
array very slowly.
149. An introduction to Data Structures
In computer science, a data structure is a
particular way of organizing data in a computer
so that it can be used efficiently.
150. An introduction to Data Structures
Organized Data + Operations = Data Structure
Algorithm + Data Structure = Computer Program
153. Stack
• A stack is a data structure in which all the
access is restricted to the most recently
inserted item.
• If we remove this item, then we can access the
next to last item inserted, and etc.
• Stack is a first in last out data structure.
154. Operations on Stack
• PUSH: The process of inserting a new element
to the top of the stack.
• POP: The process of deleting an element from
the top of stack
156. Algorithm for push
1. If TOP = SIZE – 1, then:
a) Display “The stack is in overflow condition”
b) Exit
2. TOP = TOP + 1
3. STACK [TOP] = ITEM
4. Exit
157. Algorithm for pop
1. If TOP < 0, then
a) Display “The Stack is empty”
b) Exit
2. Else remove the Top most element
3. DATA = STACK[TOP]
4. TOP = TOP – 1
5. Exit
158. Queue
• Queue is a linear data structure that add data
items to the rear of it and remove from the
front.
• Queue is a first in first out data structure.
159. Operations on Queue
• PUSH: Insert an element to the queue
• POP: Delete an element from a queue
163. Algorithm for push
1. Initialize front=0 rear = –1
2. Input the value to be inserted and assign to
variable “data”
3. If (rear >= SIZE)
a) Display “Queue overflow”
b) Exit
4. Else
a) Rear = rear +1
5. Q[rear] = data
6. Exit
164. Algorithm for pop
1. If (rear< front)
a) Front = 0, rear = –1
b) Display “The queue is empty”
c) Exit
2. Else
a) Data = Q[front]
3. Front = front +1
4. Exit
165. Limitations in Queue
Suppose a queue Q has maximum size 5, say 5
elements pushed and 2 elements popped.
Even though 2 queue cells are free, new
elements cannot be pushed.
166. Circular Queue
• In circular queues the elements Q[0],Q[1],Q[2]
.... Q[n – 1] is represented in a circular fashion.
• In a circular queue push and pop operation
can be performed on circular.
170. Algorithm for push in Circular Queue
1. Initialize FRONT = – 1; REAR = 1
2. REAR = (REAR + 1) % SIZE
3. If (FRONT is equal to REAR)
a) Display “Queue is full”
b) Exit
4. Else
a) Input the value to be inserted and assign to variable
“DATA”
5. If (FRONT is equal to – 1)
a) FRONT = 0
b) REAR = 0
6. Q[REAR] = DATA
7. Repeat steps 2 to 5 if we want to insert more
elements
8. Exit
171. Algorithm for pop in Circular Queue
1. If (FRONT is equal to – 1)
a) Display “Queue is empty”
b) Exit
2. Else
a) DATA = Q[FRONT]
3. If (REAR is equal to FRONT)
a) FRONT = –1
b) REAR = –1
4. Else
a) FRONT = (FRONT +1) % SIZE
5. Repeat the steps 1, 2 and 3 if we want to delete more
elements
6. Exit
172. Linked List
• A linked list is a collection of specially
designed data elements called nodes storing
data and linked to other nodes.
175. Advantages of Linked List
• Linked list are dynamic data structure. They
can grow or shrink during the execution of a
program.
• Efficient memory utilization. Memory is not
pre allocated. Memory is allocated whenever
it is required. And it is de allocated when it is
not needed.
• Insertion and deletion are easier and efficient.
176. Operations on Linked List
• Creation - linked list is created with one node
• Insertion
– At the beginning of the linked list
– At the end of the linked list
– At any specified position
• Deletion
– Beginning of a linked list
– End of a linked list
– Specified location of the linked list
177. Operations on Linked List
• Traversing - process of going through all the
nodes from one end to another end.
• Searching - Search for a node
• Concatenation - process of appending the
second list to the end of the first list.
181. Insert a Node at the beginning
1. Input DATA to be inserted
2. Create a NewNode
3. NewNode → DATA = DATA
4. If (SATRT equal to NULL)
a) NewNode → Link = NULL
5. Else
a) NewNode → Link = START
6. START = NewNode
7. Exit
182. Insert a Node at the end
1. Input DATA to be inserted
2. Create a NewNode
3. NewNode → DATA = DATA
4. NewNode → Next = NULL
5. If (SATRT equal to NULL)
a) START = NewNode
6. Else
a) TEMP = START
b) While (TEMP → Next not equal to NULL)
i. TEMP = TEMP → Next
c) TEMP → Next = NewNode
7. Exit
183. Insert a Node at any specified position
1. Input DATA and POS to be inserted
2. Initialize TEMP = START; and k = 0
3. Repeat the step 3 while( k is less than POS)
a) TEMP = TEMP Next
b) If (TEMP is equal to NULL)
i. Display “Node in the list less than the position”
ii. Exit
c) k = k + 1
4. Create a New Node
5. NewNode → DATA = DATA
6. NewNode → Next = TEMP → Next
7. TEMP → Next = NewNode
8. Exit
185. Algorithm for deleting a node
1. Input the DATA to be deleted
2. if ((START → DATA) is equal to DATA)
a) TEMP = START
b) START = START → Next
c) Set free the node TEMP, which is deleted
d) Exit
3. HOLD = START
4. while ((HOLD → Next → Next) not equal to NULL))
a) if ((HOLD → NEXT → DATA) equal to DATA)
I. TEMP = HOLD → Next
II. HOLD → Next = TEMP → Next
III. Set free the node TEMP, which is deleted
IV. Exit
b) HOLD = HOLD → Next
5. if ((HOLD → next → DATA) == DATA)
a) TEMP = HOLD → Next
b) Set free the node TEMP, which is deleted
c) HOLD → Next = NULL
d) Exit
6. Display “DATA not found”
7. Exit
186. Algorithm for searching a node
1. Input the DATA to be searched
2. Initialize TEMP = START; POS =1;
3. Repeat the step 4, 5 and 6 until (TEMP is equal
to NULL)
4. If (TEMP → DATA is equal to DATA)
a) Display “The data is found at POS”
b) Exit
5. TEMP = TEMP → Next
6. POS = POS+1
7. If (TEMP is equal to NULL)
a) Display “The data is not found in the list”
8. Exit
187. Algorithm for display all nodes
1. If (START is equal to NULL)
a) Display “The list is Empty”
b) Exit
2. Initialize TEMP = START
3. Repeat the step 4 and 5 until (TEMP == NULL )
4. Display “TEMP → DATA”
5. TEMP = TEMP → Next
6. Exit
188. Tree
• Tree is a non-liner data structure.
• Used to represent data items possessing
hierarchical relationship.
• Very flexible, versatile and powerful.
190. Basic Terminologies
• Root - First node in the hierarchical arrangement
• Degree of a node - Number of sub trees of a node
• Degree of a tree - Maximum degree of a node in
a tree
• Levels - Root node is level 0. Rest are 1, 2, 3 and
so on
• Depth of a tree - Maximum height of a tree
• Leaf node - Node has no child
191. Binary Tree
• Tree data structure in which each node has at
most two child nodes.
• It is possible to having one node as the child
or nothing.
• Child nodes are defined as Left and Right.
195. Left skewed and Right skewed Trees
Left Skewed Tree Right Skewed Tree
196. Complete binary tree
• A complete binary tree is a strictly binary tree,
where all the leaves are at same level.
• A binary tree of depth d, and d > 0, has 2d - 1
nodes in it.
202. Array representation
Since there is no
left child for node C
is vacant. Even
though memory is
allocated for A[5] it
is not used, so
wasted
unnecessarily.
203. Linked list representation
In linked list, every element is represented as
nodes. A node consists of three fields such as :
• Left Child (LChild)
• Information of the Node (Info)
• Right Child (RChild)
205. Operations on Binary Tree
• Create an empty binary tree
• Traversing binary tree
• Inserting an new node
• Deleting a node
• Searching for a node
• Copying the mirror image of a tree
• Determining total no: of nodes
• Determine the total no: non-leaf Nodes
• Find the smallest element in a Node
• Finding the largest element
• Find the Height of the tree
• Finding the Father/Left Child/Right Child/Brother of an
arbitrary node
206. Traversing binary tree
1. Pre Order Traversal (Node-left-right)
2. In order Traversal (Left-node-right)
3. Post Order Traversal (Left-right-node)
207. Pre Order Traversal
1. Visit the root node
2. Traverse the left sub tree in preorder
3. Traverse the right sub tree in preorder
215. Post Order Traversal recursively
void postorder (NODE *Root)
{
If (Root != NULL)
{
postorder(Root → Lchild);
postorder(Root → Rchild);
printf (“%dn”,Root info);
}
}
216. Binary Search Tree
A Binary Search tree satisfies the following
properties
• Every node has a value and all the values are
unique.
• Left child or left sub tree value is less than the
value of the root.
• Right child or right sub tree value is larger than
the value of the root.
219. Algorithm for inserting a node to BST
1. Input the DATA to be pushed and ROOT node of the tree.
2. NEWNODE = Create a New Node.
3. If (ROOT == NULL)
a) ROOT=NEW NODE
4. Else If (DATA < ROOT → Info)
a) ROOT = ROOT → Lchild
b) GoTo Step 4
5. Else If (DATA > ROOT → Info)
a) ROOT = ROOT → Rchild
b) GoTo Step 4
6. If (DATA < ROOT → Info)
a) ROOT → LChild = NEWNODE
7. Else If (DATA > ROOT → Info)
a) ROOT → RChild = NEWNODE
8. Else
a) Display (“DUPLICATE NODE”)
b) EXIT
9. NEW NODE → Info = DATA
10. NEW NODE → LChild = NULL
11. NEW NODE → RChild = NULL
12. EXIT
220. Algorithm for searching a node in BST
1. Input the DATA to be searched and assign the address of
the root node to ROOT.
2. If (DATA == ROOT → Info)
a) Display “The DATA exist in the tree”
b) GoTo Step 6
3. If (ROOT == NULL)
a) Display “The DATA does not exist”
b) GoTo Step 6
4. If(DATA > ROOT→Info)
a) ROOT = ROOT→RChild
b) GoTo Step 2
5. If(DATA < ROOT→Info)
a) ROOT = ROOT→Lchild
b) GoTo Step 2
6. Exit
221. Deleting a node on BST
Special cases
• The node to be deleted has no children
• The node has exactly one child
• The node has two children
222. The node to be deleted has no children
If N has no children then simply delete the node
and place its parent node by the NULL pointer.
223. The node to be deleted has no children
5
3 18
41
5
3 18
4
1 2
224. The node has exactly one child
1. If it is a right child, then find the smallest
element from the corresponding right sub
tree.
2. Then replace the smallest node information
with the deleted node.
3. If N has a left child, find the largest element
from the corresponding left sub tree.
4. Then replace the largest node information
with the deleted node.
225. The node has exactly one child
5
2 18
3-4 21
19 25
5
2 18
3-4 21
19 25
1 2
3
5
2 19
3-4 21
25
226. The node has two children
1. Use the in order successor of the node to be
deleted. In order successor is the left most
child of it’s right sub tree.
2. Then in order successor replace the node
value and then node is deleted.
3. Else if no right sub tree exist, replace the
node to be deleted with it’s left child.
227. The node has two children
5
2
3-4
12
9 21
19 25
5
2
3-4
12
9 21
19 25
5
2
3-4
19
9 21
25
1 2
3
228. Algorithm for deleting a node on BST
1. Find the location NODE of the DATA to be deleted.
2. If (NODE = NULL)
a) Display “DATA is not in tree”
b) Exit
3. If(NODE → Lchild = NULL)
a) LOC = NODE
b) NODE = NODE → RChild
4. If(NODE → RChild= =NULL)
a) LOC = NODE
b) NODE = NODE → LChild
5. If((NODE → Lchild not equal to NULL) && (NODE → Rchild not
equal to NULL))
a) LOC = NODE → RChild
6. While(LOC → Lchild not equal to NULL)
a) LOC = LOC → Lchild
7. LOC → Lchild = NODE → Lchild
8. LOC → RChild= NODE → RChild
9. Exit
229. Graph
• Graph is an another nonlinear data structure.
• Applied in subjects like geography,
engineering and solving games and puzzles.
238. Isomorphic graph
If there is a one-to-one correspondence
between their vertices it is an isomorphic graph
239. Degree of vertex
The number of edges incident on a vertex is its
degree.
degree (a) = 3
240. Weighted graph
If every edge and/or vertices assigned with
some weight or value it is called weighted graph
G = (V, E, WE, WV)
N Negambo
C Colombo
K Kandy
M Matara
241. Disconnected graph
Connected graph exist a path from any vertex to
any other vertex, otherwise disconnected
Disconnected graph Connected graph
242. Complete graph
If there is a path from every vertex to every
other vertex it is a complete (fully connected)
graph
243. Paths in directed graphs
• An elementary path does not meet the same
vertex twice.
• A simple path does not meet the same edges
twice.
244. Paths in directed graphs
• (e1, e3, e4, e5, e6, e7, e8) is an elementary path.
• (e1, e3, e4, e5, e6, e7, e8, e11, e12) is a simple
path
245. Representation of a graph
• Sequential representation using adjacent
• Linked representation using linked list
251. Operations on graph
• Creating a graph
• Searching and deleting from a graph
• Traversing a graph
252. Creating a graph
1. Input the total number of vertices in the graph,
say n.
2. Allocate the memory dynamically for the
vertices to store in list array.
3. Input the first vertex and the vertices through
which it has edge(s) by linking the node from list
array through nodes.
4. Repeat the process by incrementing the list
array to add other vertices and edges.
5. Exit.
253. Searching and deleting from a graph
1. Input an edge to be searched
2. Search for an initial vertex of edge in list arrays
by incrementing the array index.
3. Once it is found, search through the link list for
the terminal vertex of the edge.
4. If found display “the edge is present in the
graph”.
5. Then delete the node where the terminal vertex
is found and rearrange the link list.
6. Exit
254. Traversing a graph
• Breadth First Traversal (BFT)
• Depth First Traversal (DFT)
255. Breadth First Traversal (BFT)
• The aim of breadth first traversal is to traverse
the graph as close as possible to the root node
(considered as the start)
• Queue is used implementation of BFT
256. Breadth First Traversal (BFT) Algorithm
1. Input the vertices of the graph and its edges
2. Input the source vertex and assign it to the
variable S.
3. Add the source vertex to the queue.
4. Repeat the steps 5 and 6 until the queue is
empty
5. Pop the front element of the queue and display
it as visited.
6. Push the vertices, which is neighbor to just,
popped element, if it is not in the queue and
displayed
7. Exit.
263. Depth First Traversal (DFT)
• The aim of DFT algorithm is to traverse the
graph in such a way that is tries to go so far
from the source (start) node.
• Stack is used in the implementation of the
DFT.
264. Depth First Traversal (DFT) Algorithm
1. Input the vertices and edges of the graph.
2. Input the source vertex and assign it to the
variable S.
3. Push the source vertex to the stack.
4. Repeat the steps 5 and 6 until the stack is empty.
5. Pop the top element of the stack and display it.
6. Push the vertices which is neighbor to just
popped element, if it is not in the queue and
displayed.
7. Exit.
265. Depth First Traversal (DFT)
I I G
H
Display: I, H, E, F, D, G
G
H
G
E
G
E
G
D
G
D
G
F F
D
G