0% found this document useful (0 votes)
9 views

Data structures lab

The document contains multiple C programs demonstrating various algorithms and techniques, including finding GCD using recursion, printing Pascal's triangle, computing Fibonacci numbers, and implementing sorting algorithms like selection sort, bubble sort, and quick sort. It also includes programs for file operations, such as writing odd and even numbers to different files, and managing student records using structures. Additionally, it covers searching algorithms like linear and binary search.

Uploaded by

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

Data structures lab

The document contains multiple C programs demonstrating various algorithms and techniques, including finding GCD using recursion, printing Pascal's triangle, computing Fibonacci numbers, and implementing sorting algorithms like selection sort, bubble sort, and quick sort. It also includes programs for file operations, such as writing odd and even numbers to different files, and managing student records using structures. Additionally, it covers searching algorithms like linear and binary search.

Uploaded by

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

// 1.

C Program To
Find GCD of Two
Number Using
Recursion

#include<stdio.h>
int GCD(int x, int y);
int main(){
int a, b; // Asking for Input
printf("Enter Two Positive Integers: \n");
scanf("%d\n %d", &a, &b);
printf("GCD of %d and %d is %d.", a, b, GCD(a, b));
return 0;
}
int GCD(int x, int y){
if( y != 0)
return GCD(y, x % y);
else
return x;
}

//2. C Program to
Print Pascal
Triangle

#include < stdio.h >


long factorial(int);
int main()
{
int i, n, c;
printf("Enter the number of rows you wish to see in pascal triangle\n");
scanf("%d", & n);
for (i = 0; i < n; i++) {
for (c = 0; c <= (n - i - 2);
c++) printf(" ");
for (c = 0; c <= i; c++)
printf(" %ld ", factorial(i) / (factorial(c) * factorial(i - c)));
printf("\n");
}
return 0;
}
long factorial(int n) {
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result * c;
return result;
}

// 3. C Program To
Compute Fibonacci
numbers using
recursion method
#include<stdio.h>
int Fibonacci(int);
int main() {
int n, i = 0, c;
scanf("%d",&n);
printf("Fibonacci series\n");
for ( c = 1 ; c <= n ; c++ ) {
printf("%d\n", Fibonacci(i));
i++;
}
return 0;
}

int Fibonacci(int n) {
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}

//4. C program for


Tower of Hanoi
using Recursion

#include <stdio.h>
void towers(int, char, char, char);

int main() {
int num;
printf("Enter the number of disks : ");
scanf("%d", &num);
printf("The sequence of moves involved in the Tower of Hanoi are :\n");
towers(num, 'A', 'C', 'B');
return 0;
}
void towers(int num, char frompeg, char topeg, char auxpeg) {
if (num == 1){
printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg);
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}
// 5. C program to
find the largest and
smallest element in
a one-dimensional
(1-D) array

#include<stdio.h>

int main()
{
int a[50],i,n,large,small;
printf("How many elements:");
scanf("%d",&n);
printf("Enter the Array:");

for(i=0;i<n;++i)
scanf("%d",&a[i]);
large=small=a[0];
for(i=1;i<n;++i)
{ if(a[i]>large)
large=a[i];
if(a[i]<small)
small=a[i];
}
printf("The largest element is %d",large);
printf("\nThe smallest element is %d",small);

return 0;
}

Output:
How many elements:5
Enter the Array:1 8 12 4 6
The largest element is 12
The smallest element is 1

------------------------------------------------------------------------------------------------------------------------

//6. C Program To
Write Odd And
Even Numbers Into
Different Files
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp,*fp1,*fp2;
int c,i;
clrscr(); fp=fopen("data.txt","w"); printf("enter the numbers");
for(i=0;i<10;i++)
{
scanf("%d",&c); putw(c,fp);
}
fclose(fp); fp=fopen("data.txt","r");
fp1=fopen("even.txt","w");
fp2=fopen("odd.txt","w");
while((c=getw(fp))!=EOF)
{
if(c%2==0) putw(c,fp1);
else
putw(c,fp2);
} fclose(fp); fclose(fp1);
fclose(fp2);
fp1=fopen("even.txt","r");
while((c=getw(fp1))!=EOF)
printf("%4d",c); printf("\n\n");
fp2=fopen("odd.txt","r");
while((c=getw(fp2))!=EOF)
printf("%4d",c);
fcloseall();
}

Output:
Program to separate even and odd numbers in a file
//7. Write a C program to store record of student (stud_no, stud_name, stud_addr, stud_Per)
in a file using structure.
#include<stdio.h>
struct stud
{ int rno;
float per;
char name[20], add[20];
}s;
int main()
{
FILE *fp;
fp=fopen("student.txt","w");
printf("Enter record of student:\n\n");
printf("\nEnter student number : ");
scanf("%d",&s.rno);
printf("\nEnter name of student: ");
scanf("%s",s.name);
printf("\nEnter student address : ");
scanf("%s",s.add);
printf("\nEnter percentage of student : ");
scanf("%f",&s.per);
fprintf(fp,"%d\n%s\n%s\n%f",s.rno,s.name,s.add,s.per);
printf("\nRecord stored in file...");
fclose(fp);
return 0;
}

Output:
------------------------------------------------------------------------------------------------------------------------

//8. Following is the


C program to sort
city names in
alphabetical order

#include<stdio.h>
#include<string.h>
main(){
int i,j,n;
char str[100][100],s[100];
printf("Enter number of names :\n");
scanf("%d",&n);
printf("Enter City names in any order:\n");
for(i=0;i<n;i++){
scanf("%s",str[i]);
}
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(strcmp(str[i],str[j])>0){
strcpy(s,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],s);
}
}
}
printf("\nThe sorted order of names are:\n");
for(i=0;i<n;i++){
printf("%s\n",str[i]);
}
}

Output Enter
number of names:5
Enter names in any order:
Prajwal
Lucky
Sunny
Adisesha
Babloo

The sorted order of names is:


Adisesha
Babloo
Lucky
Prajwal
Sunny

//9. C program to
sort the given list
using selection sort
technique
#include <stdio.h>
void swap(int* xp, int* yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)


{
int i, j, min_idx;

// One by one move boundary of unsorted subarray


for (i = 0; i < n - 1; i++) { // Find the minimum element in unsorted array
min_idx = i;
for (j = i + 1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first element


swap(&arr[min_idx], &arr[i]);
}
}

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Main functions
int main()
{
int arr[] = { 64, 25, 12, 22, 11 };
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

//10.C program
to sort the given
list using
bubble sort
technique
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < n - 1; c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use '<' instead of '>' */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c < n; c++)
printf("%d\n", array[c]);
return 0;
}

Part-B
/* 1. C Program to
sort an array in
ascending order
using Insertion
Sort */
// C program for insertion sort
#include <math.h>
#include <stdio.h>

/* Function to sort an array using insertion sort*/


void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;

while (j >= 0 && arr[j] > key)


{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

// A utility function to print an array of size n


void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Main Function
int main()
{
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printArray(arr, n);
return 0;
}

//2. C program to
implement Quick
Sort Algorithm
#include <stdio.h>
// Function to swap two elements
void swap(int* a, int* b)
{
int temp = *a; *a = *b;
*b = temp;
}
// Partition function
int partition(int arr[], int low, int high)
{
// initialize pivot to be the first element
int pivot = arr[low];
int i = low; int j = high; while (i < j) {
// condition 1: find the first element greater than
// the pivot (from starting)
while (arr[i] <= pivot && i <= high - 1) { i++; }
// condition 2: find the first element smaller than the pivot (from last) while (arr[j] >
pivot && j >= low + 1) { j--; } if (i < j) {
swap(&arr[i], &arr[j]);
}
}
swap(&arr[low], &arr[j]); return j;
}

// QuickSort function
void quickSort(int arr[], int low, int high)
{
if (low < high) {

// call Partition function to find Partition Index


int partitionIndex = partition(arr, low, high);

// Recursively call quickSort() for left and right


// half based on partition Index quickSort(arr, low, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, high);
}
}

// Main function
int main()
{
int arr[] = { 19, 17, 15, 12, 16, 18, 4, 11, 13 };
int n = sizeof(arr) / sizeof(arr[0]); // printing the original array
printf("Original array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
// calling quickSort() to sort the given array
quickSort(arr, 0, n - 1); // printing the sorted array
printf("\nSorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}

Output
Original array: 19 17 15 12 16 18 4 11 13
Sorted array: 4 11 12 13 15 16 17 18 19
//3. C Program to
Input Few
Numbers &
Perform Merge
Sort on them using
Recursion
#include <stdio.h>
void mergeSort(int [], int, int, int);
void partition(int [],int, int);
int main()
{
int list[50];
int i, size;

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


scanf("%d", &size);
printf("Enter the elements:\n");
for(i = 0; i < size; i++)
{
scanf("%d", &list[i]);
}
partition(list, 0, size - 1);
printf("After merge sort:\n");
for(i = 0;i < size; i++)
{
printf("%d ",list[i]);
}

return 0;
}

void partition(int list[],int low,int high)


{ int mid;

if(low < high)


{
mid = (low + high) / 2;
partition(list, low, mid);
partition(list, mid + 1, high);
mergeSort(list, low, mid, high);
}
}

void mergeSort(int list[],int low,int mid,int high)


{
int i, mi, k, lo, temp[50];
lo = low; i = low;
mi = mid + 1;
while ((lo <= mid) && (mi <= high))
{
if (list[lo] <= list[mi])
{ temp[i] = list[lo];
lo++;
} else
{
temp[i] = list[mi];
mi++;
}
i++;
}
if (lo > mid)
{
for (k = mi; k <= high; k++)
{ temp[i] = list[k];
i++;
} } else
{
for (k = lo; k <= mid; k++)
{ temp[i] = list[k];
i++;
}
}
for (k = low; k <= high; k++)
{
list[k] = temp[k];
}
}

Output
Enter total number of elements: 5
Enter the elements:
34
7
23
32
5
After merge sort:
5 7 23 32 34
/* 4. C Program to
implement Linear
Search Algorithm
recursively */
#include <stdio.h>
int LinearS(int arr[], int value, int index, int n)
{
int pos = 0;

if(index >= n)
{ return 0;
}
else if (arr[index] == value)
{
pos = index + 1; return pos;
} else
{
return LinearS(arr, value, index+1, n);
}
return pos;
}

int main()
{
int n, value, pos, m = 0, arr[100];
printf("Enter the total elements in the array ");
scanf("%d", &n);

printf("Enter the array elements\n");


for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
printf("Enter the element to search ");
scanf("%d", &value);
pos = LinearS(arr, value, 0, n);
if (pos != 0)
{
printf("Element found at pos %d ", pos);
}
else
{
printf("Element not found");
}
return 0;
}

Output
Enter the total elements in the array 5
Enter the array elements
10 20 30 40 50
Enter the element to search 30
Element found at pos 3

//5. C Program to
Perform Binary
Search using
Recursion
#include <stdio.h>
void binary_search(int [], int, int, int);
void bubble_sort(int [], int);
int main() {
int key, size, i;
int list[25];

printf("Enter size of a list: ");


scanf("%d", &size);
printf("Enter elements\n");
for(i = 0; i < size; i++)
{
scanf("%d",&list[i]);
}
bubble_sort(list, size);
printf("\n");
printf("Enter key to search\n");
scanf("%d", &key);
binary_search(list, 0, size, key);

void bubble_sort(int list[], int size)


{
int temp, i, j;
for (i = 0; i < size; i++)
{
for (j = i; j < size; j++)
{
if (list[i] > list[j])
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
}

void binary_search(int list[], int lo, int hi, int key)


{
int mid;

if (lo > hi)


{
printf("Key not found\n");
return;
}
mid = (lo + hi) / 2;
if (list[mid] == key)
{
printf("Key found\n");
}
else if (list[mid] > key)
{
binary_search(list, lo, mid - 1, key);
}
else if (list[mid] < key)
{
binary_search(list, mid + 1, hi, key);
}
}

Output
Enter size of a list: 5
Enter elements
5
3
8
4
1
13458
Enter key to search
4
Key found
// 6. C program to implement stack. Stack is a LIFO data structure.
#include <stdio.h>
#define MAXSIZE 5

struct stack
{
int stk[MAXSIZE];
int top;
};
typedef struct stack STACK;
STACK s;

void push(void);
int pop(void);
void display(void);

void main ()
{
int choice;
int option = 1;
s.top = -1;

printf ("STACK OPERATION\n");


while (option)
{
printf ("------------------------------------------\n");
printf (" 1 --> PUSH \n");
printf (" 2 --> POP \n");
printf (" 3 --> DISPLAY \n");
printf (" 4 --> EXIT \n");
printf ("------------------------------------------\n");

printf ("Enter your choice\n");


scanf ("%d", &choice);
switch (choice)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
return;
}
fflush (stdin);
printf ("Do you want to continue(Type 0 or 1)?\n");
scanf("%d", &option);
}
}

/* Function to add an element to the stack */


void push ()
{
int num;
if (s.top == (MAXSIZE - 1))
{
printf ("Stack is Full\n");
return;
}
else
{
printf ("Enter the element to be pushed\n");
scanf ("%d", &num);
s.top = s.top + 1;
s.stk[s.top] = num;
}
return;
}

/* Function to delete an element from the stack */


int pop () {
int num;
if (s.top == - 1)
{
printf ("Stack is Empty\n");
return (s.top);
}
else
{
num = s.stk[s.top];
printf ("poped element is = %dn", s.stk[s.top]);
s.top = s.top - 1;
}
return(num);
}
/* Function to display the status of the stack */
void display ()
{
int i;
if (s.top == -1)
{
printf ("Stack is empty\n");
return;
}
else
{
printf ("\n The status of the stack is \n");
for (i = s.top; i >= 0; i--)
{
printf ("%d\n", s.stk[i]);
}
} printf ("\n");
}

Output
STACK OPERATION
------------------------------------------
1 --> PUSH
2 --> POP
3 --> DISPLAY
4 --> EXIT
------------------------------------------
Enter your choice
1
Enter the element to be pushed
10
Do you want to continue(Type 0 or 1)?
1
Enter your choice
1
Enter the element to be pushed
20
Do you want to continue(Type 0 or 1)?
1
Enter your choice
1
Enter the element to be pushed
30
Do you want to continue(Type 0 or 1)?
1
Enter your choice
3

The status of the stack is


30
20
10

Do you want to continue(Type 0 or 1)?


1
Enter your choice
2
popped element is = 30
Do you want to continue(Type 0 or 1)?
1
Enter your choice
3

The status of the stack is


20
10

Do you want to continue(Type 0 or 1)?


1
Enter your choice
2
Stack is Empty
Do you want to continue(Type 0 or 1)?
1
Stack is Full

//7. C Program to
Convert Infix to
Postfix using Stack

#include<stdio.h>
#include<ctype.h>

char stack[100];
int top = -1;

void push(char x)
{
stack[++top] = x;
}

char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}

int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;

while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
}
e++;
}

while(top != -1)
{
printf("%c ",pop());
}
return 0;
}

Output :
Enter the expression : a+b*c

abc*+

// 8. C Program to
Implement a
Queue using an
Array

#include <stdio.h>
#define MAX 50
void insert();
void delete();
void display();
int queue_array[MAX];
int rear = - 1;
int front = - 1;
main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice \n");
} /* End of switch */
} /* End of while */
} /* End of main() */

void insert() {
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
} /* End of insert() */

void delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /* End of delete() */

void display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
} /* End of display() */

Output
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice :1
Inset the element in queue : 10
Enter your choice : 1
Inset the element in queue : 20
Enter your choice : 1
Inset the element in queue : 30
Enter your choice : 3
Queue is :
10 20 30
Enter your choice : 2
Element deleted from queue is : 10
Enter your choice : 3
Queue is :
20 30
Enter your choice : 4

//9. C program to
Linked List
Implementations

// Linked list implementation in C

#include <stdio.h>
#include <stdlib.h>
#include<conio.h>

// Creating a node
struct node {
int value;
struct node *next;
};

// print the linked list value


void printLinkedlist(struct node *p) {
while (p != NULL) {
printf("%d ", p->value);
p = p->next;
}
}

int main() {
// Initialize nodes
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;

// Allocate memory
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));

// Assign value values


one->value = 1;
two->value = 2;
three->value = 3;

// Connect nodes
one->next = two;
two->next = three;
three->next = NULL;

// printing node-value
head = one;
printLinkedlist(head);
getch();
return 0;
}
Output of the Program:

123

//10. C Program
to perform Tree
traversal
#include <stdio.h>
#include <stdlib.h>

struct node {
int item;
struct node* left;
struct node* right;
};

// Inorder traversal
void inorderTraversal(struct node* root) {
if (root == NULL)
return;
inorderTraversal(root->left);
printf("%d ->", root->item);
inorderTraversal(root->right);
}

// preorderTraversal traversal
void preorderTraversal(struct node* root)
{ if (root == NULL) return;
printf("%d ->", root->item);
preorderTraversal(root->left);
preorderTraversal(root->right);
}

// postorderTraversal traversal void postorderTraversal(struct node* root) {


if (root == NULL)
return;
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ->", root->item);
}

// Create a new Node


struct node* createNode(value) {
struct node* newNode = malloc(sizeof(struct node));
newNode->item = value;
newNode->left = NULL;
newNode->right = NULL;

return newNode;
}

// Insert on the left of the node


struct node* insertLeft(struct node* root, int value) {
root->left = createNode(value);
return root->left;
}

// Insert on the right of the node


struct node* insertRight(struct node* root, int value) {
root->right = createNode(value);
return root->right;
}

int main() {
struct node* root = createNode(1);
insertLeft(root, 12);
insertRight(root, 9);

insertLeft(root->left, 5);
insertRight(root->left, 6);

printf("Inorder traversal \n");


inorderTraversal(root);

printf("\nPreorder traversal \n");


preorderTraversal(root);

printf("\nPostorder traversal \n");


postorderTraversal(root);
}

Output:
Inorder traversal
5 ->12 ->6 ->1 ->9 ->

Preorder traversal
1 ->12 ->5 ->6 ->9 ->

Postorder traversal
5 ->6 ->12 ->9 ->1 ->

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy