DSC Program-Adi

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Data Structure Using C Programs

SJES College of Management Studies


Department of Computer Applications
Data Structure Using C Lab Programs
// 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;
}

Prof. K. Adisesha 1
Data Structure Using C Programs

// 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;
}

Prof. K. Adisesha 2
Data Structure Using C Programs

// 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) );
}

Prof. K. Adisesha 3
Data Structure Using C Programs

//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);
}

Prof. K. Adisesha 4
Data Structure Using C Programs

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

Prof. K. Adisesha 5
Data Structure Using C Programs

//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

Prof. K. Adisesha 6
Data Structure Using C Programs

//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:

Prof. K. Adisesha 7
Data Structure Using C Programs

//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

Prof. K. Adisesha 8
Data Structure Using C Programs

//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;
}

Prof. K. Adisesha 9
Data Structure Using C Programs

//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;
}

Prof. K. Adisesha 10
Data Structure Using C Programs

/* 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;
}

Prof. K. Adisesha 11
Data Structure Using C Programs

// 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

Prof. K. Adisesha 12
Data Structure Using C Programs

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

Prof. K. Adisesha 13
Data Structure Using C Programs

//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))

Prof. K. Adisesha 14
Data Structure Using C Programs

{
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];
}
}

Prof. K. Adisesha 15
Data Structure Using C Programs

/* 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;
}

Prof. K. Adisesha 16
Data Structure Using C Programs

//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)


Prof. K. Adisesha 17
Data Structure Using C Programs

{
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);
}
}

Prof. K. Adisesha 18
Data Structure Using C Programs

// 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:

Prof. K. Adisesha 19
Data Structure Using C Programs

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 ()
{

Prof. K. Adisesha 20
Data Structure Using C Programs

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");
}

Prof. K. Adisesha 21
Data Structure Using C Programs

//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 == ')')

Prof. K. Adisesha 22
Data Structure Using C Programs

{
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*+

Prof. K. Adisesha 23
Data Structure Using C Programs

// 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
{

Prof. K. Adisesha 24
Data Structure Using C Programs

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() */

Prof. K. Adisesha 25
Data Structure Using C Programs

// C program to create a linked list, delete and display the elements in the list

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

typedef struct node {


int data;
struct node *next;
} node;

node *start = NULL;

int menu() {
int ch;
printf("\n 1. Create a list ");
printf("\n 2. Insert a node at end");
printf("\n 3. Delete a node from beginning");
printf("\n 4. Traverse the list (Left to Right)");
printf("\n 5. Exit ");
printf("\n\n Enter your choice: ");
scanf("%d", &ch);
return ch;
}

node* getnode() {
node *newnode = (node*) malloc(sizeof(node));
if (newnode == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
printf("\n Enter data: ");
scanf("%d", &newnode->data);
newnode->next = NULL;
return newnode;
}

void createlist() {
if (start == NULL) {
start = getnode();
printf("\n List created with one node.\n");
} else {
printf("\n List is already created.\n");
}
}

void traverse() {
node *temp = start;

Prof. K. Adisesha 26
Data Structure Using C Programs

printf("\n The contents of the List (Left to Right): \n");


if (start == NULL) {
printf("\n Empty List\n");
return;
} else {
while (temp != NULL) {
printf("%d-->", temp->data);
temp = temp->next;
}
}
printf("X\n");
}

void insert_at_end() {
node *newnode = getnode(), *temp;
if (start == NULL) {
start = newnode;
} else {
temp = start;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newnode;
}
}

void delete_at_beg() {
node *temp;
if (start == NULL) {
printf("\n No nodes exist.\n");
return;
} else {
temp = start;
start = start->next;
free(temp);
printf("\n node deleted.\n");
}
}

void main() {
int ch;
while (1) {
ch = menu();
switch (ch) {
case 1:
createlist();
break;

Prof. K. Adisesha 27
Data Structure Using C Programs

case 2:
insert_at_end();
break;
case 3:
delete_at_beg();
break;
case 4:
traverse();
break;
case 5:
exit(0);
default:
printf("\n Invalid choice, please try again.\n");
}
getch();
}
}

Prof. K. Adisesha 28
Data Structure Using C Programs

//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) {
Prof. K. Adisesha 29
Data Structure Using C Programs

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 ->

Prof. K. Adisesha 30

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