Essential C Programming Examples: Data Structures & Algorithms
Fundamental C Operations (String and Math)
String Reversal Without Built-in Functions
This program demonstrates manual string reversal using pointers and loops, calculating the string length without relying on strlen().
#include <stdio.h>
#include <string.h>
int main() {
char str[100], original[100];
char *start, *end, temp;
int length = 0;
printf("Enter a string: ");
scanf("%s", str); // accepts string without spaces
strcpy(original, str); // keep a copy of original string
char *ptr = str;
while (*ptr != '\0') {
length++;
ptr++;
}
start = str;
end = str + length - 1;
while (start < end) {
temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
printf("\nOriginal String: %s\n", original);
printf("Length of String: %d\n", length);
printf("Reversed String: %s\n", str);
return 0;
}Generating Fibonacci Series using Recursion
A recursive function implementation to calculate and display the Fibonacci sequence up to n terms.
#include <stdio.h>
int fib(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fib(n - 1) + fib(n - 2);
}
int main() {
int n, i;
printf("Enter number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 0; i < n; i++)
printf("%d ", fib(i));
return 0;
}Calculating Factorial using Recursion
A simple recursive function to compute the factorial of a non-negative integer.
#include <stdio.h>
int fact(int n) {
if (n == 0)
return 1;
return n * fact(n - 1);
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("Factorial = %d\n", fact(n));
return 0;
}Data Structures and Record Management
Employee Record System using Structures and Pointers
This menu-driven program uses an array of structures and pointers to manage employee data (ID, Name, Age, Salary).
#include <stdio.h>
#include <string.h>
#define MAX 100
struct Employee {
int Emp_id;
char Emp_name[50];
int Emp_age;
float Emp_sal;
};
int main() {
struct Employee emp[MAX]; // Array of structures
struct Employee *ptr = emp; // Pointer to structure
int choice, n = 0, i;
do {
printf("\n===== Employee Record System =====\n");
printf("1. Add Employee\n");
printf("2. Display Employees\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
if (n < MAX) {
printf("\nEnter Employee ID: ");
scanf("%d", &(ptr + n)->Emp_id);
printf("Enter Employee Name: ");
scanf("%s", (ptr + n)->Emp_name);
printf("Enter Employee Age: ");
scanf("%d", &(ptr + n)->Emp_age);
printf("Enter Employee Salary: ");
scanf("%f", &(ptr + n)->Emp_sal);
n++;
} else {
printf("\nRecord is Full! Cannot add more employees.\n");
}
break;
case 2:
if (n == 0) {
printf("\nNo Employee Records Found!\n");
} else {
printf("\n%-10s %-20s %-10s %-10s\n",
"Emp_ID", "Emp_Name", "Age", "Salary");
printf("----------------------------------------------------\n");
for (i = 0; i < n; i++) {
printf("%-10d %-20s %-10d %-10.2f\n",
(ptr + i)->Emp_id,
(ptr + i)->Emp_name,
(ptr + i)->Emp_age,
(ptr + i)->Emp_sal);
}
}
break;
case 3:
printf("\nExiting Program... Goodbye!\n");
break;
default:
printf("\nInvalid choice! Please try again.\n");
}
} while (choice != 3);
return 0;
}Sorting and Analyzing Student Names in C
This program reads student names, sorts them alphabetically using Bubble Sort, searches for a specific name, converts all names to uppercase, and calculates the total character count.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void toUpperCase(char str[]) {
for (int i = 0; str[i] != '\0'; i++) {
str[i] = toupper(str[i]);
}
}
int main() {
int n, i, j;
char temp[50], search[50];
int found = 0, totalChars = 0;
printf("Enter number of students: ");
scanf("%d", &n);
char names[n][50];
printf("Enter names of %d students:\n", n);
for (i = 0; i < n; i++) {
scanf("%s", names[i]);
}
// Sorting names alphabetically (Bubble Sort)
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (strcmp(names[i], names[j]) > 0) {
strcpy(temp, names[i]);
strcpy(names[i], names[j]);
strcpy(names[j], temp);
}
}
}
printf("\nEnter name to search: ");
scanf("%s", search);
// Searching
for (i = 0; i < n; i++) {
if (strcmp(names[i], search) == 0) {
printf("Name '%s' found at position %d (after sorting).\n", search, i + 1);
found = 1;
break;
}
}
if (!found) {
printf("Name '%s' not found in the list.\n", search);
}
// Calculate total characters
for (i = 0; i < n; i++) {
totalChars += strlen(names[i]);
}
// Convert to uppercase
for (i = 0; i < n; i++) {
toUpperCase(names[i]);
}
printf("\nNames in Alphabetical Order (Uppercase):\n");
for (i = 0; i < n; i++) {
printf("%s\n", names[i]);
}
printf("\nTotal number of characters in all names: %d\n", totalChars);
return 0;
}Student Marks Analysis: Average, Max, and Min
A menu-driven program to calculate and display statistical data for student marks, including average, highest, lowest scores, and the count of students scoring above average.
#include <stdio.h>
int main() {
int n, i, choice, above = 0;
int marks[50], sum = 0, max, min;
float avg;
printf("Enter number of students: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter marks of student %d: ", i + 1);
scanf("%d", &marks[i]);
sum += marks[i];
}
avg = (float)sum / n;
max = min = marks[0];
for (i = 0; i < n; i++) {
if (marks[i] > max) max = marks[i];
if (marks[i] < min) min = marks[i];
if (marks[i] > avg) above++;
}
do {
printf("\n--- MENU ---\n");
printf("1. Class Average\n");
printf("2. Highest Mark\n");
printf("3. Lowest Mark\n");
printf("4. Students Above Average\n");
printf("5. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice) {
case 1: printf("Class Average = %.2f\n", avg); break;
case 2: printf("Highest Mark = %d\n", max); break;
case 3: printf("Lowest Mark = %d\n", min); break;
case 4: printf("Students Above Average = %d\n", above); break;
case 5: printf("Exiting...\n"); break;
default: printf("Invalid choice\n");
}
} while (choice != 5);
return 0;
}File Handling and Advanced Algorithms
Student Records Management using File I/O
This program uses file handling (students.txt) to write, read, display, and search student names. Note that scanf("%s", ...) is used, which limits input to single words.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILENAME "students.txt"
int main() {
FILE *fp;
char name[50], searchName[50];
int choice, n, i, found;
while (1) {
printf("\n==== Student Records Menu ====\n");
printf("1. Write Student Names to File\n");
printf("2. Read and Display Student Names\n");
printf("3. Search for a Student Name\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
fp = fopen(FILENAME, "w");
if (fp == NULL) {
printf("Error opening file!\n");
exit(1);
}
printf("Enter number of students: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter name of student %d: ", i + 1);
scanf("%s", name);
fprintf(fp, "%s\n", name);
}
fclose(fp);
printf("Names written to file successfully.\n");
break;
case 2:
fp = fopen(FILENAME, "r");
if (fp == NULL) {
printf("File not found!\n");
break;
}
printf("\n-- Student Names in File --\n");
while (fscanf(fp, "%s", name) != EOF) {
printf("%s\n", name);
}
fclose(fp);
break;
case 3:
fp = fopen(FILENAME, "r");
if (fp == NULL) {
printf("File not found!\n");
break;
}
printf("Enter name to search: ");
scanf("%s", searchName);
found = 0;
i = 0;
while (fscanf(fp, "%s", name) != EOF) {
i++;
if (strcmp(name, searchName) == 0) {
printf("Name '%s' found at position %d in file.\n", searchName, i);
found = 1;
break;
}
}
if (!found) {
printf("Name '%s' not found in file.\n", searchName);
}
fclose(fp);
break;
case 4:
printf("Exiting program...\n");
exit(0);
default:
printf("Invalid choice! Try again.\n");
}
}
return 0;
}Matrix Multiplication using Functions
This program defines functions to read, display, and perform multiplication of two matrices (A * B), ensuring compatibility based on dimensions.
#include <stdio.h>
// Function to read matrix elements
void readMatrix(int r, int c, int a[r][c]) {
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
scanf("%d", &a[i][j]);
}
// Function to display matrix elements
void displayMatrix(int r, int c, int a[r][c]) {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++)
printf("%d ", a[i][j]);
printf("\n");
}
}
// Function to multiply matrices A (m x n) and B (n x p)
void multiplyMatrix(int m, int n, int p,
int A[m][n], int B[n][p], int C[m][p]) {
for (int i = 0; i < m; i++)
for (int j = 0; j < p; j++) {
C[i][j] = 0;
for (int k = 0; k < n; k++)
C[i][j] += A[i][k] * B[k][j];
}
}
int main() {
int m, n, p;
printf("Enter rows and columns of Matrix A: ");
scanf("%d %d", &m, &n);
printf("Enter columns of Matrix B: ");
scanf("%d", &p);
// Matrix B must have n rows for multiplication (A[m][n] * B[n][p])
int A[m][n], B[n][p], C[m][p];
printf("Enter elements of Matrix A:\n");
readMatrix(m, n, A);
printf("Enter elements of Matrix B:\n");
readMatrix(n, p, B);
multiplyMatrix(m, n, p, A, B, C);
printf("Resultant Matrix:\n");
displayMatrix(m, p, C);
return 0;
}Tower of Hanoi Implementation using Recursion
A classic recursive solution to the Tower of Hanoi puzzle, detailing the steps required to move n disks from the source rod (‘A’) to the destination rod (‘C’).
#include <stdio.h>
void towerOfHanoi(int n, char from, char to, char aux)
{
if (n == 1)
{
printf("Move disk 1 from rod %c to rod %c\n", from, to);
return;
}
// Move n-1 disks from source (from) to auxiliary (aux)
towerOfHanoi(n - 1, from, aux, to);
// Move the largest disk (n) from source (from) to destination (to)
printf("Move disk %d from rod %c to rod %c\n", n, from, to);
// Move n-1 disks from auxiliary (aux) to destination (to)
towerOfHanoi(n - 1, aux, to, from);
}
int main()
{
int n;
printf("Enter number of disks: ");
scanf("%d", &n);
printf("\nSteps to solve Tower of Hanoi:\n");
// A = Source, C = Destination, B = Auxiliary
towerOfHanoi(n, 'A', 'C', 'B');
return 0;
}Utility and Simulation Programs
Simple ATM Simulation Program
A basic ATM simulation allowing users to check their balance and withdraw funds, protected by a simple PIN check (though the PIN validation logic is rudimentary here).
#include <stdio.h>
int main() {
int pin, choice;
float balance = 5000, amount;
printf("Enter PIN: ");
scanf("%d", &pin);
do {
printf("\n--- ATM Menu ---\n");
printf("1. Withdraw\n");
printf("2. Balance\n");
printf("3. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
if (choice == 1) {
printf("Enter amount: ");
scanf("%f", &amount);
if (amount <= balance) {
balance -= amount;
printf("Please collect cash. Balance = %.2f\n", balance);
} else {
printf("Insufficient balance\n");
}
} else if (choice == 2) {
printf("Balance = %.2f\n", balance);
} else if (choice == 3) {
printf("Thank you\n");
} else {
printf("Invalid choice\n");
}
} while (choice != 3);
return 0;
}Library Fine Calculation Program
Calculates library fines based on the number of days a book is overdue, using a simplified 30-day month and 360-day year calculation for total days elapsed.
- No fine for returns within 7 days.
- 5 units/day fine for 8 to 15 days late.
- 10 units/day fine for 16 to 30 days late.
- Membership cancellation after 30 days late.
#include <stdio.h>
int main() {
int studentID;
int issueDay, issueMonth, issueYear;
int returnDay, returnMonth, returnYear;
int totalDays, daysLate, fine;
printf("Enter Student ID: ");
scanf("%d", &studentID);
printf("Enter Issue Date (day month year): ");
scanf("%d %d %d", &issueDay, &issueMonth, &issueYear);
printf("Enter Return Date (day month year): ");
scanf("%d %d %d", &returnDay, &returnMonth, &returnYear);
// Simplified calculation assuming 30 days/month, 360 days/year
totalDays = (returnYear - issueYear) * 360 +
(returnMonth - issueMonth) * 30 +
(returnDay - issueDay);
if (totalDays <= 7) {
printf("Student ID: %d\nNo fine. Thank you!\n", studentID);
} else if (totalDays <= 15) {
daysLate = totalDays - 7;
fine = 5 * daysLate;
printf("Student ID: %d\nFine: %d\n", studentID, fine);
} else if (totalDays <= 30) {
daysLate = totalDays - 7;
fine = 10 * daysLate;
printf("Student ID: %d\nFine: %d\n", studentID, fine);
} else {
printf("Student ID: %d\nMembership Cancelled due to late return\n", studentID);
}
return 0;
}Passenger Fare Calculation with Discounts and GST
Calculates the total fare for multiple passengers, applying discounts based on age (under 5, over 60) and gender (female), and adding a 5% GST.
#include <stdio.h>
int main() {
int n, age, i;
char gender;
float baseFare, fare, subtotal = 0, gst, total;
printf("Enter number of passengers: ");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
printf("\nPassenger %d\n", i);
printf("Enter age: ");
scanf("%d", &age);
// Note the space before %c to consume potential newline/whitespace
printf("Enter gender (M/F): ");
scanf(" %c", &gender);
printf("Enter base fare: ");
scanf("%f", &baseFare);
if (age < 5)
fare = 0; // Free for children under 5
else if (gender == 'F' || gender == 'f')
fare = 0; // Free for females (as per program logic)
else if (age > 60)
fare = baseFare * 0.7; // 30%% discount for seniors
else
fare = baseFare; // Full fare
printf("Payable fare: %.2f\n", fare);
subtotal += fare;
}
gst = subtotal * 0.05; // 5%% GST calculation
total = subtotal + gst;
printf("\nSubtotal: %.2f", subtotal);
printf("\nGST (5%%): %.2f", gst);
printf("\nTotal Fare: %.2f\n", total);
return 0;
}