Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 71

Department of Electronics & Telecommunication Engineering

INDEX
Course : Data Structure and Algorithm Sessional
Name
Course : ETE-2424
Code
Exp. Experimental Name Date of Date of
No Experiment Submission
01 Write a program using Array 11-11-2019 25/11/2029
02 Write a program using Stack 25-11-2019 9/12/2019
03 Write a program using Queue 09-12-2020 23/12/2019
04 Write a program using Recursion 23/12/2019 6/01/2020
05 Write a program using Searching 06-01-2020 20/1/2020
06 Write a program using Sorting 20-01-2020 3/02/2020
07 Write a program using Tree 3-02-2020. 17/02/2020
08 Write a program using Graph 17-02-2020 3/03/2020

Submitted By Submitted To

Name : Md.Najmuj Jakib Md Jiabul Hoque


ID:T181019 Lecturer,Dept of ETE
Semester : 4th Section : A
Dept : ETE
Department of Electronic & Telecommunication Engineering

LAB REPORT

Course Code :ETE-2424

Course Name :Data Structure & Algorithm Sessional

Experiment No :01

Experiment Name :Write algorithm &C program to find


minimum,maximum,insert & delete an element in array.

Submitted By

Name : Md Najmuj Jakib

ID :T181019

Section :A

Semester : 4th

Submitted To

Md. Jiabul Hoque

Lecturer, Dept. of ETE, IIUC

Date of Experiment :11/11/2019

Date of Submission :25/11/2019

Experiment No: 01
Example No: 01

Experiment name: Write a c program to find the maximum element in the array.
Objective :
1) To know about the array.
2) To know how to use it.
3) To find the maximum element in the array using C.
Requirements:
1) A computer with installed codeblocks program.
Algorithm:
Step 1: Start.
Step 2: Take an array A and define its value.
Step 3: Declare the biggest as integer.
Step 4: Set biggest to 0.
Step 5: Loop for each value of A.
Step 6: If A[n] > largest, assign A[n] to largest.
Step 7: After loop finishes, show the biggest element of the array.
Step 8: Stop.
Source code:
#include <stdio.h>
int main()
{
int array[100], maximum, size, c, location = 1;
printf("Enter number of elements in array\n");
scanf("%d", &size);
printf("Enter %d integers\n", size);
for (c = 0; c < size; c++)
{
scanf("%d", &array[c]);
}
maximum = array[0];
for (c = 1; c < size; c++)
{
if (array[c] > maximum)
{
maximum = array[c];
location = c+1;
}
}
printf("Maximum element is present at location %d and it's value is %d.\n", location,
maximum);
return 0;
}
Output:

Discussion:
The algorithm to find maximum is: we assume that it's present at the beginning of the
array and stores that value in a variable. Then we compare it with the other array
elements one by one, if any element is greater than our assumed maximum, then the
maximum value and the index at which it occurs are updated

Example No: 02
Experiment name: Write a c program to insert an element in an array.
Objective :
1) To know about the array.
2) To know how to use it.
3) To insert element in the array using C.
Requirements:
1) A computer with installed codeblocks program.
Algorithm:
Step 1: Start.
Step 2: Take an array A and define its value.
Step 3: Set a position to insert value or element.
Step 4: Insert the value or the element in that position.
Step 5: Show the full array with new element..
Step 6: Stop.
Source code:
#include <stdio.h>
int main()
{
int array[100],size,c,enterpoint,k;
printf("Enter number of elements in array\n");
scanf("%d",&size);
printf("Enter %d integers\n", size);
for (c = 0; c < size; c++)
{
scanf("%d",&array[c]);
}
printf("\nYour element list with their location\n\n");
for (c=0;c<size;c++)
{
printf("Location[%d]=%d.\n",c,array[c]);
}
printf("\nEnter the location in which you wants to enter element.\n\n");
printf("Element location=");
scanf("%d",&enterpoint);
k=enterpoint;
if(k>size||k<0)
{
printf("Enter valid position\n");
}
else
{
printf("\nEnter the new element\n");
printf("Location[%d]=",enterpoint);
scanf("%d",&array[k]);

printf("\nThe new element list is\n\n");

{
for (c =0;c<size;c++)
{
printf("Location[%d]=%d.\n",c,array[c]);
}
}
}
}

Output
Discussion:
Insert operation is to insert one or more data elements into an array. Based on the
requirement, a new element can be added at the beginning, end, or any given index of
array. In this experiment we have done an insertation of elements in an array with c
program. We set a position for the element and than inserted in that position.

Example No: 03
Experiment name: Write a c program to delete an element from an array.
Objective :
1) To know about the array.
2) To know how to use it.
3) To delete element in the array using C.
Requirements:
1) A computer with installed codeblocks program.
Algorithm:
Step 1: Start.
Step 2: Take an array A and define its value.
Step 3: Set a position to insert value or element.
Step 4: Insert the value or the element in that position.
Step 5: Show the full array with new element..
Step 6: Stop.
Source code:
#include <stdio.h>
int main()
{
int array[100],size,c,position,k;
printf("Enter number of elements in array\n");
scanf("%d",&size);
printf("Enter %d integers\n", size);
for (c = 0; c < size; c++)
{
scanf("%d",&array[c]);
}
printf("\nYour element list with their location\n\n");
for (c=0;c<size;c++)
{
printf("Location[%d]=%d.\n",c+1,array[c]);
}
printf("\nEnter the location where you wants to delete element\n");
printf("Location=");

scanf("%d", &position);

if (position >= size+1||position<0)


printf("Deletion not possible.\n");
else
{
for (c = position - 1; c < size - 1; c++)
array[c] = array[c+1];

printf("After delete the new list is:\n");

for (c = 0; c < size- 1; c++)


{
printf("Location[%d]=%d\n",c+1, array[c]);
}
}

Output:
Discussion:
Deletion refers to removing an existing element from the array and re-organizing all
elements of an array. Here we deleted an element with the help of c program in an
array. We set the position for the deletion of the element an and after deletion the
whole array was shown without the element.
Department of Electronic & Telecommunication Engineering

LAB REPORT

Course Code : ETE-2424

Course Name : Data Structure & Algorithm Sessional

Experiment No : 02

Experiment Name : Write an algorithm & a menu driven C program


that demonstrate the basic operation of stack.

Submitted By

Name : Md.Najmuj Jakib

ID : T181019

Section :A

Semester : 4th

Submitted To

Md. Jiabul Hoque

Lecturer, Dept. of ETE, IIUC

Date of Experiment : 25.11.2019

Date of Submission : 09.12.2019


Experiment No : 02
Experimen Name : Write an algorithm & a menu driven C
program that demonstrate the basic operation of stack.
Objectives : 1. How stack performs in C
program.
2. How pop, push operations
are operated by using stack
in C program.
Required Equipment : 1. Code-block Software.
2. Own PC.
Algorithm :
Push Operation :
Step 1 – Checks if the stack is full.
Step 2 – If the stack is full, produces an error & exit.
Step 3 – If the stack is not full, increments top to point next
empty space.
Step 4 – Adds data element to the stack location, where top
is pointing.
Step 5 – Returns success.
Pop Operation :
Step 1 – Checks if the stack is empty.
Step 2 – If the stack is empty, produces an error & exit.
Step 3 – If the stack is not empty, accesses the data element
at which top is pointing.
Step 4 – Decreases the value of top by 1.
Step 5 – Returns success.
Source Code :
#include<stdio.h>
#include<process.h>
#include<stdlib.h>

#define MAX 5

int top=-1,stack[MAX];
void push();
void pop();
void display();

void main()
{
in ch;
while(1)
{
printf("\nStack Menu");
printf("\n\n1.Push\n2.Pop\n3.Display\n4.Exit");
printf("\n\nEnter your choice(1-4)");
scanf("%d",&ch);

switch(ch
{
case 1: push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);

default: printf("\nWrong Choice!!");


}
)
}
void push()
{
int val;

if(top==MAX-1)
{
printf("\nStack is full!!");
}
else
printf("\nEnter element to push:");
scanf("%d",&val);
top=top+1;
stack[top]=val;
}
}

void pop()
{
if(top==-1)
{
printf("\nStack is empty!!");
}
else
{
printf("\nDeleted element is %d",stack[top]);
top=top-1;
}
}

void display()
{
int i;

if(top==-1)
{
printf("\nStack is empty!!");
}
else
{
printf("\nStack is...\n");
for(i=top;i>=0;-i)
printf("%d\n",stack[i]);
}
}
Output :

Discussion :
A stack is an Abstract Data Type (ADT), commonly used in most
programming languages.Stack operations may involve initializing the
stack, using it and then de-initializing it. Apart from these basic
stuffs, a stack is used for the following two primary operations −
1.push() − Pushing (storing) an element on the stack 2.pop() −
Removing (accessing) an element from the stack.To use a stack
efficiently, we need to check the status of stack as well. For the
same purpose, the following functionality is added to stacks : peek()
− get the top data element of the stack, without removing it; isFull()
− check if stack is full; isEmpty() − check if stack is empty.

Department of Electronic & Telecommunication Engineering

LAB REPORT

Course Code :ETE-2424

Course Name :Data Structure & Algorithm Sessional

Experiment No :03

Experiment Name :Write algorithm & a manu driven C program that


demonstrate the basic operation of queue.

Submitted By

Name : Md.Najmuj Jakib

ID :T181019

Section :A

Semester : 4th

Submitted To
Md. Jiabul Hoque

Lecturer, Dept. of ETE, IIUC

Date of Experiment :9/12/2019

Date of Submission :23/12/2019

Experiment No : 03
Experiment Name : Write an algorithm and menu driven c prog
that demonstrate the basic operation of queue.
Objective : 1.To understand the operation of queue.
2. To understand how enqueue, dequeue and dis
functions .

Require Equipment: 1.Codeblock software.


Algorithm:

Enqueue:

1. procedure enqueue(data)
2. if queue is full.
3. return overflow.
4. endif
5. rear ← rear + 1
6. queue[rear] ← data
7. return true
8. end procedure

Dequeue:

1. procedure dequeue
2. if queue is empty
3. return underflow
4. end if
5. data = queue[front]
6. front ← front + 1
7. return true
8. end procedure

Display:

procedure display
if queue is empty
return underflow
else
print all queue
end procedure

Source code:
#include <stdio.h>

#define MAX 25

void enqueue();

void dequeue();

void display();

int queue_array[MAX];

int rear = - 1;

int front = - 1;

main()

int choice;

while (1)

printf("1.enqueue element \n");

printf("2.dequeue element \n");

printf("3.Display queue element \n");

printf("4.Quit \n");

printf("Enter your choice : ");

scanf("%d", &choice);

switch (choice)

case 1:

enqueue();

break;
case 2:

dequeue();

break;

case 3:

display();

break;

case 4:

exit(1);

default:

printf("Wrong choice \n");

void enqueue()

int add_item;

if (rear == MAX - 1)

printf("Queue Overflow \n");

else

if (front == - 1)

front = 0;

printf("enqueue element ");

scanf("%d", &add_item);
rear = rear + 1;

queue_array[rear] = add_item;

void dequeue()

if (front == - 1 || front > rear)

printf("Queue Underflow \n");

return ;

else

printf("dequeued element : %d\n", queue_array[front]);

front = front + 1;

void display()

int i;

if (front == - 1)

printf("Queue is empty \n");

else
{

printf("Queue is : \n");

for (i = front; i <= rear; i++)

printf("%d ", queue_array[i]);

printf("\n");

Output:

Disscussion:
Queue is an abstract data structure, somewhat similar to
Stacks. Unlike stacks, a queue is open at both its ends.

Queue operations may involve initializing or defining the


queue, utilizing it, and then completely erasing it from the
memory. Here we shall try to understand the basic
operations associated with queues −

enqueue() − add (store) an item to the queue.

dequeue() − remove (access) an item from the queue.


Department of Electronic & Telecommunication Engineering

LAB REPORT

Course Code :ETE-2424

Course Name :Data Structure & Algorithm Sessional

Experiment No :04

Experiment Name :Write a C program to demonstrate recursion using


tower of Hanoi problem & Fibonacci series problem.

Submitted By

Name : Md Najmuj Jakib

ID :T181019

Section :A

Semester : 4th

Submitted To

Md. Jiabul Hoque

Lecturer, Dept. of ETE, IIUC

Date of Experiment :23/12/2019

Date of Submission :6/1/2020


Experiment No: 04
Example No 1: Write a C Program to demonstrate recursion
using Tower of Hanoi problem.

Objectives:
1) To know how to use function in function in C program.
2) to know how to call a function.

Require equipment:
Code-blocks.
Own PC.

Algorithm:
Step 1: START.
Step 2: Procedure Hanoi(disk, source, dest, aux)
Step 3: IF disk == 1, THEN
Step 4: move disk from source to dest
Step 5: ELSE
Step 6: Hanoi(disk - 1, source, aux, dest) // Step 1
Step 7: move disk from source to dest // Step 2
Step 8: Hanoi(disk - 1, aux, dest, source) // Step 3
Step 9: END IF
Step 10: END Procedure
Step 11: STOP
Source code:

#include <stdio.h>
void towers(int, char, char, char);
int main()
{
int num;
printf("Enter the number of disks : ");
scanf("%d", &num);
printf("The sequence of moves involved in the
Tower of Hanoi are :\n");
towers(num, 'A', 'C', 'B');
return 0;
}
void towers(int num, char frompeg, char topeg,
char auxpeg)
{
if (num == 1)
{
printf("\n Move disk 1 from peg %c to peg
%c", frompeg, topeg);
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("\n Move disk %d from peg %c to peg
%c", num, frompeg, topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}

Output:

Discussion:
This C Program uses recursive function & solves the tower of
hanoi. The tower of hanoi is a mathematical puzzle. It consists
of threerods, and a number of disks of different sizes which can
slide onto any rod. The puzzle starts with the disks in a neat
stack in ascending order of size on one rod, the smallest at the
top. We have to obtain the same stack on the third rod.
In our Towers of Hanoi solution, we recurse on the largest disk
to be moved. That is, we will write a recursive function that
takes as a parameter the disk that is the largest disk in the
tower we want to move. Our function will also take three
parameters indicating from which peg the tower should be
moved (source), to which peg it should go (dest), and the other
peg, which we can use temporarily to make this happen
(spare).
Example No 2: Write a C Program to demonstrate recursion
using Fibonacci series problem.
Objectives:
1) To know how to use function in function in C program.
2) to know how to call a function.
Require equipment:
Code-blocks.
Own PC.
Algorithm:
Step 1: START.
Step 2: Procedure Fibonacci(n)
Step 3: declare f0, f1, fib, loop
Step 4: set f0 to 0
Step 5: set f1 to 1
Step 6: display f0, f1
Step 7: for loop ← 1 to n
Step 8: fib ← f0 + f1
Step 9: f0 ← f1
Step 10: f1 ← fib
Step 11: display fib
Step 12: end for
Step 13: STOP

Source code:
#include<stdio.h>
int Fibonacci(int);
int main()
{
int n, i = 0, c;
scanf("%d",&n);
printf("Fibonacci series\n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d\n", Fibonacci(i));
i++;
}
return 0;
}
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
Output:

Discussion:
The Fibonacci sequence is a set of numbers that starts with a
one or a zero, followed by a one, and proceeds based on the
rule that each number (called a Fibonacci number) is equal to
the sum of the preceding two numbers. It adds previous two
numbers value to compute the next number value.
In this program fibonacci series is calculated using recursion,
with seed as 0 and 1. Recursion means a function calling itself,
in the below code fibonacci function calls itself with a lesser
value several times. An termination condition is very important
to recursion function, i.e n == 0 and n == 1 or the recursive call
would be infinite leading to stack overflow error.
Department of Electronic & Telecommunication Engineering

LAB REPORT

Course Code :ETE-2424

Course Name :Data Structure & Algorithm Sessional

Experiment No :05

Experiment Name :Write an algoritm & C program to demonstrate


linear & binary series.

Submitted By

Name : Md.Najmuj Jakibb

ID :T181019

Section :A

Semester : 4th

Submitted To

Md. Jiabul Hoque

Lecturer, Dept. of ETE, IIUC


Date of Experiment :6/1/2020

Date of Submission :20/1/2020

Experiment no- 5
Example no 1- write a c program to demonstrate liner search.

Objectives-

Searching Algorithms are designed to check for an element or


retrieve an element from any data structure where it is stored.

It decides whether a search key is present in the data or not.

liner search starts at the beginning of the list and checks every
element of the list.

Require equipment-

Code-blocks

Own PC

Algorithm-

Step 1 - Read the search element from the user.

Step 2 - Compare the search element with the first element in the list.

Step 3 - If both are matched, then display "Given element is found!!!"


and terminate the function

Step 4 - If both are not matched, then compare search element with the
next element in the list.
Step 5 - Repeat steps 3 and 4 until search element is compared with last
element in the list.

Step 6 - If last element in the list also doesn't match, then display
"Element is not found!!!" and terminate the function.

Source code-

#include<stdio.h>

int main()

int a[20],i,x,n;

printf("How many elements?");

scanf("%d",&n);

printf("Enter array elements:n");

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

scanf("%d",&a[i]);

printf("nEnter element to search:");

scanf("%d",&x);

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

if(a[i]==x)

break;
if(i<n)

printf("Element found at index %d",i);

else

printf("Element not found");

return 0;

Output-

Discussion-

Linear search in C to find whether a number is present in an array. If it's


present, then at what location it occurs. It is also known as a sequential
search. It is straightforward and works as follows: we compare each
element with the element to search until we find it or the list ends.
Example no 2- Write a C program to demonstrate binary search.

Objectives-

Searching Algorithms are designed to check for an element or retrieve an


element from any data structure where it is stored.

Binary search algorithm applies to a sorted array for searching an element.

The search starts with comparing the target element with the middle element of
the array. If value matches then the position of the element is returned.

Require equipment-

Codebolcks

Own PC

Algorithm-

Step 1 - Read the search element from the user.

Step 2 - Find the middle element in the sorted list.

Step 3 - Compare the search element with the middle element in the sorted list.

Step 4 - If both are matched, then display "Given element is found!!!" and
terminate the function.

Step 5 - If both are not matched, then check whether the search element is smaller
or larger than the middle element.

Step 6 - If the search element is smaller than middle element, repeat steps 2, 3, 4
and 5 for the left sublist of the middle element.

Step 7 - If the search element is larger than middle element, repeat steps 2, 3, 4 and
5 for the right sublist of the middle element.
Step 8 - Repeat the same process until we find the search element in the list or until
sublist contains only one element.

Step 9 - If that element also doesn't match with the search element, then display
"Element is not found in the list!!!" and terminate the function.

Source code-

#include<stdio.h>

void main()

int arra[100],i,n,x,f,l,m,flag=0;

printf("Input no. of elements in an array\n");

scanf("%d",&n);

printf("Input %d value in ascending order\n",n);

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

scanf("%d",&arra[i]);

printf("Input the value to be search : ");

scanf("%d",&x);

/* Binary Search logic */

f=0;l=n-1;

while(f<=l)

m=(f+l)/2;

if(x==arra[m])
{

flag=1;

break;

else if(x<arra[m])

l=m-1;

else

f=m+1;

if(flag==0)

printf("%d value not found\n",x);

else

printf("%d value found at %d position\n",x,m);

Output-
Discussion-

Binary search in C language to find an element in a sorted array. If the array isn't
sorted, you must sort it using a sorting technique such as merge sort. If the
element to search is present in the list, then we print its location.
Department of Electronic & Telecommunication Engineering

LAB REPORT

Course Code :ETE-2424

Course Name :Data Structure & Algorithm Sessional

Experiment No :06

Experiment Name :Write an algoritm & C program to demonstrate bubble sort &
quick sort.

Submitted By

Name : Md Najmuj Jakib

ID :T181019

Section :A

Semester : 4th

Submitted To

Md. Jiabul Hoque

Lecturer, Dept. of ETE, IIUC

Date of Experiment : 20/1/2020

Date of Submission :3/2/2020


Experiment No: 06

Example 1: Write a C program to demonstrate Bubble Sort.

Objectives:

To learn about bubble sort.


To learn how to solve problem with c programming using bubble sort.

Requirements:

Desktop Computer/Laptop
CodeBlocks app

Algorithm:

Step 1: Repeat Steps 2 and 3 for i=1 to 10

Step 2: Set j=1

Step 3: Repeat while j<=r

(A) if a[i] < a[j]

Then interchange a[i] and a[j]

[End of if]

(B) Set j = j+1

[End of Inner Loop]

[End of Step 1 Outer Loop]

Step 4: Exit

Source Code:

#include <stdio.h>

int main()
{

Int a[50], r, m, s, swap;

printf ("Enter number of elements\n");

scanf ("%d",&r);

printf ("Enter %d integers\n",r);

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

scanf ("%d",&a[m]);

for (m=0; m<r-1; m++)

for (s=0; s<r-m-1; s++)

if (a[s]>a[s+1])

swap=a[s];

a[s]=a[s+1];

a[s+1]=swap;

printf ("Sorted list in ascending order:\n");

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

printf ("%d\n", a[m]);


}

Output:

Discussion:

Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-


based algorithm in which each pair of adjacent elements is compared and the
elements are swapped if they are not in order. 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.

Example 2: Write a C program to demonstrate Quick sort.

Objectives:
To learn about quick sort.
To learn how to solve problem with c programming using quick sort.

Requirements:

Desktop Computer/Laptop
CodeBlocks app

Algorithm:

QUICKSORT (A, p, r)

1 if p < r

2 then q ← PARTITION (A, p, r)

3 QUICKSORT (A, p, q - 1)

4 QUICKSORT (A, q + 1, r)

The key to the algorithm is the PARTITION procedure, which rearranges

the subarray A[p r] in

place.

PARTITION (A, p, r)

1 x ← A[r]

2i←p-1

3 for j ← p to r - 1

4 do if A[j] ≤ x

5 then i ← i + 1

6 exchange A[i] ↔ A[j]

7 exchange A[i + 1] ↔ A[r]


8 return i + 1

Source Code:

#include<stdio.h>

void quicksort (int number[],int p,int r)

int i, j, pivot, swap;

if(p<r)

pivot= p;

i= p;

j= r;

while (i<j)

While (number[i]<=number[pivot]&&i<r)

i++;

while (number[j]>number[pivot])

j--;

if (i<j)

{
swap= number[i];

number[i]= number[j];

number[j]= swap;

swap= number[pivot];

number[pivot]= number[j];

number[j]= swap;

quicksort(number,p,j-1);

quicksort(number,j+1,r);

int main()

int i, count, number[25];

printf ("Enter number of elements:\n");

scanf ("%d",&count);

printf ("Enter %d elements:\n", count);

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

scanf ("%d",&number[i]);

quicksort (number,0,count-1);

printf ("Sorted in ascending order:\n");

for (i=0;i<count;i++)
printf ("%d\n",number[i]);

Output:

Discussion:

Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of
data into smaller arrays. A large array is partitioned into two arrays one of which holds
values smaller than the specified value, say pivot, based on which the partition is made
and another array holds values greater than the pivot value.

Quicksort partitions an array and then calls itself recursively twice to sort the two
resulting subarrays. This algorithm is quite efficient for large-sized data sets as its
average and worst-case complexity are O(nLogn) and image.png(n2), respectively.
Department of Electronic & Telecommunication Engineering
LAB REPORT

Course Code :ETE-2424

Course Name :Data Structure & Algorithm Sessional

Experiment No :07

Experiment Name :Write an algoritm & C program to implement the tree


traversal using the binary tree.

Submitted By

Name : Md.Najmuj Jakib

ID :T181019

Section :A

Semester : 4th

Submitted To

Md. Jiabul Hoque

Lecturer, Dept. of ETE, IIUC

Date of Experiment : 3/2/2020

Date of Submission :17/2/2020

Experiment No : 07

Experiment Name : Write a C program to implement the tree traversal


using the binary tree.
Objective : 1.To understand how tree traversal work in c
programming.
2.To understand how in-order traversal,pre-order
traversal,post-order traversal works.

Require Equipment: 1.Codeblock software.


Algorithm:
In-order Traversal:
Step 1 − Recursively traverse left subtree.
Step 2 − Visit root node.
Step 3 − Recursively traverse right subtree.

Pre-order Traversal:
Step 1 − Visit root node.
Step 2 − Recursively traverse left sub-tree.
Step 3 − Recursively traverse right sub-tree.

Post-order Traversal:
Step 1 − Recursively traverse left subtree.
Step 2 − Recursively traverse right subtree.
Step 3 − Visit root node.

Source code:
#include <stdio.h>
#include <stdlib.h>

struct node {
int data;

struct node *leftChild;


struct node *rightChild;
};

struct node *root = NULL;

void insert(int data) {


struct node *tempNode = (struct node*) malloc(sizeof(struct
node));
struct node *current;
struct node *parent;

tempNode->data = data;
tempNode->leftChild = NULL;
tempNode->rightChild = NULL;

//if tree is empty


if(root == NULL) {
root = tempNode;
} else {
current = root;
parent = NULL;

while(1) {
parent = current;

//go to left of the tree


if(data < parent->data) {
current = current->leftChild;
//insert to the left
if(current == NULL) {
parent->leftChild = tempNode;
return;
}
} //go to right of the tree
else {
current = current->rightChild;

//insert to the right


if(current == NULL) {
parent->rightChild = tempNode;
return;
}
}
}
}
}
struct node* search(int data) {
struct node *current = root;
printf("Visiting elements: ");

while(current->data != data) {
if(current != NULL)
printf("%d ",current->data);

//go to left tree


if(current->data > data) {
current = current->leftChild;
}
//else go to right tree
else {
current = current->rightChild;
}

//not found
if(current == NULL) {
return NULL;
}
}

return current;
}

void pre_order_traversal(struct node* root) {


if(root != NULL) {
printf("%d ",root->data);
pre_order_traversal(root->leftChild);
pre_order_traversal(root->rightChild);
}
}

void inorder_traversal(struct node* root) {


if(root != NULL) {
inorder_traversal(root->leftChild);
printf("%d ",root->data);
inorder_traversal(root->rightChild);
}
}

void post_order_traversal(struct node* root) {


if(root != NULL) {
post_order_traversal(root->leftChild);
post_order_traversal(root->rightChild);
printf("%d ", root->data);
}
}

int main() {
int i;
int array[7] = { 27, 14, 35, 10, 19, 31, 42 };

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


insert(array[i]);
i = 31;
struct node * temp = search(i);

if(temp != NULL) {
printf("[%d] Element found.", temp->data);
printf("\n");
}else {
printf("[ x ] Element not found (%d).\n", i);
}

i = 15;
temp = search(i);

if(temp != NULL) {
printf("[%d] Element found.", temp->data);
printf("\n");
}else {
printf("[ x ] Element not found (%d).\n", i);
}
printf("\nPreorder traversal: ");
pre_order_traversal(root);

printf("\nInorder traversal: ");


inorder_traversal(root);

printf("\nPost order traversal: ");


post_order_traversal(root);

return 0;
}
Output:

Disscussion:
Traversal is a process to visit all the nodes of a tree and may
print their values too. Because, all nodes are connected via
edges (links) we always start from the root (head) node. That is,
we cannot randomly access a node in a tree. There are three
ways which we use to traverse a tree −
In-order Traversal
Pre-order Traversal
Post-order Traversal
Generally, we traverse a tree to search or locate a given item or
key in the tree or to print all the values it contains.
Department of Electronic & Telecommunication Engineering

LAB REPORT

Course Code :ETE-2424

Course Name :Data Structure & Algorithm Sessional

Experiment No :08

Experiment Name :Write an algoritm & C program to implement BFS traversal


& DFS traversal

Submitted By

Name : Md.Najmuj Jakib

ID :T181019

Section :A

Semester : 4th

Submitted To

Md. Jiabul Hoque

Lecturer, Dept. of ETE, IIUC

Date of Experiment : 17/2/2020


Date of Submission :3/3/2020

Experiment Name:

Experiment No: 08

Example (1): A c program top implement BFS traversal.

Objectives: 1) To understand how a graph can be represented and Breadth First traversed

Algorithm: Step1: Initialize the queue.

Step2: We start from visiting S (starting node), and mark it as visited.

Step3: see an unvisited adjacent node from S, and here we have three
Nodes and alphabetically choose A.

Step4: the unvisited adjacent node from S is B. We mark it as visited


And enqueue it.

Step5: the unvisited adjacent node from S is C. We mark it as visited


And enqueue it.

Step6: S is left with no unvisited adjacent nodes. So, we dequeue and


Find A.

Step7: From A we have D as unvisited adjacent node, We mark it as


As visited and enqueue it.

Required Equipment: 1) Code Blocks

2)PC

Source Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 5

struct Vertex {
char label;
bool visited;
};

int queue[MAX];
int rear = -1;
int front = 0;
int queueItemCount = 0;

struct Vertex* lstVertices[MAX];

int adjMatrix[MAX][MAX];

int vertexCount = 0;

//queue functions

void insert(int data) {


queue[++rear] = data;
queueItemCount++;
}

int removeData() {
queueItemCount--;
return queue[front++];
}

bool isQueueEmpty() {
return queueItemCount == 0;
}

void addVertex(char label) {


struct Vertex* vertex = (struct Vertex*) malloc(sizeof(struct
Vertex));
vertex->label = label;
vertex->visited = false;
lstVertices[vertexCount++] = vertex;
}

void addEdge(int start,int end) {


adjMatrix[start][end] = 1;
adjMatrix[end][start] = 1;
}

void displayVertex(int vertexIndex) {


printf("%c ",lstVertices[vertexIndex]->label);
}

int getAdjUnvisitedVertex(int vertexIndex) {


int i;

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


if(adjMatrix[vertexIndex][i] == 1 && lstVertices[i]->visited
== false)
return i;
}

return -1;
}

void breadthFirstSearch() {
int i;

lstVertices[0]->visited = true;

displayVertex(0);

insert(0);
int unvisitedVertex;

while(!isQueueEmpty()) {

int tempVertex = removeData();

while((unvisitedVertex = getAdjUnvisitedVertex(tempVertex)) !
= -1) {
lstVertices[unvisitedVertex]->visited = true;
displayVertex(unvisitedVertex);
insert(unvisitedVertex);
}

for(i = 0;i<vertexCount;i++) {
lstVertices[i]->visited = false;
}
}

int main() {
int i, j;

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


for(j = 0; j<MAX; j++)
adjMatrix[i][j] = 0;
}

addVertex('S'); // 0
addVertex('A'); // 1
addVertex('B'); // 2

addVertex('D'); // 4

addEdge(0, 1); // S - A
addEdge(0, 2); // S - B
addEdge(0, 3); // S - C
addEdge(1, 4); // A - D
addEdge(2, 4); // B - D
addEdge(3, 4); // C - D

printf("\nBreadth First Search: ");

breadthFirstSearch();

return 0;
}

Output:
Breadth First Search: S A B C D

Discussion :
Breadth first search is a graph traversal algorithm that starts traversing the
graph from root node and explores all the neighbouring nodes. Then, it selects
the nearest node and explore all the unexplored nodes. The algorithm follows
the same process for each of the nearest node until it finds the goal.
Example(2): A c program to implement DFS traversal.

Objectives: To understand how a graph can represented and Depth first traversed.

Required Equipment: 1)Code blocks

2)PC

Algorithm: Step1: Initialize the stack.

Step2: Take S as visited and put it on to the stack, and take the

node in an alphabetical order.

Step3: Mark S as visited and put it onto the stack, explore any

unvisited adjacent node from A. Both A and D are adjacent to

A.

Step4: Visit D and mark it as visited and put onto the stack. We

have B and C nodes which are adjacent to D which also

unvisited.

Step5: Choose B and mark its as visited and put it onto the

stack,B does not have any unvisited nodes, so we find D to be

on the top of the stack.


Step6: we check the stack top for return to the previous node

and check if its has any unvisited nodes.

Step7: Only unvisited adjacent node is D to C, So visit C.

Source code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX 5

struct Vertex {
char label;
bool visited;
};

int stack[MAX];
int top = -1;

struct Vertex* lstVertices[MAX];

int adjMatrix[MAX][MAX];

int vertexCount = 0;

void push(int item) {


stack[++top] = item;
}

int pop() {
return stack[top--];
}

int peek() {
return stack[top];
}

bool isStackEmpty() {
return top == -1;
}

void addVertex(char label) {


struct Vertex* vertex = (struct Vertex*) malloc(sizeof(struct
Vertex));
vertex->label = label;
vertex->visited = false;
lstVertices[vertexCount++] = vertex;
}

void addEdge(int start,int end) {


adjMatrix[start][end] = 1;
adjMatrix[end][start] = 1;
}

void displayVertex(int vertexIndex) {


printf("%c ",lstVertices[vertexIndex]->label);
}

int getAdjUnvisitedVertex(int vertexIndex) {


int i;

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


if(adjMatrix[vertexIndex][i] == 1 && lstVertices[i]->visited
== false) {
return i;
}
}

return -1;
}

void depthFirstSearch() {
int i;

lstVertices[0]->visited = true;

displayVertex(0);

push(0);

while(!isStackEmpty()) {
//get the unvisited vertex of vertex which is at top of the
stack
int unvisitedVertex = getAdjUnvisitedVertex(peek());

if(unvisitedVertex == -1) {
pop();
} else {
lstVertices[unvisitedVertex]->visited = true;
displayVertex(unvisitedVertex);
push(unvisitedVertex);
}
}

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


lstVertices[i]->visited = false;
}
}

int main() {
int i, j;

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


for(j = 0; j < MAX; j++)
adjMatrix[i][j] = 0;
}

addVertex('S'); // 0
addVertex('A'); // 1
addVertex('B'); // 2
addVertex('C'); // 3
addVertex('D'); // 4

addEdge(0, 1); // S - A
addEdge(0, 2); // S - B
addEdge(0, 3); // S - C
addEdge(1, 4); // A - D
addEdge(2, 4); // B - D
addEdge(3, 4); // C - D

printf("Depth First Search: ")


depthFirstSearch();

return 0;
}

Output:

Depth First Search: S A D B C


Discussion:

Depth first search (DFS) algorithm starts with the initial node of the graph G,
and then goes to deeper and deeper until we find the goal node or the node
which has no children. The algorithm, then backtracks from the dead end
towards the most recent node that is yet to be completely unexplored.

You might also like