C Programming Examples: Data Structures & Algorithms
C Programming Examples: Data Structures and Algorithms
This document presents a collection of fundamental C programming examples, covering essential data structures and algorithms. Each section includes a C code implementation along with a brief explanation of its functionality.
1. String Length and Concatenation in C
This C program demonstrates how to calculate the length of a string and concatenate two strings without using built-in library functions like strlen()
or strcat()
. It provides a menu-driven interface for user interaction.
C Code for String Operations
#include <stdio.h>
// Function to calculate the length of a string
int stringLength(char str[])
{
int length = 0;
while (str[length] != '\0')
{
length++;
}
return length;
}
// Function to concatenate two strings
void stringConcatenate(char str1[], char str2[])
{
int i = 0, j = 0;
// Find the end of the first string
while (str1[i] != '\0')
{
i++;
}
// Append the second string to the first
while (str2[j] != '\0')
{
str1[i] = str2[j];
i++;
j++;
}
str1[i] = '\0'; // Null-terminate the concatenated string
}
int main()
{
char str1[100], str2[100];
int choice;
printf("Enter the first string: ");
scanf("%s", str1);
printf("Enter the second string: ");
scanf("%s", str2);
do
{
printf("\nChoose an operation:\n");
printf("1. String Length\n");
printf("2. String Concatenation\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Length of first string: %d\n", stringLength(str1));
printf("Length of second string: %d\n", stringLength(str2));
break;
case 2:
// Note: str1 will be modified to contain the concatenated string
stringConcatenate(str1, str2);
printf("Concatenated string: %s\n", str1);
break;
case 3:
printf("Exiting the program. Goodbye!\n");
return 0; // Exit the program
default:
printf("Invalid choice! Please enter a valid option.\n");
break;
}
} while (choice != 3); // Continue until user chooses to exit
return 0; // Should not be reached if case 3 is handled correctly
}
This program defines two custom functions: stringLength
to compute the length of a C-style string by counting characters until the null terminator ('\0'
) is found, and stringConcatenate
to append the content of one string to another. The main
function provides a simple menu to test these operations.
2. Binary Search Algorithm in C
Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing the search interval in half. This program implements binary search to find a specific element in an array.
C Code for Binary Search
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d integers (in sorted order): \n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter value to find: ");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first + last) / 2;
while (first <= last)
{
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search)
{
printf("%d found at location %d.\n", search, middle + 1);
break; // Element found, exit loop
}
else
last = middle - 1;
middle = (first + last) / 2; // Recalculate middle
}
if (first > last) // Element not found
printf("Not found! %d is not present in the list.\n", search);
return 0;
}
The program prompts the user to enter a sorted list of integers and a value to search for. It then uses a while
loop to repeatedly adjust the first
, last
, and middle
indices until the element is found or the search interval becomes empty.
3. Selection Sort Implementation in C
Selection sort is a simple sorting algorithm that repeatedly finds the minimum element from the unsorted part of the array and puts it at the beginning. This program demonstrates its implementation in C.
C Code for Selection Sort
#include<stdio.h>
int main()
{
int a[10], i;
int j, temp, num;
printf("Enter the number of elements (max 10): ");
scanf("%d", &num);
printf("Enter %d integers:\n", num);
for(i = 0; i < num; i++)
{
printf("a[%d]=\t", i);
scanf("%d", &a[i]);
}
// Selection Sort Logic
for(i = 0; i < num - 1; i++)
{
// Find the minimum element in the unsorted array
for(j = i + 1; j < num; j++)
{
if(a[i] > a[j])
{
// Swap elements
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("\nArray after Selection Sort:\n");
for(i = 0; i < num; i++)
{
printf("a[%d]=\t%d\n", i, a[i]);
}
return 0; // Added return 0 for main function
}
This program takes an array of integers as input and sorts them using the selection sort algorithm. The outer loop iterates through the array, and the inner loop finds the smallest element in the remaining unsorted portion, swapping it with the element at the current outer loop index.
4. Queue Operations Using Linked List in C
A queue is a linear data structure that follows the First-In, First-Out (FIFO) principle. This program implements a queue using a linked list, allowing for insertion (enqueue), deletion (dequeue), and display operations.
C Code for Linked List Queue
#include<stdio.h>
#include<stdlib.h> // Required for malloc and exit
// Structure for a node in the linked list
struct node
{
int data;
struct node *next;
};
struct node front = NULL; // Pointer to the front of the queue
struct node rear = NULL; // Pointer to the rear of the queue
// Function prototypes
void insert();
void delete_element(); // Renamed to avoid conflict with C++ keyword
void display();
int main() // Changed from void main() to int main()
{
int choice;
// Initialize choice to a value that ensures the loop runs at least once
choice = 0;
while(choice != 4)
{
printf("\n*************************Main Menu*****************************\n");
printf("\n==================================================\n");
printf("\n1. Insert an element\n2. Delete an element\n3. Display the queue\n4. Exit\n");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
insert();
break;
case 2:
delete_element();
break;
case 3:
display();
break;
case 4:
exit(0); // Terminate the program
default:
printf("\nEnter a valid choice (1-4)!\n");
}
}
return 0; // Should not be reached if exit(0) is called for case 4
}
// Function to insert an element into the queue (enqueue)
void insert()
{
struct node *ptr;
int item;
ptr = (struct node *) malloc (sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW: Queue is full (memory allocation failed)\n");
return;
}
else
{
printf("\nEnter value to insert: ");
scanf("%d", &item);
ptr -> data = item;
ptr -> next = NULL; // New node always points to NULL initially
if(front == NULL) // If queue is empty
{
front = ptr;
rear = ptr;
}
else // If queue is not empty
{
rear -> next = ptr;
rear = ptr;
}
printf("Element %d inserted successfully.\n", item);
}
}
// Function to delete an element from the queue (dequeue)
void delete_element()
{
struct node *ptr;
if(front == NULL)
{
printf("\nUNDERFLOW: Queue is empty\n");
return;
}
else
{
ptr = front;
front = front -> next; // Move front to the next node
printf("Deleted element: %d\n", ptr->data);
free(ptr); // Free the memory of the deleted node
}
}
// Function to display elements of the queue
void display()
{
struct node *ptr;
ptr = front;
if(front == NULL)
{
printf("\nQueue is empty\n");
}
else
{
printf("\nQueue elements are: \n");
while(ptr != NULL)
{
printf("%d\n", ptr -> data);
ptr = ptr -> next;
}
}
}
This program uses a linked list to implement a queue. The front
pointer points to the first element, and the rear
pointer points to the last. The insert()
function adds elements to the rear, and delete_element()
removes elements from the front, adhering to the FIFO principle.
5. Stack Operations Using Linked List in C
A stack is a linear data structure that follows the Last-In, First-Out (LIFO) principle. This program implements a stack using a linked list, providing operations such as push, pop, display, and more.
C Code for Linked List Stack
#include <stdio.h>
#include <stdlib.h> // Required for malloc and exit
// Structure for a node in the linked list
struct node
{
int info;
struct node ptr; // Pointer to the next node (below in stack)
} top, top1, temp; // Global pointers for stack operations
int count = 0; // Global variable to keep track of stack elements
// Function prototypes
void create();
void push(int data);
void pop();
void display();
void empty();
int topelement();
void stack_count();
void destroy();
int main() // Changed from void main() to int main()
{
int no, ch, e;
printf("\n--- Stack Operations Menu ---");
printf("\n 1. Push");
printf("\n 2. Pop");
printf("\n 3. Top Element");
printf("\n 4. Check if Empty");
printf("\n 5. Exit");
printf("\n 6. Display Stack");
printf("\n 7. Stack Count");
printf("\n 8. Destroy Stack");
create(); // Initialize the stack
while (1) // Infinite loop until user chooses to exit
{
printf("\n\nEnter your choice: ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data to push: ");
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
case 3:
if (top == NULL)
printf("No elements in stack.\n");
else
{
e = topelement();
printf("\nTop element: %d\n", e);
}
break;
case 4:
empty();
break;
case 5:
exit(0); // Terminate the program
case 6:
display();
break;
case 7:
stack_count();
break;
case 8:
destroy();
break;
default:
printf("Invalid choice! Please enter a correct option.\n");
break;
}
}
return 0; // Should not be reached if exit(0) is called for case 5
}
/ Function to create an empty stack /
void create()
{
top = NULL; // Initialize top pointer to NULL
printf("Stack created successfully (empty).\n");
}
/ Function to push data onto the stack /
void push(int data)
{
if (top == NULL) // If stack is empty
{
top = (struct node )malloc(sizeof(struct node));
top->ptr = NULL;
top->info = data;
}
else // If stack is not empty
{
temp = (struct node )malloc(sizeof(struct node));
temp->ptr = top; // New node points to the current top
temp->info = data;
top = temp; // New node becomes the new top
}
count++; // Increment element count
printf("Element %d pushed to stack.\n", data);
}
/ Function to pop data from the stack /
void pop()
{
top1 = top; // Use a temporary pointer
if (top1 == NULL)
{
printf("\nError: Trying to pop from an empty stack.\n");
return;
}
else
{
top1 = top1->ptr; // Move top1 to the next element
printf("\nPopped value: %d\n", top->info);
free(top); // Free the memory of the old top node
top = top1; // Update top to the new top
count--; // Decrement element count
}
}
/ Function to display stack elements /
void display()
{
top1 = top; // Use a temporary pointer to traverse
if (top1 == NULL)
{
printf("Stack is empty.\n");
return;
}
printf("\nStack elements (Top to Bottom): ");
while (top1 != NULL)
{
printf("%d ", top1->info);
top1 = top1->ptr;
}
printf("\n");
}
/ Function to return the top element of the stack /
int topelement()
{
return (top->info);
}
/ Function to check if stack is empty or not /
void empty()
{
if (top == NULL)
printf("\nStack is empty.\n");
else
printf("\nStack is not empty with %d elements.\n", count);
}
/ Function to destroy the entire stack /
void destroy()
{
top1 = top; // Start from the current top
while (top1 != NULL)
{
top1 = top->ptr; // Move top1 to the next node
free(top); // Free the current top node
top = top1; // Update top to the next node
}
top = NULL; // Ensure top is explicitly NULL after destruction
printf("\nAll stack elements destroyed.\n");
count = 0; // Reset count
}
This program implements a stack using a singly linked list. The top
pointer always points to the most recently added element. Functions are provided for common stack operations like push()
(add element), pop()
(remove element), display()
(show elements), topelement()
(view top element), empty()
(check if empty), stack_count()
(get number of elements), and destroy()
(clear stack).
6. Tower of Hanoi Recursive Solution in C
The Tower of Hanoi is a mathematical puzzle. It consists of three rods and a number of disks of different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
- Only one disk can be moved at a time.
- Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod.
- No disk may be placed on top of a smaller disk.
This program provides a recursive solution to the Tower of Hanoi problem.
C Code for Tower of Hanoi
#include <stdio.h>
// Function prototype for Tower of Hanoi
void TOH(int, char, char, char);
int main()
{
int no_of_discs;
printf("Enter the number of discs: ");
scanf("%d", &no_of_discs);
printf("\nSteps to solve Tower of Hanoi with %d discs:\n", no_of_discs);
// Call the recursive function:
// no_of_discs: number of discs
// 'X': Source Tower
// 'Y': Auxiliary Tower
// 'Z': Destination Tower
TOH(no_of_discs, 'X', 'Y', 'Z');
return 0;
}
// Recursive function to solve Tower of Hanoi
void TOH(int n, char towerX, char towerY, char towerZ)
{
if (n == 1)
{
printf("\n Move disc 1 from %c to %c", towerX, towerZ);
return;
}
// Move n-1 discs from Source (towerX) to Auxiliary (towerY) using Destination (towerZ)
TOH(n - 1, towerX, towerZ, towerY);
// Move the nth disc from Source (towerX) to Destination (towerZ)
printf("\n Move disc %d from %c to %c", n, towerX, towerZ);
// Move n-1 discs from Auxiliary (towerY) to Destination (towerZ) using Source (towerX)
TOH(n - 1, towerY, towerX, towerZ);
}
The TOH
function is recursive. It breaks down the problem into three steps: moving n-1
discs from the source to the auxiliary peg, moving the largest disc to the destination peg, and then moving the n-1
discs from the auxiliary to the destination peg.
7. Find Greatest Common Divisor (GCD) in C
The Greatest Common Divisor (GCD) of two or more integers (when at least one of them is not zero) is the largest positive integer that divides each of the integers. This program calculates the GCD of two numbers using a simple iterative approach.
C Code for GCD Calculation
#include <stdio.h>
int main()
{
// Declare the variables
int n1, n2, i, gcd_num; // Renamed GCD_Num to gcd_num for consistency
printf("Enter any two positive integers: \n");
scanf("%d %d", &n1, &n2);
// Loop from 1 up to the minimum of n1 and n2
for(i = 1; i <= n1 && i <= n2; ++i)
{
// Check if i is a common divisor of both n1 and n2
if (n1 % i == 0 && n2 % i == 0)
{
gcd_num = i; // If it is, update gcd_num (the largest one found so far will be the GCD)
}
}
// Print the GCD of two numbers
printf("GCD of %d and %d is %d.\n", n1, n2, gcd_num);
return 0;
}
This program takes two integers as input and iterates from 1 up to the smaller of the two numbers. In each iteration, it checks if the current number i
divides both input numbers evenly. The last such i
found will be the Greatest Common Divisor.