0% found this document useful (0 votes)
2 views62 pages

FDT ManualV1.0

The document is a lab manual for the Fundamentals of Data Structure course at SNPS University, compiled by Prabodh C P. It includes various programming topics such as string operations, search algorithms, sorting methods, and data structures like linked lists and trees, along with code listings and outputs. The manual is created using free software and is shared under a Creative Commons license for academic use.

Uploaded by

anukantharaju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views62 pages

FDT ManualV1.0

The document is a lab manual for the Fundamentals of Data Structure course at SNPS University, compiled by Prabodh C P. It includes various programming topics such as string operations, search algorithms, sorting methods, and data structures like linked lists and trees, along with code listings and outputs. The manual is created using free software and is shared under a Creative Commons license for academic use.

Uploaded by

anukantharaju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Department of CSE

}
Fundamentals of Data Structure (24BEELY106)
} I/II Semester
(common to all branches)
LAB MANUAL

Compiled by :
Prabodh C P
Asst Professor
Dept of CSE, SNPSU

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
To veiw a copy of this license, visit https://creativecommons.org/licenses/by-nc-sa/4.0/
Contents

Code::Blocks Usage iii

1 String Operations 2

2 Linear Search 5

3 Binary Search 7

4 Selection Sort 9

5 Singly Linked List 11

6 Stack 17

7 Path Matrix 21

8 Binary Search Tree 23

9 Array Operations 29

10 Bubble Sort 33

11 Insertion Sort 36

12 Linear Queue 38

13 Circular Queue 42

14 Shortest Path Matrix 47

15 Graph using Adjacency Matrix 50

i
Listings

1.1 A01StringOperations.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.1 A02LinearSearch.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.1 A03BinarySearch.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
4.1 A04SelectionSort.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
4.2 out4.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
5.1 A05SinglyLinkedList.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
6.1 A06StackOperations.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
6.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
7.1 A07PathMatrix.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
7.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
8.1 A08BST.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
8.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
9.1 B01ArrayOperations.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
9.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
10.1 B02BubbleSort.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
10.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
11.1 B03InsertionSort.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
11.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
12.1 B04LinearQueue.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
12.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
13.1 B05CircularQueue.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
13.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
14.1 B06ShortestPathMatrix.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
14.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
15.1 B07GraphAdjMatrix.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
15.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

ii
Preface

Usage of Free and Open Source Software


This manual has been developed for the lab component of the subject Fundamentals of Data Structure (24BEELY106)
for the first year students of SNPS University. This manual has been prepared entirely using Free Software. The
following Free Software has been used in preparation of this manual.
Operating System Ubuntu 24.04.2 LTS (Noble Numbat)

Linux Kernel 6.8.0-40-generic


Compiler gcc 13.3.0
IDE Code::Blocks 20.03

Version Control git 2.43


Typesetting Texmaker 5.1.3 with LaTeX
Image Editing GIMP 2.10.30
I am sharing this manual under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
License. To veiw a copy of this license, visit https://creativecommons.org/licenses/by-nc-sa/4.0/.
You are free to share modify this manual with attribution for academic purposes.

Use and spread the word of Free Software. Free Software leads to a Free Society!

Prabodh C P

iii
CODE::BLOCKS

CODE::BLOCKS TUTORIAL
Using Code::Blocks to compile and execute a C Program
To launch Code::Blocks IDE, Click on
Applications → Programming → Code::Blocks IDE
You will get a window as shown below

iv
LISTINGS LISTINGS

Code::Blocks creates what is called a Workspace to keep track of the project you are working on. It is possible for
you to be working on multiple projects within your workspace. A project is a collection of one or more source (as
well as header) files. Source files are the files that contain the source code for your program. If you are developing a
C program, you are writing C source code (.c files).

First start a new Project by clicking on Create a new project


OR To create a project, click on the File pull-down menu, open New and then Project.You get this pop-up window

Choose Console application


Then in the next window select the programming language C (and not C++)

In the next step give the Project Title and specify the folder where you want to save your project.
(Note : Dont use any special characters or whitespaces for project title and folder names)

Finally you will be prompted to choose the compiler. Just choose the default options here (Dont change the
options). You should be using GNU GCC Compiler. Click Finish to create the new project.

Dept of CSE, SNPSU - CPP v


LISTINGS LISTINGS

The system will then return to the [MyProgram] window and you are ready to write your program.In the Man-
agement area of the screen (Shift-F2 toggles the Management display), you will see the files that are part of the
project in the Projects tab. To see the source files, click on the triangle symbol to expand the Workspace and its
subdirectories.

Under Sources, there is a file called main.c, which is automatically created for you when you build a console
application. Click on main.c.

main.c contains a simple Hello World program which you can edit later to solve a programming problem. Now let
us see how to compile and execute this main.c program. Just to understand the process of debugging we knowingly
introduce an error in the program by removing the semicolon after the printf statement. We will now compile the
program (To compile a file means to take the instructions that you have written and translate it into machine code

Dept of CSE, SNPSU - CPP vi


LISTINGS LISTINGS

for the computer to understand).


Compile the project from the Build pull-down menu by clicking on Build option[Ctrl+F9].

The error messages are shown in the Build messages window at the bottom. Let us now try to understand these
error messages. === Build: Debug in MyProgram (compiler: GNU GCC Compiler) ===
main.c In function main:
main.c 7 error: expected ; before return
main.c 8 warning: control reaches end of non-void function [-Wreturn-type]
=== Build failed: 1 error(s), 1 warning(s) (0 minute(s), 1 second(s)) ===

The error messages show the errors in syntax (and not the logical errors). It also indicates the line number and
the type of error. Here in this example the error says that before the return statement in line no 7 a semicolon is
missing. The next message is a warning message which has resulted because of the previous error.
Now go to line number 6 and add a semicolon at the end. Now build your project again.

Dept of CSE, SNPSU - CPP vii


LISTINGS LISTINGS

Now the build message window shows the following message. 0 error(s), 0 warning(s) (0 minute(s), 0 second(s)
This means that the errors and warnings have been successfully resolved. Now it is time to run the program. You
can Execute the project from the Build pull-down menu by clicking on Run option[Ctrl+F10].

An output window pops displaying the output of the program. A greeting message ”Hello world!” is printed on
to the output console.

Dept of CSE, SNPSU - CPP viii


LISTINGS LISTINGS

Installing Code::Blocks IDE


If you want to install Code::Blocks IDE on your system, you can download it from its official webpage.
http://www.codeblocks.org/
It is available for Linux, Mac, Windows platforms.
On Debian/Ubuntu systems Code::Blocks can be installed by using the apt package manner. You have to be
connected to the internet for necessary files to be downloaded. Run the following command.
$sudo apt install codeblocks
For Windows download the binary whose name is like codeblocks-17.12mingw-setup.exe

Dept of CSE, SNPSU - CPP ix


PART-A

1
Chapter 1

String Operations

Question
Write a menu driven C program to perform the following string operations using pointers

ˆ String Length
ˆ String Concatenation
ˆ String Reverse

C Code
1 #include <stdio.h>
2 #include <stdlib.h>
3

4 int main()
5 {
6 char acString1[40], acString2[40],acString3[40];
7 int iLen, i, iChoice;
8 char *strPtr;
9

10 while(1)
11 {
12 printf("\n1.String Length\n2.String Concatenation\n3.String Reverse\n4.Exit\
n");
13 printf("\nEnter your choice\n");
14 scanf("%d",&iChoice);
15

16 switch(iChoice)
17 {
18 case 1:
19 printf("\nEnter the string : ");
20 scanf("%s", acString1);
21 iLen = 0;
22 strPtr = acString1;
23 while(*strPtr != ’\0’)
24 {
25 iLen++;
26 strPtr++;
27 }
28 printf("\nLength of the string is %d\n", iLen);
29

30 break;
31 case 2:
32 printf("\nEnter the first string : ");
33 scanf("%s", acString1);
34 printf("\nEnter the second string : ");

2
CHAPTER 1. STRING OPERATIONS

35 scanf("%s", acString2);
36

37 strPtr = acString1;
38 iLen = 0;
39 while(*strPtr != ’\0’)
40 {
41 iLen++;
42 strPtr++;
43 }
44

45 strPtr = acString2;
46 i = 0;
47 while(*strPtr != ’\0’)
48 {
49 acString1[iLen + i] = *strPtr;
50 strPtr++;
51 i++;
52 }
53 acString1[iLen+i]=’\0’;
54 printf("\nConcatenated String is %s\n", acString1);
55 break;
56 case 3:
57 printf("\nEnter the string to be reversed: ");
58 scanf("%s", acString2);
59 strPtr = acString2;
60 while(*strPtr != ’\0’)
61 {
62 strPtr++;
63 }
64 strPtr--;
65 i=0;
66 while(strPtr >= acString2)
67 {
68 acString3[i] = *strPtr;
69 strPtr--;
70 i++;
71 }
72 acString3[i]=’\0’;
73 printf("\nReversed String is %s\n", acString3);
74 break;
75 case 4:
76 exit(0);
77 }
78 }
79 return 0;
80 }
Listing 1.1: A01StringOperations.c

Output
=================================
1 /***************************************
2

3 1.String Length
4 2.String Concatenation
5 3.String Reverse
6 4.Exit
7

8 Enter your choice


9 1
10

11 Enter the string : Raj

Dept of CSE, SNPSU - CPP 3


CHAPTER 1. STRING OPERATIONS

12

13 Length of the string is 3


14

15 1.String Length
16 2.String Concatenation
17 3.String Reverse
18 4.Exit
19

20 Enter your choice


21 2
22

23 Enter the first string : Raj


24

25 Enter the second string : kumar


26

27 Concatenated String is Rajkumar


28

29 1.String Length
30 2.String Concatenation
31 3.String Reverse
32 4.Exit
33

34 Enter your choice


35 3
36

37 Enter the string to be reversed: reverse


38

39 Reversed String is esrever


40

41 1.String Length
42 2.String Concatenation
43 3.String Reverse
44 4.Exit
45

46 Enter your choice


47 4
48 ***************************************/
Listing 1.2: OUTPUT

Dept of CSE, SNPSU - CPP 4


Chapter 2

Linear Search

Question
Write a program to find the location of a given number using Linear search.

C Code
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<stdbool.h>
4

5 int main(void)
6 {
7 int iaArr[10],iNum,i,j,iKey;
8 bool bFound;
9

10 printf("\nEnter the number of elements\n");


11 scanf("%d",&iNum);
12

13 printf("\nEnter the elements\n");


14 for(j=0;j<iNum;j++)
15 scanf("%d",&iaArr[j]);
16

17 printf("\nEnter the key element\n");


18 scanf("%d",&iKey);
19

20 bFound = false;
21 for(i=0;i<iNum;i++)
22 {
23 if(iaArr[i] == iKey)
24 {
25 bFound = true;
26 break;
27 }
28 }
29 if(bFound)
30 printf("\nKey element %d found at position %d\n",iKey,i+1);
31 else
32 printf("\nKey element %d not found\n", iKey);
33

34 return 0;
35 }
Listing 2.1: A02LinearSearch.c

Output

5
CHAPTER 2. LINEAR SEARCH

1 /***************************************
2 Enter the number of elements
3 5
4

5 Enter the elements


6 2 4 1 7 6
7

8 Enter the key element


9 4
10

11 Key element 4 found at position 2


12

13

14

15 Enter the number of elements


16 4
17

18 Enter the elements


19 3 8 6 2
20

21 Enter the key element


22 9
23

24 Key element 9 not found


25

26 ***************************************/
Listing 2.2: OUTPUT

Dept of CSE, SNPSU - CPP 6


Chapter 3

Binary Search

Question
Write a C program to search for an element in an array using Binary Search.

C Code
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<stdbool.h>
4 int main(void)
5 {
6 int iaArr[10],iNum,i,iMid,iLow,iHigh,iKey;
7 bool bFound;
8

9 printf("\nEnter the number of elements\n");


10 scanf("%d",&iNum);
11

12 printf("\nEnter the elements\n");


13 for(i=0;i<iNum;i++)
14 scanf("%d",&iaArr[i]);
15

16 printf("\nThe elements entered are\n");


17 for(i=0;i<iNum;i++)
18 printf("%d\t",iaArr[i]);
19

20 printf("\nEnter the key element that you want to search\n");


21 scanf("%d",&iKey);
22

23 bFound = false;
24 iLow = 0;
25 iHigh = iNum-1;
26 while(iLow <= iHigh)
27 {
28 iMid = (iLow+iHigh)/2;
29 if(iKey == iaArr[iMid])
30 {
31 bFound = true;
32 break;
33 }
34 else if(iKey < iaArr[iMid])
35 {
36 iHigh = iMid-1;
37 }
38 else
39 {
40 iLow = iMid+1;

7
CHAPTER 3. BINARY SEARCH

41 }
42 }
43

44 if(bFound)
45 printf("\nKey element %d found at position %d\n",iKey,iMid+1);
46 else
47 printf("\nKey element %d not found\n", iKey);
48

49 return 0;
50 }
Listing 3.1: A03BinarySearch.c

Output 1

1 /***************************************
2 Enter the number of elements
3 5
4

5 Enter the elements


6 2 4 6 8 10
7

8 The elements entered are


9 2 4 6 8 10
10 Enter the key element that you want to search
11 8
12

13 Key element 8 found at position 4


14

15

16 Enter the number of elements


17 3
18

19 Enter the elements


20 1 3 5
21

22 The elements entered are


23 1 3 5
24 Enter the key element that you want to search
25 7
26

27 Key element 7 not found


28 ***************************************/
Listing 3.2: OUTPUT

Dept of CSE, SNPSU - CPP 8


Chapter 4

Selection Sort

Question
Write a C program to sort a list of N elements using Selection Sort Algorithm.

C Code
Implementation
1 /***************************************************************************
2 *File : A04SelectionSort.c
3 *Description : Program to implement Selection Sort Algorithm
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 24.04
6 *Date : 7 November 2024
7 ***************************************************************************/
8

9 #include<stdio.h>
10 #include<stdlib.h>
11

12 /***************************************************************************
13 *Function : main
14 *Input parameters: none
15 *RETURNS : 0 on success
16 ***************************************************************************/
17

18 int main(void)
19 {
20 int iNum, i, j, k, iaArr[10], iTemp,iMinPos;
21

22

23 printf("\n*************************************************");
24 printf("\n*\tPROGRAM TO IMPLEMENT SELECTION SORT\t*\n");
25 printf("*************************************************");
26

27 printf("\nEnter no of elements\n");
28 scanf("%d",&iNum);
29

30 printf("\nEnter the elements\n");


31 for(i=0;i<iNum;i++)
32 scanf("%d",&iaArr[i]);
33

34 for(i=0;i<iNum-1;i++)
35 {
36 iMinPos = i;
37 for(j=i+1;j<iNum;j++)

9
CHAPTER 4. SELECTION SORT

38 {
39

40 if(iaArr[j] < iaArr[iMinPos])


41 iMinPos = j;
42 }
43 iTemp = iaArr[i];
44 iaArr[i] = iaArr[iMinPos];
45 iaArr[iMinPos] = iTemp;
46

47

48 printf("\nElements swapped are %d and %d\n",iaArr[iMinPos],iaArr[i]);


49 for(k=0;k<iNum;k++)
50 printf("%d\t",iaArr[k]);
51

52

53 }
54

55 printf("\n\nThe Final Sorted array is \n");


56

57 for(i=0;i<iNum;i++)
58 printf("%d\t",iaArr[i]);
59

60 printf("\n");
61 return 0;
62 }
Listing 4.1: A04SelectionSort.c

Output
=================================
1 /***************************************
2

3 *************************************************
4 * PROGRAM TO IMPLEMENT SELECTION SORT *
5 *************************************************
6 Enter no of elements
7 5
8

9 Enter the elements


10 50 10 40 20 30
11

12 Elements swapped are 50 and 10


13 10 50 40 20 30
14 Elements swapped are 50 and 20
15 10 20 40 50 30
16 Elements swapped are 40 and 30
17 10 20 30 50 40
18 Elements swapped are 50 and 40
19 10 20 30 40 50
20

21 The Final Sorted array is


22 10 20 30 40 50
23

24

25 ***************************************/
Listing 4.2: out4.c

Dept of CSE, SNPSU - CPP 10


Chapter 5

Singly Linked List

Question
Write a C program to construct a singly linked list and perform insertion at the end, delete
specified element and display the elements.

C Code
1

2 #include<stdio.h>
3 #include<stdlib.h>
4

5 //Node Structure
6 struct node
7 {
8 int iInfo;
9 struct node* link;
10 };
11

12 typedef struct node* NODEPTR;


13 //NODEPTR is a pointer type that can point to a node
14 NODEPTR fnGetNode();
15 NODEPTR fnInsertRear(NODEPTR, int);
16 NODEPTR fnDeleteElement(NODEPTR, int);
17 void fnDisplay(NODEPTR);
18 void fnSearch(NODEPTR, int);
19

20 int main()
21 {
22 NODEPTR listPtr;
23 int iElem, iChoice;
24 //listPtr points to the first node in the list
25 listPtr = NULL; //initially the list is empty
26

27 while(1)
28 {
29 printf("\n1.Insert\n2.Delete\n3.Display\n4.Search\n5.Exit\n");
30 printf("\nEnter your choice\n");
31 scanf("%d",&iChoice);
32

33 switch(iChoice)
34 {
35 case 1:
36 printf("\nEnter the element to be inserted : ");
37 scanf("%d", &iElem);
38 listPtr = fnInsertRear(listPtr, iElem);
39 break;
40 case 2:

11
CHAPTER 5. SINGLY LINKED LIST

41 printf("\nEnter the element to be deleted : ");


42 scanf("%d", &iElem);
43 listPtr = fnDeleteElement(listPtr, iElem);
44 break;
45

46 case 3:
47 fnDisplay(listPtr);
48 break;
49 case 4:
50 printf("\nEnter the element to be searched : ");
51 scanf("%d", &iElem);
52 fnSearch(listPtr, iElem);
53 break;
54 case 5:
55 exit(0);
56 }
57 }
58 return 0;
59 }
60

61 NODEPTR fnInsertRear(NODEPTR listPtr, int iElem)


62 {
63 NODEPTR temp, cur;
64 temp = fnGetNode(); //create a new node pointed by temp
65 temp->iInfo = iElem; //store the element into the node
66 temp->link = NULL;
67 if(listPtr == NULL) //if list is empty
68 {
69 listPtr = temp;
70 }
71 else //insert at the end of the list
72 {
73 cur = listPtr;
74 while(cur->link != NULL)
75 {
76 cur = cur->link;
77 }
78 cur->link = temp;
79 }
80 return listPtr;
81 }
82

83 NODEPTR fnDeleteElement(NODEPTR listPtr, int iElem)


84 {
85 NODEPTR temp, cur, prev;
86 if(listPtr == NULL) //if list is empty
87 {
88 printf("\nDeletion not possible on empty list\n");
89 }
90 else if(listPtr->iInfo == iElem) //if node to be deleted is first element
91 {
92 if(listPtr->link == NULL) //if list has only one node
93 {
94 printf("\nElement deleted is %d\n", listPtr->iInfo);
95 free(listPtr);
96 listPtr = NULL; //list is now empty
97 }
98 else
99 {
100 temp = listPtr;
101 printf("\nElement deleted is %d\n", temp->iInfo);
102 listPtr = listPtr->link; //update listPtr to point to the

Dept of CSE, SNPSU - CPP 12


CHAPTER 5. SINGLY LINKED LIST

new first node


103 free(temp);
104 }
105 }
106 else //list has more than one elements
107 {
108 prev = NULL;
109 cur = listPtr;
110 //iterate till you have not reached the end of the list or you have not
found the search item
111 while(cur != NULL && cur->iInfo != iElem)
112 {
113 prev = cur;
114 cur = cur->link;
115 }
116 if(cur == NULL) //search reached end but element not found
117 {
118 printf("\nElement to be deleted is not found in the list\n");

119 }
120 else //cur points to the node to be deleted
121 {
122 prev->link = cur->link;
123 printf("\nElement deleted is %d\n", cur->iInfo);
124 free(cur);
125 }
126 }
127 return listPtr;
128 }
129

130 void fnDisplay(NODEPTR listPtr)


131 {
132 NODEPTR cur;
133 if(listPtr == NULL) //if list is empty
134 {
135 printf("\nList is empty\n");
136 }
137 else
138 {
139 cur = listPtr; //make cur point to the first node
140 printf("\nList contents : \n");
141 while(cur!=NULL) //iterate till the end of list and display node contents
142 {
143 printf("%d\t", cur->iInfo);
144 cur = cur->link;
145 }
146 }
147 printf("\n");
148 }
149 void fnSearch(NODEPTR listPtr, int iKey)
150 {
151 NODEPTR cur;
152 int iCount = 1;
153 if(listPtr == NULL) //if list is empty
154 {
155 printf("\nList is empty\n");
156 }
157 else
158 {
159 cur = listPtr; //make cur point to the first node
160 while(cur!=NULL && cur->iInfo != iKey) //iterate till the end of list and
display node contents

Dept of CSE, SNPSU - CPP 13


CHAPTER 5. SINGLY LINKED LIST

161 {
162 cur = cur->link;
163 iCount++;
164 }
165 if(cur == NULL)
166 {
167 printf("\nKey element %d not found.\n", iKey);
168 }
169 else
170 {
171 printf("\nKey element %d found in position %d\n", iKey, iCount);
172 }
173 }
174 }
175

176 NODEPTR fnGetNode()


177 {
178 NODEPTR newNodePtr;
179 newNodePtr = (NODEPTR)malloc(sizeof(struct node));
180 if(newNodePtr == NULL)
181 {
182 printf("\nError allocating dynamic memory!!\n");
183 exit(0);
184 }
185 return newNodePtr;
186 }
Listing 5.1: A05SinglyLinkedList.c

Output
=================================
1 /***************************************
2

3 1.Insert
4 2.Delete
5 3.Display
6 4.Search
7 5.Exit
8

9 Enter your choice


10 3
11

12 List is empty
13

14

15 1.Insert
16 2.Delete
17 3.Display
18 4.Search
19 5.Exit
20

21 Enter your choice


22 1
23

24 Enter the element to be inserted : 20


25

26 1.Insert
27 2.Delete
28 3.Display
29 4.Search
30 5.Exit
31

Dept of CSE, SNPSU - CPP 14


CHAPTER 5. SINGLY LINKED LIST

32 Enter your choice


33 1
34

35 Enter the element to be inserted : 30


36

37 1.Insert
38 2.Delete
39 3.Display
40 4.Search
41 5.Exit
42

43 Enter your choice


44 3
45

46 List contents :
47 20 30
48

49 1.Insert
50 2.Delete
51 3.Display
52 4.Search
53 5.Exit
54

55 Enter your choice


56 1
57

58 Enter the element to be inserted : 40


59

60 1.Insert
61 2.Delete
62 3.Display
63 4.Search
64 5.Exit
65

66 Enter your choice


67 3
68

69 List contents :
70 20 30 40
71

72 1.Insert
73 2.Delete
74 3.Display
75 4.Search
76 5.Exit
77

78 Enter your choice


79 4
80

81 Enter the element to be searched : 30


82

83 Key element 30 found in position 2


84

85 1.Insert
86 2.Delete
87 3.Display
88 4.Search
89 5.Exit
90

91 Enter your choice


92 4
93

Dept of CSE, SNPSU - CPP 15


CHAPTER 5. SINGLY LINKED LIST

94 Enter the element to be searched : 90


95

96 Key element 90 not found.


97

98 1.Insert
99 2.Delete
100 3.Display
101 4.Search
102 5.Exit
103

104 Enter your choice


105 2
106

107 Enter the element to be deleted : 30


108

109 Element deleted is 30


110

111 1.Insert
112 2.Delete
113 3.Display
114 4.Search
115 5.Exit
116

117 Enter your choice


118 3
119

120 List contents :


121 20 40
122

123 1.Insert
124 2.Delete
125 3.Display
126 4.Search
127 5.Exit
128

129 Enter your choice


130 5
131

132 ***************************************/
Listing 5.2: OUTPUT

Dept of CSE, SNPSU - CPP 16


Chapter 6

Stack

Question
Write a C program to demonstrate the working of stack using arrays.

C Code
1 #include <stdio.h>
2 #include <stdlib.h>
3 #define MAX_SIZE 5
4

5 int iaStack[MAX_SIZE], iTop = -1;


6

7 void fnPush();
8 void fnPop();
9 void fnDisplay();
10

11

12 int main()
13 {
14 int iElem, iChoice;
15

16 while(1)
17 {
18 printf("\n1.Push\n2.Pop\n3.Display\n4.Exit\n");
19 printf("\nEnter your choice\n");
20 scanf("%d",&iChoice);
21

22 switch(iChoice)
23 {
24 case 1:
25 fnPush();
26 break;
27 case 2:
28 fnPop();
29 break;
30 case 3:
31 fnDisplay();
32 break;
33 case 4:
34 exit(0);
35 }
36 }
37 return 0;
38 }
39

40 void fnPush()
41 {

17
CHAPTER 6. STACK

42 int iVal;
43 if(iTop == MAX_SIZE - 1)
44 {
45 printf("\nStack Overflow!!\n");
46 }
47 else
48 {
49 printf("\nEnter the element to be pushed on to the stack : ");
50 scanf("%d", &iVal);
51 iTop++;
52 iaStack[iTop] = iVal;
53 }
54 }
55

56 void fnPop()
57 {
58 int iVal;
59 if(iTop == -1)
60 {
61 printf("Stack Underflow!!\n");
62 }
63 else
64 {
65 iVal = iaStack[iTop];
66 iTop--;
67 printf("\nElement popped from the stack is %d\n", iVal);
68 }
69 }
70

71 void fnDisplay()
72 {
73 if(iTop == -1)
74 {
75 printf("\nStack is Empty\n");
76 }
77 else
78 {
79 printf("\nStack Contents: \n");
80 for(int i=iTop;i>=0;i--)
81 {
82 printf("\n%d", iaStack[i]);
83 }
84 }
85 printf("\n");
86 }
Listing 6.1: A06StackOperations.c

Output
=================================
1 /***************************************
2

3 1.Push
4 2.Pop
5 3.Display
6 4.Exit
7

8 Enter your choice


9 2
10 Stack Underflow!!
11

12 1.Push

Dept of CSE, SNPSU - CPP 18


CHAPTER 6. STACK

13 2.Pop
14 3.Display
15 4.Exit
16

17 Enter your choice


18 3
19

20 Stack is Empty
21

22

23 1.Push
24 2.Pop
25 3.Display
26 4.Exit
27

28 Enter your choice


29 1
30

31 Enter the element to be pushed on to the stack : 10


32

33 1.Push
34 2.Pop
35 3.Display
36 4.Exit
37

38 Enter your choice


39 1
40

41 Enter the element to be pushed on to the stack : 20


42

43 1.Push
44 2.Pop
45 3.Display
46 4.Exit
47

48 Enter your choice


49 1
50

51 Enter the element to be pushed on to the stack : 30


52

53 1.Push
54 2.Pop
55 3.Display
56 4.Exit
57

58 Enter your choice


59 3
60

61 Stack Contents:
62

63 30
64 20
65 10
66

67 1.Push
68 2.Pop
69 3.Display
70 4.Exit
71

72 Enter your choice


73 2
74

Dept of CSE, SNPSU - CPP 19


CHAPTER 6. STACK

75 Element popped from the stack is 30


76

77 1.Push
78 2.Pop
79 3.Display
80 4.Exit
81

82 Enter your choice


83 4
84

85 ***************************************/
Listing 6.2: OUTPUT

Dept of CSE, SNPSU - CPP 20


Chapter 7

Path Matrix

Question
Write a C program to generate and Display Path matrix of a graph whose adjacency matrix is
given as input.

C Code
=================================
1 #include <stdio.h>
2

4 const int MAX = 100;


5

6 void WarshallTransitiveClosure(int graph[MAX][MAX], int numVert)


7 {
8 int i,j,k;
9

10 for (k=0; k<numVert; k++)


11 {
12 for (i=0; i<numVert; i++)
13 {
14 for (j=0; j<numVert; j++)
15 {
16 if (graph[i][j] || (graph[i][k] && graph[k][j]))
17 graph[i][j] = 1;
18 }
19 }
20 }
21 }
22

23 int main()
24 {
25 int i, j, numVert;
26 int graph[MAX][MAX];
27

28

29 printf("Enter the number of vertices : ");


30 scanf("%d",&numVert);
31

32 printf("Enter the adjacency matrix :-\n");


33 for (i=0; i<numVert; i++)
34 for (j=0; j<numVert; j++)
35 scanf("%d",&graph[i][j]);
36

37 WarshallTransitiveClosure(graph, numVert);
38

39 printf("\nThe Path Matrix for the given graph is :-\n");

21
CHAPTER 7. PATH MATRIX

40 for (i=0; i<numVert; i++)


41 {
42 for (j=0; j<numVert; j++)
43 {
44 printf("%d\t",graph[i][j]);
45 }
46 printf("\n");
47 }
48

49 return 0;
50 }
Listing 7.1: A07PathMatrix.c

Output

Figure 7.1: Input Graph

1 /***************************************
2 Enter the number of vertices : 5
3 Enter the adjacency matrix :-
4 1 1 0 1 0
5 0 0 1 0 0
6 0 0 0 0 1
7 0 0 1 0 0
8 0 0 0 0 0
9

10 The Path Matrix for the given graph is :-


11 1 1 1 1 1
12 0 0 1 0 1
13 0 0 0 0 1
14 0 0 1 0 1
15 0 0 0 0 0
16

17 ***************************************/
Listing 7.2: OUTPUT

Dept of CSE, SNPSU - CPP 22


Chapter 8

Binary Search Tree

Question
Write a C program to create and traverse a binary search tree using various tree traversals.

C Code
1 /***************************************************************************
2 *File : 10_BST.c
3 *Description: Binary Search Tree Operations
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 28 September 2023
7 ***************************************************************************/
8

9 #include<stdio.h>
10 #include<stdlib.h>
11

12 struct node
13 {
14 int info;
15 struct node *lbranch;
16 struct node *rbranch;
17 };
18 typedef struct node* NODEPTR;
19

20 /* FUNCTION PROTOTYPES */
21 NODEPTR fnGetNode(void);
22 void fnFreeNode(NODEPTR x);
23 NODEPTR fnInsertNode(int, NODEPTR);
24 void fnInOrder(NODEPTR);
25 void fnPreOrder(NODEPTR);
26 void fnPostOrder(NODEPTR);
27

28 int main()
29 {
30 NODEPTR root = NULL;
31 int iChoice, iItem, i, iNum;
32

33 for(;;)
34 {
35 printf("\n1.Insert\n2.Inorder traversal\n3.Preorder traversal");
36 printf("\n4.Postorder traversal\n5.Exit\n");
37 printf("\nEnter your choice : ");
38 scanf("%d",&iChoice);
39

40 switch(iChoice)

23
CHAPTER 8. BINARY SEARCH TREE

41 {
42 case 1: printf("\nEnter the element : ");
43 scanf("%d", &iItem);
44 root = fnInsertNode(iItem,root);
45 break;
46

47 case 2: if(root ==NULL)


48 {
49 printf("\nTree is Empty\n");
50 }
51 else
52 {
53 printf("\nInorder Traversal is :\n");
54 fnInOrder(root);
55 printf("\n");
56 }
57 break;
58

59 case 3: if(root ==NULL)


60 {
61 printf("\nTree is Empty\n");
62 }
63 else
64 {
65 printf("\nPreorder Traversal is :\n");
66 fnPreOrder(root);
67 printf("\n");
68 }
69 break;
70

71 case 4: if(root ==NULL)


72 {
73 printf("\nTree is Empty\n");
74 }
75 else
76 {
77 printf("\nPostorder Traversal is :\n");
78 fnPostOrder(root);
79 printf("\n");
80 }
81 break;
82

83 case 5: exit(0);
84

85 default: printf("Wrong choice\n");


86 break;
87

88 }
89

90 }
91 return 0;
92 }
93

94 NODEPTR fnGetNode(void)
95 {
96 NODEPTR x;
97 x = ( NODEPTR ) malloc (sizeof(struct node));
98 if(x == NULL)
99 {
100 printf("\nOut of Memory");
101 exit(0);
102 }

Dept of CSE, SNPSU - CPP 24


CHAPTER 8. BINARY SEARCH TREE

103 return x;
104 }
105

106 void fnFreeNode(NODEPTR x)


107 {
108 free(x);
109 }
110

111 NODEPTR fnInsertNode(int iItem,NODEPTR root)


112 {
113 NODEPTR temp,prev,cur;
114

115 temp = fnGetNode();


116 temp->info = iItem;
117 temp->lbranch = NULL;
118 temp->rbranch = NULL;
119

120 if(root == NULL)


121 return temp;
122

123 prev = NULL;


124 cur = root;
125

126 while(cur != NULL)


127 {
128 prev = cur;
129

130 if(iItem == cur->info)


131 {
132 printf("\nDuplicate items not allowed\n");
133 fnFreeNode(temp);
134 return root;
135 }
136

137 cur = (iItem < cur->info)? cur->lbranch: cur->rbranch;


138 }
139

140 if(iItem < prev->info)


141 prev->lbranch = temp;
142 else
143 prev->rbranch = temp;
144

145 return root;


146

147 }
148

149 void fnPreOrder(NODEPTR root)


150 {
151 if(root != NULL)
152 {
153 printf("%d\t",root->info);
154 fnPreOrder(root->lbranch);
155 fnPreOrder(root->rbranch);
156 }
157 }
158

159 void fnInOrder(NODEPTR root)


160 {
161 if(root != NULL)
162 {
163 fnInOrder(root->lbranch);
164 printf("%d\t",root->info);

Dept of CSE, SNPSU - CPP 25


CHAPTER 8. BINARY SEARCH TREE

165 fnInOrder(root->rbranch);
166 }
167 }
168

169 void fnPostOrder(NODEPTR root)


170 {
171 if(root != NULL)
172 {
173 fnPostOrder(root->lbranch);
174 fnPostOrder(root->rbranch);
175 printf("%d\t",root->info);
176 }
177 }
Listing 8.1: A08BST.c

Output
=================================
1 /***************************************
2 1.Insert
3 2.Inorder traversal
4 3.Preorder traversal
5 4.Postorder traversal
6 5.Exit
7

8 Enter your choice : 1


9

10 Enter the element : 20


11

12 1.Insert
13 2.Inorder traversal
14 3.Preorder traversal
15 4.Postorder traversal
16 5.Exit
17

18 Enter your choice : 1


19

20 Enter the element : 10


21

22 1.Insert
23 2.Inorder traversal
24 3.Preorder traversal
25 4.Postorder traversal
26 5.Exit
27

28 Enter your choice : 1


29

30 Enter the element : 30


31

32 1.Insert
33 2.Inorder traversal
34 3.Preorder traversal
35 4.Postorder traversal
36 5.Exit
37

38 Enter your choice : 1


39

40 Enter the element : 5


41

42 1.Insert
43 2.Inorder traversal
44 3.Preorder traversal

Dept of CSE, SNPSU - CPP 26


CHAPTER 8. BINARY SEARCH TREE

45 4.Postorder traversal
46 5.Exit
47

48 Enter your choice : 2


49

50 Inorder Traversal is :
51 5 10 20 30
52

53 1.Insert
54 2.Inorder traversal
55 3.Preorder traversal
56 4.Postorder traversal
57 5.Exit
58

59 Enter your choice : 3


60

61 Preorder Traversal is :
62 20 10 5 30
63

64 1.Insert
65 2.Inorder traversal
66 3.Preorder traversal
67 4.Postorder traversal
68 5.Exit
69

70 Enter your choice : 4


71

72 Postorder Traversal is :
73 5 10 30 20
74

75 1.Insert
76 2.Inorder traversal
77 3.Preorder traversal
78 4.Postorder traversal
79 5.Exit
80

81 Enter your choice : 5


82 ***************************************/
Listing 8.2: OUTPUT

Dept of CSE, SNPSU - CPP 27


PART-B

28
Chapter 9

Array Operations

Question
Write a C program to demonstrate the following operations in an array

ˆ insertion of an element
ˆ deletion of an element
ˆ traversal

C Code
1 #include<stdio.h>
2 #include<stdlib.h>
3 #define LENGTH 50
4

5 int main()
6 {
7 int i, iaList[LENGTH], iNum, iIndex, iVal, iChoice;
8

9 printf("\nEnter the number of elements\n");


10 scanf("%d",&iNum);
11

12 printf("\nEnter the elements\n");


13 for(i=0;i<iNum;i++)
14 scanf("%d",&iaList[i]);
15

16

17 while(1)
18 {
19 printf("\nArray Operations : \n=====================\n1.Traversal\n2.Insert\
n3.Delete\n4.Exit\n");
20 printf("\nWhich operation do you want to perform?\n");
21 scanf("%d",&iChoice);
22

23 switch(iChoice)
24 {
25 case 1: /* Array Traversal*/
26 printf("\nArray Traversal to display array contents :\n");
27 for(i=0;i<iNum;i++)
28 {
29 printf("\n%d", iaList[i]);
30 }
31 printf("\n");
32

33 break;
34 case 2:

29
CHAPTER 9. ARRAY OPERATIONS

35 printf("\nArray Operation: Insertion of an element:\n");


36 printf("\nEnter the element to be inserted : ");
37 scanf("%d",&iVal);
38

39 printf("\nEnter the index where %d is to be inserted : ", iVal);


40 scanf("%d",&iIndex);
41 /*Shift elements starting from the given index till the end one position
right*/
42 for(i=iNum-1; i>= iIndex; i--)
43 {
44 iaList[i+1] = iaList[i];
45 }
46 iaList[iIndex] = iVal; //insert value at specified index
47 iNum++; //update count of elements in array
48

49 /* Display Contents of Array*/


50 printf("\nThe contents of the array is :\n");
51 for(i=0;i<iNum;i++)
52 {
53 printf("\n%d", iaList[i]);
54 }
55 printf("\n");
56 break;
57

58 case 3:
59 printf("\nArray Operation: Deletion of an element:\n");
60 printf("\nEnter the index where element is to be deleted : ");
61 scanf("%d",&iIndex);
62 if(iIndex >=iNum)
63 {
64 printf("\nInvalid Index\n");
65 break;
66 }
67

68 iVal = iaList[iIndex];
69 /*Shift elements starting from the element after the given index
till the end one position left*/
70 for(i=iIndex; i<iNum; i++)
71 {
72 iaList[i] = iaList[i+1];
73 }
74 iNum = iNum - 1; //update count of elements in array
75 printf("\nThe deleted element is %d at index %d\n", iVal, iIndex);
76 /* Display Contents of Array*/
77 printf("\nThe contents of the array is :\n");
78 for(i=0;i<iNum;i++)
79 {
80 printf("\n%d", iaList[i]);
81 }
82 printf("\n");
83 break;
84 case 4:
85 exit(0);
86 }
87 }
88 return 0;
89 }
Listing 9.1: B01ArrayOperations.c

Output
=================================

Dept of CSE, SNPSU - CPP 30


CHAPTER 9. ARRAY OPERATIONS

1 /***************************************
2 Enter the number of elements
3 5
4

5 Enter the elements


6 4 2 6 8 1
7

8 Array Operations :
9 =====================
10 1.Traversal
11 2.Insert
12 3.Delete
13 4.Exit
14

15 Which operation do you want to perform?


16 1
17

18 Array Traversal to display array contents :


19

20 4
21 2
22 6
23 8
24 1
25

26 Array Operations :
27 =====================
28 1.Traversal
29 2.Insert
30 3.Delete
31 4.Exit
32

33 Which operation do you want to perform?


34 2
35

36 Array Operation: Insertion of an element:


37

38 Enter the element to be inserted : 9


39

40 Enter the index where 9 is to be inserted : 2


41

42 The contents of the array is :


43

44 4
45 2
46 9
47 6
48 8
49 1
50

51 Array Operations :
52 =====================
53 1.Traversal
54 2.Insert
55 3.Delete
56 4.Exit
57

58 Which operation do you want to perform?


59 3
60

61 Array Operation: Deletion of an element:


62

Dept of CSE, SNPSU - CPP 31


CHAPTER 9. ARRAY OPERATIONS

63 Enter the index where element is to be deleted : 8


64

65 Invalid Index
66

67 Array Operations :
68 =====================
69 1.Traversal
70 2.Insert
71 3.Delete
72 4.Exit
73

74 Which operation do you want to perform?


75 3
76

77 Array Operation: Deletion of an element:


78

79 Enter the index where element is to be deleted : 4


80

81 The deleted element is 8 at index 4


82

83 The contents of the array is :


84

85 4
86 2
87 9
88 6
89 1
90

91 Array Operations :
92 =====================
93 1.Traversal
94 2.Insert
95 3.Delete
96 4.Exit
97

98 Which operation do you want to perform?


99 4
100

101 ***************************************/
Listing 9.2: OUTPUT

Dept of CSE, SNPSU - CPP 32


Chapter 10

Bubble Sort

Question
Write a C program to sort a list of elements using Bubble sort algorithm.

C Code
1 /***************************************************************************
2 *File : B02BubbleSort.c
3 *Description : Program to implement Bubble Sort Algorithm
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 24.04
6 *Date : 7 November 2024
7 ***************************************************************************/
8

9 #include<stdio.h>
10 #include<stdlib.h>
11

12 /***************************************************************************
13 *Function : main
14 *Input parameters: none
15 *RETURNS : 0 on success
16 ***************************************************************************/
17 #include<stdio.h>
18 #include<stdlib.h>
19 int main(void)
20 {
21 int iNum, i, j, k, iaArr[10], iTemp;
22

23 printf("\n*************************************************");
24 printf("\n*\tPROGRAM TO IMPLEMENT BUBBLE SORT\t*\n");
25 printf("*************************************************");
26

27 printf("\nEnter no of elements\n");
28 scanf("%d",&iNum);
29

30 printf("\nEnter the elements\n");


31 for(i=0;i<iNum;i++)
32 {
33 scanf("%d",&iaArr[i]);
34 }
35 getchar();
36 for(k=0;k<iNum;k++)
37 {
38 printf("%d\t",iaArr[k]);
39 }
40

33
CHAPTER 10. BUBBLE SORT

41 for(i=0;i<iNum-1;i++)
42 {
43 for(j=0;j<iNum-i-1;j++)
44 {
45 printf("\n\nIteration i=%d, j=%d\t now comparing %d and %d\n",i,j, iaArr
[j], iaArr[j+1]);
46 if(iaArr[j] > iaArr[j+1])
47 {
48 iTemp = iaArr[j];
49 iaArr[j] = iaArr[j+1];
50 iaArr[j+1] = iTemp;
51 }
52 for(k=0;k<iNum;k++)
53 {
54 printf("%d\t",iaArr[k]);
55 }
56 getchar();
57 }
58 }
59 printf("\nThe Sorted array is \n");
60 for(i=0;i<iNum;i++)
61 printf("%d\t",iaArr[i]);
62

63 printf("\n");
64 return 0;
65 }
Listing 10.1: B02BubbleSort.c

Output
=================================
1 /***************************************
2 *************************************************
3 * PROGRAM TO IMPLEMENT BUBBLE SORT *
4 *************************************************
5 Enter no of elements
6 5
7

8 Enter the elements


9 50 10 40 20 30
10 50 10 40 20 30
11

12 Iteration i=0, j=0 now comparing 50 and 10


13 10 50 40 20 30
14

15

16 Iteration i=0, j=1 now comparing 50 and 40


17 10 40 50 20 30
18

19

20 Iteration i=0, j=2 now comparing 50 and 20


21 10 40 20 50 30
22

23

24 Iteration i=0, j=3 now comparing 50 and 30


25 10 40 20 30 50
26

27

28 Iteration i=1, j=0 now comparing 10 and 40


29 10 40 20 30 50
30

31

Dept of CSE, SNPSU - CPP 34


CHAPTER 10. BUBBLE SORT

32 Iteration i=1, j=1 now comparing 40 and 20


33 10 20 40 30 50
34

35

36 Iteration i=1, j=2 now comparing 40 and 30


37 10 20 30 40 50
38

39

40 Iteration i=2, j=0 now comparing 10 and 20


41 10 20 30 40 50
42

43

44 Iteration i=2, j=1 now comparing 20 and 30


45 10 20 30 40 50
46

47

48 Iteration i=3, j=0 now comparing 10 and 20


49 10 20 30 40 50
50

51 The Sorted array is


52 10 20 30 40 50
53 ***************************************/
Listing 10.2: OUTPUT

Dept of CSE, SNPSU - CPP 35


Chapter 11

Insertion Sort

Question
Write a C program to sort a list of N elements using Insertion Sort Algorithm.

C Code
1 /***************************************************************************
2 *File : B03InsertionSort.c
3 *Description : Program to implement Insertion Sort Algorithm
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 24.04
6 *Date : 7 November 2024
7 ***************************************************************************/
8

9 #include<stdio.h>
10 #include<stdlib.h>
11

12 /***************************************************************************
13 *Function : main
14 *Input parameters: none
15 *RETURNS : 0 on success
16 ***************************************************************************/
17

18 int main(void)
19 {
20 int iNum, i, j, k, iaArr[10], iTemp,iKey;
21

22

23 printf("\n*************************************************");
24 printf("\n*\tPROGRAM TO IMPLEMENT INSERTION SORT\t*\n");
25 printf("*************************************************");
26

27 printf("\nEnter no of elements\n");
28 scanf("%d",&iNum);
29

30 printf("\nEnter the elements\n");


31 for(i=0;i<iNum;i++)
32 scanf("%d",&iaArr[i]);
33 getchar();
34 for(i=1;i<iNum;i++)
35 {
36 iKey = iaArr[i];
37 j = i-1;
38 while(j>=0 && iaArr[j] > iKey)
39 {
40 iaArr[j+1] = iaArr[j];

36
CHAPTER 11. INSERTION SORT

41 j--;
42 }
43 iaArr[j+1] = iKey;
44

45 printf("\nIteration i=%d, j=%d, Key=%d\n",i,j,iKey);


46 for(k=0;k<iNum;k++)
47 {
48 printf("%d\t",iaArr[k]);
49 }
50 getchar();
51

52 }
53

54 printf("\nThe Sorted array is \n");


55

56 for(i=0;i<iNum;i++)
57 printf("%d\t",iaArr[i]);
58

59 printf("\n");
60 return 0;
61 }
Listing 11.1: B03InsertionSort.c

Output
=================================
1

2 /***************************************
3 *************************************************
4 * PROGRAM TO IMPLEMENT INSERTION SORT *
5 *************************************************
6 Enter no of elements
7 5
8

9 Enter the elements


10 50 10 40 20 30
11

12 Iteration i=1, j=-1, Key=10


13 10 50 40 20 30
14

15 Iteration i=2, j=0, Key=40


16 10 40 50 20 30
17

18 Iteration i=3, j=0, Key=20


19 10 20 40 50 30
20

21 Iteration i=4, j=1, Key=30


22 10 20 30 40 50
23

24 The Sorted array is


25 10 20 30 40 50
26 ***************************************/
Listing 11.2: OUTPUT

Dept of CSE, SNPSU - CPP 37


Chapter 12

Linear Queue

Question
Write a C program to simulate the working of Linear Queue using arrays.

C Code
1 #include <stdio.h>
2 #include <stdlib.h>
3

5 #define QUEUE_SIZE 5
6 int myQueue[QUEUE_SIZE];
7 int iFront = 0, iRear = -1;
8

9 void fnInsertRear();
10 void fnDeleteFront();
11 void fnDisplay();
12

13 int main()
14 {
15 int iElem, iChoice;
16

17 for(;;)
18 {
19 printf("\nQueue Operations\n");
20 printf("=====================");
21 printf("\n1.Qinsert\n2.Qdelete\n3.Qdisplay\n4.Exit\n");
22 printf("Enter your choice\n");
23 scanf("%d",&iChoice);
24 switch(iChoice)
25 {
26 case 1: if(iRear == QUEUE_SIZE-1)
27 {
28 printf("\nQueue is Full\n");
29 }
30 else
31 {
32 fnInsertRear();
33 }
34 break;
35 case 2: if(iRear == iFront-1)
36 {
37 printf("\nQueue is Empty\n");
38 }
39 else
40 {

38
CHAPTER 12. LINEAR QUEUE

41 fnDeleteFront();
42 }
43 break;
44 case 3: if(iRear == iFront-1)
45 {
46 printf("\nQueue is Empty\n");
47 }
48 else
49 {
50 printf("\nContents of the Queue is \n");
51 fnDisplay();
52 }
53 break;
54

55 case 4: exit(0);
56

57 default: printf("\nInvalid choice\n");


58 }
59 }
60 return 0;
61 }
62

63 void fnInsertRear()
64 {
65 int iVal;
66 printf("\nEnter the element to be inserted : ");
67 scanf("%d", &iVal);
68 iRear++;
69 myQueue[iRear] = iVal;
70 }
71

72 void fnDeleteFront()
73 {
74 int iElem;
75 iElem = myQueue[iFront];
76

77 if(iFront == iRear)
78 {
79 iFront = 0;
80 iRear = -1;
81 }
82 else
83 {
84 iFront++;
85 }
86 printf("\nElement deleted is %d\n", iElem);
87 }
88

89 void fnDisplay()
90 {
91 int i;
92 for(i=iFront; i<=iRear; i++)
93 {
94 printf("%d\t", myQueue[i]);
95 }
96 printf("\n");
97 }
Listing 12.1: B04LinearQueue.c

Output
=================================

Dept of CSE, SNPSU - CPP 39


CHAPTER 12. LINEAR QUEUE

1 Queue Operations
2 =====================
3 1.Qinsert
4 2.Qdelete
5 3.Qdisplay
6 4.Exit
7 Enter your choice
8 2
9

10 Queue is Empty
11

12 Queue Operations
13 =====================
14 1.Qinsert
15 2.Qdelete
16 3.Qdisplay
17 4.Exit
18 Enter your choice
19 3
20

21 Queue is Empty
22

23 Queue Operations
24 =====================
25 1.Qinsert
26 2.Qdelete
27 3.Qdisplay
28 4.Exit
29 Enter your choice
30 1
31

32 Enter the element to be inserted : 1


33

34 Queue Operations
35 =====================
36 1.Qinsert
37 2.Qdelete
38 3.Qdisplay
39 4.Exit
40 Enter your choice
41 1
42

43 Enter the element to be inserted : 2


44

45 Queue Operations
46 /***************************************
47 =====================
48 1.Qinsert
49 2.Qdelete
50 3.Qdisplay
51 4.Exit
52 Enter your choice
53 1
54

55 Enter the element to be inserted : 3


56

57 Queue Operations
58 =====================
59 1.Qinsert
60 2.Qdelete
61 3.Qdisplay
62 4.Exit

Dept of CSE, SNPSU - CPP 40


CHAPTER 12. LINEAR QUEUE

63 Enter your choice


64 3
65

66 Contents of the Queue is


67 1 2 3
68

69 Queue Operations
70 =====================
71 1.Qinsert
72 2.Qdelete
73 3.Qdisplay
74 4.Exit
75 Enter your choice
76 2
77

78 Element deleted is 1
79

80 Queue Operations
81 =====================
82 1.Qinsert
83 2.Qdelete
84 3.Qdisplay
85 4.Exit
86 Enter your choice
87 3
88

89 Contents of the Queue is


90 2 3
91

92 Queue Operations
93 =====================
94 1.Qinsert
95 2.Qdelete
96 3.Qdisplay
97 4.Exit
98 Enter your choice
99 1
100

101 Enter the element to be inserted : 4


102

103 Queue Operations


104 =====================
105 1.Qinsert
106 2.Qdelete
107 3.Qdisplay
108 4.Exit
109 Enter your choice
110 3
111

112 Contents of the Queue is


113 2 3 4
114

115 Queue Operations


116 =====================
117 1.Qinsert
118 2.Qdelete
119 3.Qdisplay
120 4.Exit
121 Enter your choice
122 4
123 ***************************************/
Listing 12.2: OUTPUT

Dept of CSE, SNPSU - CPP 41


Chapter 13

Circular Queue

Question
Write a C program to implement a circular queue of integers.

C Code
1

2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <stdbool.h>
5

6 #define QUEUE_SIZE 5
7

8 int myQueue[QUEUE_SIZE];
9 int iFront = -1, iRear = -1;
10

11 void fnInsertRear();
12 void fnDeleteFront();
13 void fnDisplay();
14

15 int main()
16 {
17

18 int iChoice;
19

20 for(;;)
21 {
22 printf("\nQueue Operations\n");
23 printf("=====================");
24 printf("\n1.Qinsert\n2.Qdelete\n3.Qdisplay\n4.Exit\n");
25 printf("Enter your choice\n");
26 scanf("%d",&iChoice);
27

28 switch(iChoice)
29 {
30 case 1: if((iRear + 1) % QUEUE_SIZE == iFront)
31 {
32 printf("\nQueue is Full\n");
33 }
34 else
35 {
36 fnInsertRear();
37 }
38

39 break;
40 case 2: if(iFront == -1)

42
CHAPTER 13. CIRCULAR QUEUE

41 {
42 printf("\nQueue is Empty\n");
43 }
44 else
45 {
46 fnDeleteFront();
47 }
48

49 break;
50 case 3: if(iFront == -1)
51 {
52 printf("\nQueue is Empty\n");
53 }
54 else
55 {
56 printf("\nContents of the Queue is \n");
57 fnDisplay();
58 }
59

60 break;
61

62 case 4: exit(0);
63

64 default: printf("\nInvalid choice\n");


65 }
66 }
67 return 0;
68 }
69

70

71 void fnInsertRear()
72 {
73 int iVal;
74 printf("\nEnter the element : ");
75 scanf("%d", &iVal);
76 if(iRear == -1)
77 {
78 iFront++;
79 iRear++;
80 }
81 else
82 iRear = (iRear + 1)%QUEUE_SIZE;
83

84 myQueue[iRear] = iVal;
85 }
86

87 void fnDeleteFront()
88 {
89 int iElem;
90 iElem = myQueue[iFront];
91

92 if(iFront == iRear)
93 {
94 iFront = -1;
95 iRear = -1;
96 }
97 else
98 {
99 iFront = (iFront + 1)%QUEUE_SIZE;
100 }
101 printf("\nDeleted element is %d\n", iElem);
102 }

Dept of CSE, SNPSU - CPP 43


CHAPTER 13. CIRCULAR QUEUE

103

104 void fnDisplay()


105 {
106 int i;
107 if(iFront <= iRear)
108 {
109 for(i=iFront; i<=iRear; i++)
110 {
111 printf("%d\t", myQueue[i]);
112 }
113 printf("\n");
114 }
115 else
116 {
117 for(i=iFront; i<=QUEUE_SIZE-1; i++)
118 {
119 printf("%d\t", myQueue[i]);
120 }
121 for(i=0; i<=iRear; i++)
122 {
123 printf("%d\t", myQueue[i]);
124 }
125 printf("\n");
126 }
127 }
Listing 13.1: B05CircularQueue.c

Output
=================================
1 /***************************************
2 Queue Operations
3 =====================
4 1.Qinsert
5 2.Qdelete
6 3.Qdisplay
7 4.Exit
8 Enter your choice
9 2
10

11 Queue is Empty
12

13 Queue Operations
14 =====================
15 1.Qinsert
16 2.Qdelete
17 3.Qdisplay
18 4.Exit
19 Enter your choice
20 3
21

22 Queue is Empty
23

24 Queue Operations
25 =====================
26 1.Qinsert
27 2.Qdelete
28 3.Qdisplay
29 4.Exit
30 Enter your choice
31 1
32

Dept of CSE, SNPSU - CPP 44


CHAPTER 13. CIRCULAR QUEUE

33 Enter the element : 2


34

35 Queue Operations
36 =====================
37 1.Qinsert
38 2.Qdelete
39 3.Qdisplay
40 4.Exit
41 Enter your choice
42 1
43

44 Enter the element : 3


45

46 Queue Operations
47 =====================
48 1.Qinsert
49 2.Qdelete
50 3.Qdisplay
51 4.Exit
52 Enter your choice
53 3
54

55 Contents of the Queue is


56 2 3
57

58 Queue Operations
59 =====================
60 1.Qinsert
61 2.Qdelete
62 3.Qdisplay
63 4.Exit
64 Enter your choice
65 1
66

67 Enter the element : 4


68

69 Queue Operations
70 =====================
71 1.Qinsert
72 2.Qdelete
73 3.Qdisplay
74 4.Exit
75 Enter your choice
76 3
77

78 Contents of the Queue is


79 2 3 4
80

81 Queue Operations
82 =====================
83 1.Qinsert
84 2.Qdelete
85 3.Qdisplay
86 4.Exit
87 Enter your choice
88 2
89

90 Deleted element is 2
91

92 Queue Operations
93 =====================
94 1.Qinsert

Dept of CSE, SNPSU - CPP 45


CHAPTER 13. CIRCULAR QUEUE

95 2.Qdelete
96 3.Qdisplay
97 4.Exit
98 Enter your choice
99 3
100

101 Contents of the Queue is


102 3 4
103

104 Queue Operations


105 =====================
106 1.Qinsert
107 2.Qdelete
108 3.Qdisplay
109 4.Exit
110 Enter your choice
111 4
112

113 ***************************************/
Listing 13.2: OUTPUT

Dept of CSE, SNPSU - CPP 46


Chapter 14

Shortest Path Matrix

Question
Write a C program to generate and Display Shortest Path matrix of a graph whose cost adjacency
matrix is given as input.

C Code
1

3 #include <stdio.h>
4 #include <stdlib.h>
5 /******************************************************************************
6 *Function : main
7 *Input parameters: no parameters
8 *RETURNS : 0 on success
9 ******************************************************************************/
10 int main(void)
11 {
12 int iN, i, j, k;
13 int iaFloyd[10][10], iaCost[10][10];
14 printf("\n*********************************************************");
15 printf("\n*\tPROGRAM TO IMPLEMENT FLOYD’S ALGORITHM\t*\n");
16 printf("*********************************************************");
17 printf("\nEnter the number of vertices\n");
18 scanf("%d",&iN);
19 printf("\nEnter the Cost adjacency Matrix\n");
20 for(i=0;i<iN;i++)
21 for(j=0;j<iN;j++)
22 scanf("%d",&iaCost[i][j]);
23 printf("\nInput Graph\n");
24 for(i=0;i<iN;i++)
25 {
26 for(j=0;j<iN;j++)
27 {
28 printf("%d\t",iaCost[i][j]);
29 }
30 printf("\n");
31 }
32 printf("\n");
33

34 for(i=0;i<iN;i++)
35 {
36 for(j=0;j<iN;j++)
37 {
38 iaFloyd[i][j] = iaCost[i][j];
39 }

47
CHAPTER 14. SHORTEST PATH MATRIX

40 }
41

42 for(k=0;k<iN;k++)
43 {
44 for(i=0;i<iN;i++)
45 {
46 for(j=0;j<iN;j++)
47 {
48 if(iaFloyd[i][j] > (iaFloyd[i][k] + iaFloyd[k][j]))
49 iaFloyd[i][j] = (iaFloyd[i][k] + iaFloyd[k][j]);
50 }
51 }
52 }
53 printf("\nAll Pair Shortest Path Matrix\n");
54 for(i=0;i<iN;i++)
55 {
56 for(j=0;j<iN;j++)
57 {
58 printf("%d\t",iaFloyd[i][j]);
59 }
60 printf("\n");
61 }
62 printf("\n");
63 return 0;
64 }
Listing 14.1: B06ShortestPathMatrix.c

Figure 14.1: Input Graph

Output
=================================
1 /***************************************
2

3 *********************************************************
4 * PROGRAM TO IMPLEMENT FLOYD’S ALGORITHM *
5 *********************************************************
6 Enter the number of vertices
7 4
8

9 Enter the Cost adjacency Matrix


10 0 9999 3 9999
11 2 0 9999 9999
12 9999 7 0 1
13 6 9999 9999 0
14

15 Input Graph
16 0 9999 3 9999
17 2 0 9999 9999
18 9999 7 0 1
19 6 9999 9999 0
20

21

Dept of CSE, SNPSU - CPP 48


CHAPTER 14. SHORTEST PATH MATRIX

22 All Pair Shortest Path Matrix


23 0 10 3 4
24 2 0 5 6
25 7 7 0 1
26 6 16 9 0
27

28

29 ***************************************/
Listing 14.2: OUTPUT

Dept of CSE, SNPSU - CPP 49


Chapter 15

Graph using Adjacency Matrix

Question
Write a C program to create a directed graph using Adjacency Matrix.

C Code
1 #include <stdio.h>
2

3 int main()
4 {
5 int iaGraph[10][10], iNum, i, j;
6

7 printf("\nEnter the number of Vertices : ");


8 scanf("%d", &iNum);
9

10 printf("\nEnter the edges of the graph (1 if edge exists and 0 otherwise) : \n")
;
11 for(i=0; i<iNum; i++)
12 {
13 for(j=0; j<iNum; j++)
14 {
15 printf("\nEdge b/w vertex %d and %d : ", i+1, j+1);
16 scanf("%d", &iaGraph[i][j]);
17 }
18 }
19

20 printf("\nThe adjacency matrix of the entered graph is :\n");


21 for(i=0; i<iNum; i++)
22 {
23 for(j=0; j<iNum; j++)
24 {
25 printf("%d\t", iaGraph[i][j]);
26 }
27 printf("\n");
28 }
29 return 0;
30 }
Listing 15.1: B07GraphAdjMatrix.c

50
CHAPTER 15. GRAPH USING ADJACENCY MATRIX

Figure 15.1: Input Graph

Output
=================================
1 /***************************************
2 Enter the number of Vertices : 5
3

4 Enter the edges of the graph (1 if edge exists and 0 otherwise) :


5

6 Edge b/w vertex 1 and 1 : 1


7

8 Edge b/w vertex 1 and 2 : 1


9

10 Edge b/w vertex 1 and 3 : 0


11

12 Edge b/w vertex 1 and 4 : 1


13

14 Edge b/w vertex 1 and 5 : 0


15

16 Edge b/w vertex 2 and 1 : 0


17

18 Edge b/w vertex 2 and 2 : 0


19

20 Edge b/w vertex 2 and 3 : 1


21

22 Edge b/w vertex 2 and 4 : 0


23

24 Edge b/w vertex 2 and 5 : 0


25

26 Edge b/w vertex 3 and 1 : 0


27

28 Edge b/w vertex 3 and 2 : 0


29

30 Edge b/w vertex 3 and 3 : 0


31

32 Edge b/w vertex 3 and 4 : 0


33

34 Edge b/w vertex 3 and 5 : 1


35

36 Edge b/w vertex 4 and 1 : 0


37

38 Edge b/w vertex 4 and 2 : 0


39

40 Edge b/w vertex 4 and 3 : 1


41

42 Edge b/w vertex 4 and 4 : 0


43

Dept of CSE, SNPSU - CPP 51


CHAPTER 15. GRAPH USING ADJACENCY MATRIX

44 Edge b/w vertex 4 and 5 : 0


45

46 Edge b/w vertex 5 and 1 : 0


47

48 Edge b/w vertex 5 and 2 : 0


49

50 Edge b/w vertex 5 and 3 : 0


51

52 Edge b/w vertex 5 and 4 : 0


53

54 Edge b/w vertex 5 and 5 : 0


55

56 The adjacency matrix of the entered graph is :


57 1 1 0 1 0
58 0 0 1 0 0
59 0 0 0 0 1
60 0 0 1 0 0
61 0 0 0 0 0
62 ***************************************/
Listing 15.2: OUTPUT

Dept of CSE, SNPSU - CPP 52

You might also like