UG - BCA - Computer Applications - 101 14 - Lab C and Data Structure
UG - BCA - Computer Applications - 101 14 - Lab C and Data Structure
B.C.A.
I - Semester
101 14
Author
Dr. Kavita Saini, Assistant Professor, School of Computer Science & Engineering, Galgotias University, Greater Noida.
All rights reserved. No part of this publication which is material protected by this copyright notice
may be reproduced or transmitted or utilized or stored in any form or by any means now known or
hereinafter invented, electronic, digital or mechanical, including photocopying, scanning, recording
or by any information storage or retrieval system, without prior written permission from the Alagappa
University, Karaikudi, Tamil Nadu.
Information contained in this book has been published by VIKAS® Publishing House Pvt. Ltd. and has
been obtained by its Authors from sources believed to be reliable and are correct to the best of their
knowledge. However, the Alagappa University, Publisher and its Authors shall in no event be liable for
any errors, omissions or damages arising out of use of this information and specifically disclaim any
implied warranties or merchantability or fitness for any particular use.
Work Order No. AU/DDE/DE1-238/Preparation and Printing of Course Materials/2018 Dated 30.08.2018 Copies - 500
LAB: C AND DATA STRUCTURE
Self-Instructional
4 Material
SYSTEM / SOFTWARE REQUIREMENTS Lab: C and Data Structure
You can use Turbo C++ compiler to run a C program only you need to save the
source file with the .C extension instead of .CPP. Following are the system
requirements to run a compolier. NOTES
1. Intel based desktop PC of 166MHz or faster processor with at least
64 MB RAM and 100 MB free disk space.
2. Turbo C++ compiler or GCC compilers
In this manual, we have used Turbo C++. To write C code first we need to
open Turbo C++.
For every C program we need to follow following steps:
Write a program code save your program (F2) compile (Alt+F9)
Run(Ctrl +F9)
Step 1:
Click on Turbo C++ from start menu or double click on Turbo C++ on desktop
Self-Instructional
Material 1
Lab: C and Data Structure Step 2:
Click on Start Turbo C++. After clicking on Start Turbo C++ button following
screen will appear:
NOTES
Self-Instructional
2 Material
Lab: C and Data Structure
Step 4:
Save program by pressing F2 key or by using menu option File->Save As.
NOTES
Step 5:
Compile program Hello.C by pressing Alt+F9 keys or by using menu option
Compile-> Compile.
Self-Instructional
Material 3
Lab: C and Data Structure Step 6:
Run program Hello.C by pressing Ctrl +F9 keys or by using menu option Run->
Run.
NOTES
Output:
Programs:
1. Write a program to print sum and average of two given numbers.
#include<iostream.h>
#include<stdio.h>
void main()
{
int num1,num2,sum,avg;
sum = num1+num2;
Self-Instructional
4 Material
avg = sum/2; Lab: C and Data Structure
}
Output:
Enter two numbers
3
4
Values after swapping :
Value of a num1 4
Value of a num2 3
Self-Instructional
Material 5
Lab: C and Data Structure
Try yourself:-
(i) Write a program to calculate volume of cylinder.
NOTES Volume of cylinder= PI*r*r*h
(ii) Write a program to calculate curved surface area of cylinder.
Curved surface area of cylinder= 2*PI*r*h
(iii) Write a program to print ASCII value of digits, uppercase and lowercase
alphabets.
}
else
{
printf(“Number is odd”);
}
}
Output:
4. Write a program to print the largest number among three numbers given by
the user.
// program to print the largest number among three numbers
#include <stdio.h>
void main()
{
Self-Instructional int num1,num2,num3;
6 Material
Lab: C and Data Structure
printf (“Enter three numbers”);
scanf (“%d%d%d”,&num1,&num2,&num3);
NOTES
if (num1 >= num2 && num1 >= num3)
{
printf (“Largest number: %d”,num1);
else
{
printf (“Largest number: %d”,num3);
}
}
Output:
Try yourself:-
(1) Write a program to convert a lowercase alphabet to uppercase or vice-
versa.
(2) Write a program to check whether a year is leap year or not.
(3) Write a program to check whether a given character is uppercase or
lowercase alphabet or a digit or a special character.
void main()
{
int num, i;
printf (“Enter a numbers: “);
scanf (“%d”,&num);
printf (“Table of %d\n”,num);
for (i=1;i<=10;i++)
{
Self-Instructional
8 Material
printf (“%d\n”,num*i); Lab: C and Data Structure
}
}
NOTES
Output:
}
Output:
Self-Instructional
Material 9
Lab: C and Data Structure 8. Write a program to check whether a given number is Armstrong.
A number is known as Armstrong number if sum of the cubes of its digits is
equal to the number itself.
NOTES For example:
370 is an Armstrong number because:
370 = 33+ 73+ 03
= 27 + 343 + 0
= 370
// C Program to check Armstrong Number
#include<iostream.h>
#include <stdio.h>
void main()
{
int num, sum = 0, rem, temp;
printf (“Enter a number: “);
scanf (“%d”,&num);
temp = num;
while (num>0)
{
rem = num%10;
sum = sum+(rem*rem*rem);
num = num/10;
}
if (temp==sum)
printf (“Given number is armstrong\n “);
else
printf (“Given number is not armstrong\n “);
}
Output:
Enter a number: 370
Given number is armstrong
9. Write a program to print table of any number using do while loop.
//C program to print table of any number using do while
loop
#include<iostream.h>
#include <stdio.h>
void main()
{
Self-Instructional
10 Material
int num, i; Lab: C and Data Structure
printf (“Enter a number: “);
scanf (“%d”,&num);
printf (“\n Table of %d”,num);
NOTES
i=1;
do
{
printf (“\n %d”,num*i);
i++;
}while(i<=10);
}
Output:
Try yourself:-
(1) Write a program to reverse a number.
(2) Write a program to check whether a number is prime number or not.
(3) Write a program to convert binary number to decimal number.
return (fibonacci(n-1)+fibonacci(n-2));
//recursive call of fibonacci function
}
}
int main()
{
int n, i;
Self-Instructional
12 Material
printf (“Enter number of terms for Fibonacci Series:”); Lab: C and Data Structure
scanf (“%d”, &n);
printf (“Fibonacci Series \n”);
NOTES
for (i=0; i< n;i++)
{
printf (“ %d “,fibonacci(i));
}
return 0;
}
Output:
Try yourself:-
(1) Write a program that uses a recursive function to find the binary equivalent
of a given non-negative integer n.
(2) Write a programs functions to find the GCD of two given integers using
recursive function.
int arr[5], i;
printf (“Enter 5 numbers:\n “);
for (i=0;i<5;i++)
scanf (“%d”,&arr[i]);
printf (“\n Array values are \n”);
for (i=0;i<5;i++)
printf (“%d \n”,arr[i]);
}
Self-Instructional
Material 13
Lab: C and Data Structure Output:
NOTES
int arr[5],i,max;
printf (“Enter 5 numbers:\n “);
for (i=0;i<5;i++)
scanf (“%d”,&arr[i]);
max = arr[0];
for (i = 1;i < 5; i++)
{
if (max < arr[i])
max = arr[i];
}
printf (“Largest element = %d” ,max);
}
Output:
14. Write a program that takes string as input and print it.
#include <stdio.h>
#include <conio.h>
Self-Instructional
14 Material
void main() Lab: C and Data Structure
{
char str[15];
printf (“Enter your name: “);
NOTES
scanf (“%s”,str);
printf (“\nWelcome %s “,str);getch();
}
15. Write a program to print length of a given string without using string
functions.
//C program to count string length
#include<stdio.h>
void main( )
{
int i,count=0;
char str[50];
printf (“Enter any string “);
int main( )
{
int i,len=0;
char str[50],rev_str[50]; Self-Instructional
Material 15
Lab: C and Data Structure
printf (“Enter any string “);
gets (str); //gets function allows user to input string
with space
NOTES
//count length of string
for (i = 0; str[i] != ‘\0’; i++)
{
len++;
}
int j=0;
for (i = len - 1; i >= 0 ; i—,j++)
{
rev_str[j] = str[i];
}
rev_str[j] =’\0'; //reverse string is terminated
if (flag == 1)
printf(“ \nstring is a palindrome”);
else
printf(“ \nstring is a not palindrome”);}
Output:
Self-Instructional
16 Material
Lab: C and Data Structure
Try yourself:-
(1) Write a program to insert an element in an array.
(2) Write a program to find sum of elements of an array. NOTES
(3) Write a program to find largest number from an array.
}
}
int main()
{
Self-Instructional
18 Material
Lab: C and Data Structure
}
}
NOTES
printf (“\nEnter the elements of second matrix\n”);
for ( i = 0 ;i < 3; i++ )
{
printf (“\n enter values for row %d \n”,i+1);
for ( j = 0 ; j< 3 ; j++ )
{
scanf (“%d”,&m2[i][j]);
}
}
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 3; ++j)
{
res[i][j]=0;
}
}
printf (“Multiplication of two matrices \n”);
for ( i = 0 ;i < 3 ; i++ )
{
for ( j = 0 ; j<3 ; j++ )
{
}
printf (“\n”);
}
Self-Instructional
Material 19
Lab: C and Data Structure Output:
NOTES
Try yourself:-
(1) Write a program to print sum of diagonal values of a square Matrix.
(2) Write a program to find largest and smallest element of a Matrix.
(3) Write a program to convert first letter of each word of a string to uppercase
and other to lowercase.
(4) Write a program to find substring in string (pattern matching).
Mode Description
r Opens a file in read mode and returns null if file does not exist
w Opens a file in write mode. NOTES
a Opens a file in append mode
a+ Opens a file for read and write mode.
File *fptr;
fptr = (fopen(“d:\\student.txt”, “w”));
if (fptr == NULL)
{
printf (“Can’t open file”);
fclose (fptr);
} Self-Instructional
Material 21
Lab: C and Data Structure Output:
NOTES
void main()
{
int arr[5],i,*ptr;
ptr = arr; //ptr pointer is holding address of arr[0]
element.
printf (“Enter 5 numbers:\n “);
for (i=0;i<5;i++)
scanf (“%d”,&arr[i]);
printf (“\n Array values using pointer \n”);
for (i=0;i<5;i++)
printf (“%d\n”,*(ptr + i)); //*(ptr+i) will print array
values
}
21. Write a program to input and print student data using structure.
//C program to input and print student data using structure
#include<stdio.h>
//student structure
struct student
{
int rno;
char name[10];
};
Self-Instructional
22 Material
int main() Lab: C and Data Structure
{
struct student obj;
//input values
NOTES
printf (“\n enter student roll number :”);
scanf (“%d”,&obj.rno);
printf (“\n enter student name :”);
scanf (“%s”,&obj.name);
//display values
printf (“\n roll number : %d “,obj.rno);
printf (“\n Name: %s”, obj.name);
}
Output:
22. Write a program to input and print student data using structure array.
//C program to input and print student data using structure
array
#include<stdio.h>
//student structure
struct student
{
int rno;
char name[10];
};
int main()
{
int i;
struct student obj[5]; // structure object as an array
Self-Instructional
Material 23
Lab: C and Data Structure printf (“\n enter student roll number and name :”);
for (i=0;i<5;i++)
{
printf (“\n Roll number :”);
NOTES
scanf (“%d”,&obj[i].rno);
printf (“\n Name :”);
scanf (“%s”,&obj[i].name);
}
//display values
printf (“\n student roll number and name \n”);
for (i=0;i<5;i++)
{
printf (“\n Roll number\t: %d “,obj[i].rno);
printf (“\n Name \t: %s”, obj[i].name);
}
}
Output:
Self-Instructional
24 Material
23. Write a program to input and print student data using pointer object Lab: C and Data Structure
of structure.
//C program to input and print student data using pointer
object of structure.
#include<iostream.h> NOTES
#include<stdio.h>
//student structure
struct student
{
int rno;
char name[10];
};
int main()
{
struct student obj,*ptr;
//input values
printf (“\n enter student roll number :”);
scanf (“%d”,&obj.rno);
printf (“\n enter student name :”);
scanf (“%s”,&obj.name);
}
Output:
Union is a user defined data type similar to structure but in union, all members
share the same memory location.
In the example given below, both a and b share the same location, if we
change a, we can see the changes being reflected in b.
Self-Instructional
Material 25
Lab: C and Data Structure 24. Write a program to illustrate the concept of union.
//C program to demonstrate union
#include<iostream.h>
#include <stdio.h>
NOTES
// union
union number
{
int a, b;
};
void main()
{
// A union object obj
union number obj;
obj.a=10;
printf (“value of a and b after initializing value to a
only\n”);
printf (“value of a and b = %d \n value of b = %d”,obj.a,
obj.b);
}
Output:
Stack is a linear data structure which has LIFO (Last in First Out) property.
It contains only one pointer known as TOP that points top most element of Stack.
In stack insertion and deletion is allowed only from top. Where insertion in stack
is also known as a PUSH operation and deletion from stack is also known as POP
operation in stack.
Self-Instructional
26 Material
Stack Implementation Lab: C and Data Structure
Operations on Stack:
(i) Push ( ) operation insert an item to the top of stack.
(ii) Pop ( ) operation deletes an item from the top of stack
Applications of Stack
(i) Conversion of infix expression into Prefix expression
(ii) Conversion of infix expression into Postfix expression
(iii) Evaluation of Postfix expression
(iv) Tower or Hanoi
(v) Recursion
Array Implementation of Stack
Algorithm: To PUSH value in stack using array.
Description:
Here Stack is an array where we will PUSH and POP values.
MAX is a constant used to define maximum limit of
TOP is the top most element of Stack where insertion and deletion is allowed
DATA is data to be inserted in Stack
PUSH (Stack, Top, Data)
Algorithm to push an item on to stack.
1. IF TOP = MAX then
2. Write: “Stack is overflow”
3. Exit
4. Else
[increment TOP by 1]
5. Set TOP = TOP + 1
6. Set STACK [TOP]= DATA
[End of IF STRUCTURE]
7. END
Self-Instructional
Material 27
Lab: C and Data Structure Algorithm: To POP value from stack using array.
Description:
Here Stack is an array where we will PUSH and POP values.
NOTES
TOP is the top most element of Stack where insertion and deletion is allowed
DATA is deleted data
POP (Stack, Top)
Algorithm to push an item into stack.
1. IF TOP = 0 then
2. Write: “Stack is underflow”
3. Exit
4. Else
5. Set DATA = STACK [TOP]
[decrease TOP by 1]
6. Set TOP = TOP- 1
[End of IF STRUCTURE]
7. END
25. Write a C Program to implement Stack using Array.
#include <stdio.h>
#define MAX 5
int top=-1;
int ele[MAX];
//PUSH function
top++;
ele [top] = item;
Self-Instructional
28 Material
Lab: C and Data Structure
printf (“\n Inserted value is : %d”,item);
}
}
NOTES
//POP function
int pop( )
{
int item;
if ( top==-1 )
{
printf (“\nStack Underflow”);
}
else
{
item = ele[top];
top—;
}
return item;
}
//DISPLAY function
void display ()
{
if ( top==-1 )
{
printf (“\nStack Underflow”);
}
else
{
int i;
printf (“Stack value are \n”);
for (i=top;i>=0;i—)
printf (“%d \n”,ele[i]);
}
}
Self-Instructional
Material 29
Lab: C and Data Structure
void main ()
{
int item = 0, choice, value; char ans;
NOTES
do
{
switch (choice)
{
case 1:
printf (“Enter the value to be insert: “);
scanf (“%d”,&value);
push (value);
break;
case 2:
value = pop();
printf (“\nDeleted value is %d “,value);
break;
case 3:
display ();
break;
case 4:
exit(0);
default:
printf (“Invalid choice”);
}
Self-Instructional
30 Material
Output: Lab: C and Data Structure
NOTES
Self-Instructional
Material 31
Lab: C and Data Structure 6. If a right parenthesis is encountered ,then:
(i) Repeatedly pop from Stack and add to P each operator (on the top of
Stack) until a left parenthesis is encountered.
NOTES (ii) Remove the left Parenthesis.
[End of If]
[End of If]
7. END.
26. Write a program to convert infix expression to postfix expression
using stack.
//C program to convert infix expression to postfix
expression
#include<stdio.h>
#include <ctype.h>
#define SIZE 50
char s[SIZE];
int top=-1;
//push Function
void push(char elem)
{
s[++top]=elem;
}
//pop function
char pop()
{
return (s[top—]);
}
// precedence function
int pr(char elem)
{
switch (elem)
{
case ‘#’: return 0;
case ‘(‘: return 1;
case ‘+’:
case ‘-’: return 2;
case ‘*’:
Self-Instructional case ‘/’: return 3;
32 Material
} Lab: C and Data Structure
}
//main function
void main()
NOTES
{
char infx[50],pofx[50],ch,elem;
int i=0,k=0;
printf (“\n\n Enter the Infix Expression (Ex. A+B-2) “);
scanf (“%s”,infx);
push (‘#’);
while ( (ch=infx[i++]) != ‘\0’)
{
if ( ch == ‘(‘) push(ch);
else
if (isalnum(ch)) pofx[k++]=ch;
else
if ( ch == ‘)’)
{
while ( s[top] != ‘(‘)
pofx [k++]=pop();
elem = pop(); /* Remove ( */
}
else
{ /* Operator */
while ( pr(s[top]) >= pr(ch) )
pofx [k++]=pop();
push (ch);
}
}
// Pop from stack till empty
while ( s[top] != ‘#’)
pofx [k++]=pop();
pofx [k]=’\0';
printf (“\n\n Infix Expn: %s \n Postfix Expn: %s\n”,
infx, pofx);
}
Output:
Self-Instructional
Material 33
Lab: C and Data Structure Algorithm: To evaluate postfix expression using stack.
Description:
Here P is an arithmetic expression written in postfix expression.
NOTES
Stack is an array where we will PUSH all the operands and final value.
TOP is the top most element of Stack where insertion and deletion is allowed
1. Add a Right Parenthesis “)” at the end of P postfix expression.
2. Scan P from left to right and repeat Step 3 to 4 for each element of P until
“)” is encountered.
3. If an operand is encountered, add it to stack.
4. If an operator * is encountered, then
(i) Remove two TOP elements of the stack where A is the TOP and B is
the TOP-1 element.
(ii) Evaluate B * A.
(iii) Place the result of step (b) on to stack.
5. Set value equal to TOP element on stack.
6. Exit
27. Write program to evaluation of postfix expressions using stack.
//C program to evaluate postfix expressions using stack.
#include<stdio.h>
#include<ctype.h>
int stack[20];
int top = -1;
void push(int x)
{
stack [++top] = x;
}
int pop()
{
return stack[top—];
}
int main()
{
char exp[20];
Self-Instructional
34 Material
char *e; Lab: C and Data Structure
int n1,n2,n3,num;
printf (“Enter the expression :: “);
scanf (“%s”,exp);
NOTES
e = exp;
while (*e != ‘\0’)
{
if (isdigit(*e))
{
num = *e - 48;
push (num);
}
else
{
n1 = pop ();
n2 = pop ();
switch (*e)
{
case ‘+’:
{
n3 = n1 + n2;
break;
}
case ‘-’:
{
n3 = n2 - n1;
break;
}
case ‘*’:
{
n3 = n1 * n2;
break;
}
case ‘/’:
{
n3 = n2 / n1;
break;
}
}
push (n3);
Self-Instructional
Material 35
Lab: C and Data Structure }
e++;
}
printf (“\n The result of expression %s = %d\n\n”, exp,
NOTES pop());
}
Output:
ELSE
SET NEXT [NEW] = TOP
[END OF IF]
SET DATA [TOP] = INFO
SET TOP = NEW
[END OF IF]
3 END
Algorithm: To pop value from stack using linked list.
Description:
Here TOP is the Top node of Stack to be deleted.
TEMP is name given to the node to be deleted from the list.
Self-Instructional
36 Material
POP_STACK (TOP) Lab: C and Data Structure
1. [UNDERFLOW?]
IF TOP = NULL THEN
WRITE: UNDER FLOW
NOTES
EXIT
2. ELSE
SET INFO = DATA [TOP]
SET TEMP = TOP
SET TOP =NEXT [TOP]
DELETE TEMP
[END OF IF]
3. END
28. Write a program for stack implementation using linked list.
//C program for stack implementation using linked list
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*top,*curr,*temp;
NOTES
// Pop Operation on stack
void pop()
{
curr = top;
if (curr == NULL)
{
printf (“\nStack is empty”);
return;
}
else
curr = curr->ptr;
printf (“\n Popped value : %d”, top->info);
free(top);
top = curr;
if (curr == NULL)
{
printf (“Stack is empty”);
return;
}
do
{
printf (“\n Enter choice : “);
scanf (“%d”, &ch);
switch (ch)
{
case 1:
printf (“Enter data : “);
scanf (“%d”, &no);
push (no);
break;
case 2:
pop ();
break;
case 3:
display ();
break;
case 4:
exit(0);
Self-Instructional
Material 39
Lab: C and Data Structure Output:
NOTES
Try yourself:-
(1) Write a program to solve Towers of Hanoi problem using a recursive
function.
(2) Write a program to convert infix expression to prefix expression.
IF (FRONT=0) THEN
WRITE “QUEUE IS EMPTY”
ELSE
ITEM=QUEUE [FRONT]
IF (FRONT=REAR) THEN
REAR=0
FRONT=0
Self-Instructional
40 Material ELSE
FRONT=FRONT+1 Lab: C and Data Structure
END IF
END IF
EXIT
NOTES
29. Write a program to implement queue using array.
//Program to implement queue using array
#include <stdio.h>
#define MAX 50
int queue[MAX];
int rear = - 1;
int front = - 1;
if (rear == MAX - 1)
printf (“Queue Overflow \n”);
else
{
if (front == - 1)
front = 0;
rear = rear + 1;
queue [rear] = data;
}
}
NOTES
else
{
data = queue[front];
front = front + 1;
}
//display function
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[i]);
printf (“\n”);
}
}
//main function
void main()
{
int choice, item;
char ans;
do
{
}
Output:
Self-Instructional
Material 43
Lab: C and Data Structure 30. Write a program to implement circular queue using array.
//Program to implement queue using array
#include <stdio.h>
NOTES
#define MAX 5
int queue[MAX];
int rear = - 1;
int front = - 1;
//display function
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 \n “, queue[i]);
}
}
if (front>rear)
Self-Instructional
Material 45
Lab: C and Data Structure {
for (i=front;i<MAX;i++)
printf (“%d \n “, queue[i]);
NOTES
for (i=0;i<rear;i++)
printf (“%d \n “, queue[i]);
}
}
//main function
void main()
{
int choice, item;
char ans;
do
{
Self-Instructional
46 Material
Output: Lab: C and Data Structure
NOTES
struct node
{
int info;
struct node *next;
}*front,*rear,*temp,*curr;
if (curr == NULL)
{
printf (“\n Error: Trying to display elements from empty
queue”);
return;
}
else
if (curr->next != NULL)
{
curr = curr->next;
printf(“\n Dequed value : %d”, front->info);
free(front);
front = curr;
}
else
{
printf (“\n Dequed value : %d”, front->info);
free (front);
front = NULL;
rear = NULL;
}
Self-Instructional
48 Material
Lab: C and Data Structure
// Displaying queue
void display()
NOTES
{
curr = front;
}
while (curr != rear)
{
printf (“%d “, curr->info);
curr = curr->next;
}
if (curr == rear)
printf (“%d”, curr->info);
}
void main()
{
int data, ch, e;
char ans;
front = rear = NULL;
do
{
printf (“\n 1. Insert \n 2. Delete \n 3. Display \n 4.
Exit \n”);
Self-Instructional
Material 49
Lab: C and Data Structure enqueue (data);
break;
case 2:
dequeue ();
NOTES
break;
case 3:
display ();
break;
case 4:
exit(0);
default :
printf (“ Invalid choice “);
break;
}
printf (“\n do you want to cont...(Y/N)”);
scanf (“%s”, &ans);
} while (ans==’y’ || ans==’Y’);
}
Output:
Self-Instructional
50 Material
Lab: C and Data Structure
Try yourself:-
(1) Write a program to implement circular queue using linked list.
(2) Write a program to implement priority queue. NOTES
32. Write a program to insert node at the beginning of single linked list.
//C program to insert node at the beginning of single
linked list
#include <stdio.h>
#include <stdlib.h>
if (start == NULL)
{
start =end= temp;
end->next=NULL;
}
else
{
temp->next = start;
start=temp;
}
}
Self-Instructional
Material 51
Lab: C and Data Structure //Function to traversal/print single linked list
void traversal()
{
if (start == NULL)
NOTES
{
printf (“Underflow \n”);
}
else
{
curr =start;
while (curr!=NULL)
{
printf (“%d \n “,curr->data);
curr = curr->next;
}
}
}
void main()
{
int d, ch;
char ans;
start = end= NULL;
do
{
printf (“\nEnter value to be inserted “);
scanf (“%d”,&d);
insert_beginning (d);
printf (“\n\nCont...(y/n)”);
scanf (“%s”,&ans);
}while (ans==’y’|| ans==’Y’);
Self-Instructional
52 Material
Output: Lab: C and Data Structure
NOTES
33. Write a program to insert node at the end of single linked list.
//C program to insert node at the end of single linked
list
#include <stdio.h>
#include <stdlib.h>
void insert_end(int d)
{
Self-Instructional
Material 53
Lab: C and Data Structure if (start == NULL)
{
start =end= temp;
end->next=NULL;
NOTES
}
else
{
temp->next = start;
start=temp;
}
}
curr =curr->next;
}
}
}
void main()
{
int d, ch;
char ans;
start = end= NULL;
Self-Instructional
54 Material
do Lab: C and Data Structure
{
printf (“\nEnter value to be inserted “);
scanf (“%d”,&d);
NOTES
insert_beginning (d);
printf (“\n\nCont...(y/n)”);
scanf (“%s”,&ans);
}while (ans==’y’|| ans==’Y’);
}
Output:
struct node
{
struct node *prev;
int data;
struct node *next;
}*start,*end,*temp,*curr;
Self-Instructional
Material 55
Lab: C and Data Structure
//Function to insert at the beginning in double linked
list
if (start == NULL)
{
start =end= temp;
end->next=NULL;
end->prev=NULL;
}
else
{
temp->prev=NULL;
temp->next=start;
start->prev=temp;
start = temp;
}
if (start == NULL)
{
printf (“Underflow \n”);
}
else
{
curr =start;
Self-Instructional
56 Material
while (curr!=NULL) Lab: C and Data Structure
{
printf (“%d \n “,curr->data);
NOTES
curr =curr->next;
}
}
}
curr =curr->prev;
}
}
}
void main()
{
int d, ch;
char ans;
start = end= NULL;
do
{
printf (“\nEnter value to be inserted “);
Self-Instructional
Material 57
Lab: C and Data Structure scanf (“%d”,&d);
insert_beginning (d);
printf (“\n\nCont...(y/n)”);
scanf (“%s”,&ans);
NOTES
}while (ans==’y’|| ans==’Y’);
}
Output:
35. Write a program to insert node at the end of double linked list.
//C program to insert node at the end of double linked
list
#include <stdio.h>
#include <stdlib.h>
struct node
{
struct node *prev;
Self-Instructional
58 Material
int data; Lab: C and Data Structure
struct node *next;
}*start,*end,*temp,*curr;
NOTES
//Function to insert at the end in double linked list
void insert_end (int d)
{
if (start == NULL)
{
start =end= temp;
end->next=NULL;
end->prev=NULL;
}
else
{
end->next=temp;
temp->prev=end;
temp->next=NULL;
end =temp;
}
if (start == NULL)
{
printf (“Underflow \n”);
}
else
Self-Instructional
Material 59
Lab: C and Data Structure {
curr =start;
while (curr!=NULL)
{
NOTES
printf (“%d \n “,curr->data);
curr = curr->next;
}
}
}
curr = curr->prev;
}
}
}
void main()
{
int d, ch;
char ans;
start = end= NULL;
do
{
Self-Instructional
60 Material
printf (“\n Enter value to be inserted “); Lab: C and Data Structure
scanf (“%d”,&d);
insert_end (d);
printf (“\n\nCont...(y/n)”);
NOTES
scanf (“%s”,&ans);
}while (ans==’y’|| ans==’Y’);
}
Output:
Try yourself:-
(1) Write a program to implement circular Linked List.
(2) Write a program to merge two linked lists.
(3) Write a program to sort a linked list.
5. [LEFT CHILD?]
IF LEFT [PTR] ‘“ NULL THEN
Self-Instructional SET PTR: = LEFT [PTR]
62 Material
ELSE Lab: C and Data Structure
SET PTR: = STACK [TOP]
SET TOP: = TOP -1
[END OF IF]
NOTES
[END OF LOOP]
6. END
Algorithm: For post-order traversal
A binary tree t is in memory. This algorithm does postorder traversal of t. An array
stack is used to temporarily old the address of nodes.
POSTORDER _TRAVERSAL (INFO, LEFT, RIGHT, ROOT)
1. [INITIALLY PUSH NULL TO STACK AND INITIALIZE PTR]
SET TOP: =1
SET STACK [1]:=NULL
SET PTR: =ROOT
2. [PUSH LEFT-MOST PATH ONTO STACK ]
REPEAT STEPS 3 TO 5 WHILE PTR ‘“ NULL
3. SET TOP:=TOP+1
SET STACK [TOP]:=PTR
NOTES
#include <stdio.h>
#include <stdlib.h>
root->data = newnode->data;
root->left = NULL;
root->right = NULL;
printf (“Root Node is Added \n”);
return;
}
if (tree->data == newnode->data)
{
printf (“Element already in the tree \n”);
return;
}
if (tree->data > newnode->data)
{
if (tree->left != NULL)
{
Self-Instructional
64 Material
insert (tree->left, newnode); Lab: C and Data Structure
}
else
{
NOTES
tree->left = newnode;
(tree->left)->left = NULL;
(tree->left)->right = NULL;
printf (“Node Added To Left \n”);
return;
}
}
else
{
if (tree->right != NULL)
{
insert(tree->right, newnode);
}
else
{
tree->right = newnode;
(tree->right)->left = NULL;
(tree->right)->right = NULL;
printf (“Node Added To Right \n”);
return;
}
}
}
}
if (ptr != NULL)
Self-Instructional
Material 65
Lab: C and Data Structure {
inorder (ptr->left);
printf (“%d “, ptr->data);
inorder (ptr->right);
NOTES
}
}
int main()
{
Self-Instructional
66 Material
do Lab: C and Data Structure
{
printf (“\n1.Insert Element \n”);
printf (“2.Inorder Traversal \n”);
NOTES
printf (“3.Display Tree Structure \n”);
printf (“4. Exit \n”);
Self-Instructional
Material 67
Lab: C and Data Structure Output:
NOTES
37. Write a program for binary tree insertion and preorder traversal.
//C program for preorder traversal of binary tree
#include <stdio.h>
#include <stdlib.h>
NOTES
root->data = newnode->data;
root->left = NULL;
root->right = NULL;
printf(“Root Node is Added \n”);
return;
}
if (tree->data == newnode->data)
{
printf (“Element already in the tree \n”);
return;
}
if (tree->data > newnode->data)
{
if (tree->left != NULL)
{
insert (tree->left, newnode);
}
else
{
tree->left = newnode;
(tree->left)->left = NULL;
(tree->left)->right = NULL;
printf (“Node Added To Left \n”);
return;
}
}
else
{
if (tree->right != NULL)
{
insert (tree->right, newnode);
}
else
{
tree->right = newnode;
Self-Instructional
Material 69
Lab: C and Data Structure (tree->right)->left = NULL;
(tree->right)->right = NULL;
printf (“Node Added To Right \n”);
return;
NOTES
}
}
}
int main()
{
do
{
printf (“\n1.Insert Element \n”);
printf (“2.Preorder Traversal \n”);
printf (“3.Display Tree Structure \n”);
printf (“4. Exit \n”);
}
Output:
38. Write a program for binary tree insertion and post-order traversal.
//C Program for postorder traversal of binary tree
#include <stdio.h>
#include <stdlib.h>
root->data = newnode->data;
root->left = NULL;
root->right = NULL;
printf (“Root Node is Added \n”);
return;
}
if (tree->data == newnode->data)
{
printf (“Element already in the tree \n”);
return;
}
if (tree->data > newnode->data)
{
if (tree->left != NULL)
{
insert (tree->left, newnode);
}
else
{
tree->left = newnode;
(tree->left)->left = NULL;
(tree->left)->right = NULL;
printf (“Node Added To Left \n”);
return;
}
} Self-Instructional
Material 73
Lab: C and Data Structure else
{
if (tree->right != NULL)
{
NOTES
insert (tree->right, newnode);
}
else
{
tree->right = newnode;
(tree->right)->left = NULL;
(tree->right)->right = NULL;
printf (“Node Added To Right \n”);
return;
}
}
}
}
}
int main()
{
do
{
printf (“\n1.Insert Element \n”);
printf (“2.Postorder Traversal \n”);
printf (“3.Display Tree Structure \n”);
printf (“4. Exit \n”);
}
Output:
Self-Instructional
76 Material
Lab: C and Data Structure
Try yourself:-
(1) Write a program to check whether a tree is a binary search tree.
(2) Write a program to search an element in a tree recursively. NOTES
(3) Write a program for depth first binary tree search using recursion.
(4) Write a program to find the largest value in a tree using inorder traversal.
1. Dijkstra’s Algorithm
Dijkstra’s algorithm maintains a set S of vertices where minimum paths have been
found.
Algorithm: Dijkstra’s algorithm for the single shortest path problem
Procedure: DIJKSTRA_SSSP(N, COST)
/*N is the number of vertices labelled {1,2,3,....N} of the weighted digraph.
COST[1:N,1:N] is the cost matrix of the graph. If there is no edge then COST
[i,j] = “*/
/* The procedure computes the cost of the shortest path from vertex 1 the
source to every other vertex of the weighted digraph*/
for i=2 to N do
DISTANCE[i]= COST [1,i]; /*Initialize DISTANCE vector to the cost
of the end edges connecting vertex i with
the source vertex
if there is no edge then COST[1,i]= “*/
Self-Instructional
Material 77
Lab: C and Data Structure 2. Floyd-Warshall Algorithm
The Floyd-Warshall algorithm works based on a property of intermediate vertices
of a shortest path. An intermediate vertex for a path p = <v1, v2, ..., vj> is any
NOTES vertex other than v1 or vj.
Algorithm
FLOYD-WARSHALL(W)
1. n = W.rows
2. D(0) = W
3. (0) = (0)ij = NIL if i=j or wij =
= i if ij and wij <
4. for k = 1 to n
5. let D(k) = (d(k)ij) be a new nxn matrix
6. for i = 1 to n
7. for j = 1 to n
8. dkij = min(d(k-1)ij, d(k-1)ik + d(k-1)kj)
9. if d(k-1)ij d” d(k-1)ik + d(k-1)kj
10. (k)ij = (k-1)ij
11. else
12. (k)ij = (k-1)kj
13. return D(n)
Basically the algorithm works by repeatedly exploring paths between every
pair using each vertex as an intermediate vertex.
Finding Minimum cost Spanning Trees
1. Kruskal’s Algorithm:
Kruskal’s algorithm is a greedy algorithm. To find out minimum spanning tree
(MST) of a connected and weighted graph we use Kruskal’s algorithm. This means
it finds a subset of the edges to forms a tree including each vertex in such a way
that the total weight of all the edges in the tree is minimal. In case a graph is not a
connected graph it finds a MST connected component and that is a minimum
spanning forest.
This Algorithm finds a minimum spanning tree T of a weighted graph G.
1. Order all the edges of G according to increasing weights
2. Initialize T to be a graph consisting of same nodes as G and no edges.
3. Repeat the following M-1 times, Where M is the number of nodes in G:
Add to T an Edge E of G with minimum weight such
that E does not form a cycle in T.
End of Loop
4. End of Loop
Self-Instructional
78 Material
2. Prims Algorithm Lab: C and Data Structure
E‘= ²”;
Select a minimum cost edge (u,v) from E;
V‘= {u} /*Include u in V’ */
while V‘!= V do
Let (u,v) be the lowest cost edge such that u is in V‘ and v is in V –V‘
Add edge (u,v) to set E’;
Add v to set V‘;
End while
end PRIM
Graph traversing Methods
1. Breadth First Search(BFS)
2. Depth First Search(DFS)
Algorithm for BFS (Breadth First Search)
This Algorithm executes a breadth first search on a graph G beginning at a starting
node A
1. [Initialize all nodes to the ready state]
Set status: =1
2. Put the starting node A in Queue and change its status to the
Set status: =2
3. Repeat steps 4 and 5 until Queue is Empty:
4. Remove the front node N of Queue process N and change the status of N
to the processed
State.
Set status: =3
Self-Instructional
Material 79
Lab: C and Data Structure 5. Add to the rear of Queue all the neighbors of N that are in the ready state
(state=1), and
Change their status to the waiting state
Set status: =2
NOTES
[End of step 3 loop]
End
Algorithm for DFS (Depth First Search)
This algorithm executes a Depth First Search on a graph G beginning A
1. [initialize all nodes to the ready state ]
Set status: =1
2. Push the starting node A onto stack and change its status to the waiting
state
Set status: =2
3. Repeat step 4 and 5 until stack is empty
4. Pop the top node N of stack. process N and change its status to the
processed state
Set status: =3
5. Push onto stack all the neighbors of N that are still in the ready state
(status=1),and change their status to the waiting state
Set status: =2
[End of step 3 loop]
6. End
Searching and Sorting Algorithms
Searching refers to the operation of finding the location of a given item in a collection
of items.
Algorithm: For sequential search
INPUT : LIST OF SIZE N, TARGET VALUE T
OUTPUT : POSITION OF T IN THE LIST
1. BEGIN
2. SET FOUND: = FALSE
SET I: = 0
3. WHILE Id”N AND FOUND IS FALSE
IF LIST [I] = T THEN
SET FOUND: = TRUE
EXIT
ELSE
SET I: =I+1
Self-Instructional
80 Material [END OF STEP 3 LOOP]
4. IF FOUND = FALSE THEN Lab: C and Data Structure
#include <stdio.h>
NOTES
Self-Instructional
82 Material
40. Write a C program for binary search. Lab: C and Data Structure
#include <stdio.h>
NOTES
// Binary Search Function
void binary_search (int a[ ] , int size , int key)
{
int low ,high ,mid ,flag ;
flag= 0;
low = 0;
high = size -1;
while (low <= high && flag ==0)
{
mid =(low +high)/2;
if ( key == a [mid])
{
flag=1;
break;
}
else if (key < a[mid ] )
{
high = mid -1;
}
else
{
low = mid +1;
}
}
if ( flag ==1)
{
printf (“value found at %d location “, mid +1);
}
else
printf (“value not found “);
}
void main()
{
int arr[10],i,k;
printf (“Enter 10 values\n”; Self-Instructional
Material 83
Lab: C and Data Structure for(i=0;i<10;i++)
scanf(“%d”,arr[i]);
printf (“Enter value to be searched “);
scanf(“%d”,k);
NOTES
//call of binary_Search function
binary_search(arr,10,k);
}
Output:
Sorting refers to the operation of arranging data in some given order such as
increasing or decreasing with numerical data and alphabetically with character
data.
Selection Sort
Selection sort algorithm starts by comparing first two elements of an array and
swapping if necessary.
This algorithm is not suitable for large data sets as its average and worst
case complexities are of O(n2), where n is the number of items.
41. Write a program to sort an array using selection sort.
//C program for selection sort
#include <stdio.h>
void selection_sort (int a[ ], int size )
{
int temp ,i,j, min;
}
}
//main function
void main()
{
int arr[10],i;
cout<<“Enter 10 values\n”;
for(i=0;i<10;i++)
cin>>arr[i];
Self-Instructional
Material 85
Lab: C and Data Structure 42. Write a program to sort an array using bubble sort.
//C program for bubble sort
#include <stdio.h>
void bubble_sort (int a[ ], int size )
NOTES
{
int temp ,i,j;
for(i=0; i<size; i++)
{
for(j=0; j<size-1; j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
} }
}
}
/main function
void main()
{
int arr[10],i;
printf(“Enter 10 values\n”);
for(i=0;i<5;i++)
scanf(“%d”,arr[i]);
Self-Instructional
86 Material
Output: Lab: C and Data Structure
NOTES
Self-Instructional
Material 87
Lab: C and Data Structure 43. Write a program to sort an array using insertion sort.
//C program for insertion sort Search
#include <stdio.h>
NOTES
}
}
//main function
void main()
{
int arr[10],i,k;
printf(“Enter 10 values\n”);
for(i=0;i<5;i++)
scanf(“%d”,arr[i]);
Self-Instructional }
88 Material
Output: Lab: C and Data Structure
NOTES
Self-Instructional
Material 89
Lab: C and Data Structure 44. Write a program to sort an array using quick sort.
//C program for quick sort
#include <stdio.h>
NOTES
do
{
while (a[low]<pivot)
{
low ++;
}
while (a [high]>pivot)
{
high—;
}
if (low <=high)
{
temp = a [low];
a [low]= a[high];
a [high]= temp ;
low++;
high—;
}
if (first <high)
{
quick_sort (a, first, high);
}
if(low< last)
Self-Instructional
90 Material
{ Lab: C and Data Structure
quick_sort (a, low, last);
}
}
NOTES
//main function
void main()
{
int arr[10],i,k;
printf (“Enter 10 values\n”);
for (i=0;i<10;i++)
scanf (“%d”,arr[i]);
Self-Instructional
Material 91
Lab: C and Data Structure Algorithm: For shell sort
ALGORITHM _ SHELL SHORT
INPUT_ LIST OF N ELEMENTS
NOTES OUTPUT_ LIST OF N ELEMENTS IN ASSENDING ORDER
SHELL_ SORT (LIST, SIZE)
1. [INITIALIZE]
SET GAP: = N/2
2. REPEAT THROUGH STEP 6 WHILE GAP =0
SET SWAP: = 0
4. REPEAT THROUGH STEP 6 WHILE SWAP=1
5. REPEAT THROUGH STEP 6 FOR I=1, 3 ...I< (N-GAP)
6. IF (LIST [I] > LIST [I+ GAP]) THEN
SET LIST [I] = LIST [I+ GAP]
SET SWAP: = 1
[END OF FOR LOOP]
[END OF INNER WHILE LOOP]
[END OF OUTER WHILE LOOP]
7. END
45. Write a program to implement shell sort.
//C program for shell sort
#include <stdio.h>
void shell_sort (int a[ ], int size )
{
int temp , gap ,i ,swap ;
gap = size /2 ;
do
{
do
{
swap =0;
for ( i=0 ; i < size-gap ; i ++)
{
if(a[i] > a[ i+ gap])
{
temp = a[i] ;
a[i] = a [i+ gap];
a[ i+ gap]= temp;
Self-Instructional
92 Material
swap=1; Lab: C and Data Structure
}}
}while ( swap ==1);
gap= gap/2 ;
NOTES
}while (gap >0) ;
}
//main function
void main()
{
int arr[10],i,k;
printf (“Enter 10 values\n”);
for(i=0;i<10;i++)
scanf(“%d”,arr[i]);
//call of shell sort function
shell_sort(arr,10);
Self-Instructional
Material 93
Lab: C and Data Structure 46. Write a program to implement merge sort.
//C program for merge sort
#include <stdio.h>
NOTES
void main()
{
int arr[10],i,k;
printf (“Enter 10 values\n”);
for (i=0;i<10;i++)
scanf (“%d”,arr[i]);
Self-Instructional
Material 95
Lab: C and Data Structure //call of merge sort function
merge_sort (arr, 0, 9);
Self-Instructional
96 Material