1
🎓 Student Record — Input and Display
Read one student's data from keyboard and print it neatly
Basic
The most basic struct example. Define a
Student structure, read all fields from the user with scanf and fgets, then print a formatted card. Shows how all the different field types work together in one variable.
#include <stdio.h> #include <string.h> typedef struct { char name[30]; int rollNo; int age; float marks; char grade; } Student; int main() { Student s; /* Input */ printf("Enter name : "); fgets(s.name, 30, stdin); s.name[strcspn(s.name, "\n")] = '\0'; /* remove newline */ printf("Enter roll no : "); scanf("%d", &s.rollNo); printf("Enter age : "); scanf("%d", &s.age); printf("Enter marks : "); scanf("%f", &s.marks); /* Assign grade */ if (s.marks >= 90) s.grade = 'A'; else if (s.marks >= 75) s.grade = 'B'; else if (s.marks >= 55) s.grade = 'C'; else s.grade = 'F'; /* Display */ printf("\n--- Student Card ---\n"); printf("Name : %s\n", s.name); printf("Roll No : %d\n", s.rollNo); printf("Age : %d\n", s.age); printf("Marks : %.1f\n",s.marks); printf("Grade : %c\n", s.grade); return 0; }
Enter name : Ananta Enter roll no : 101 Enter age : 18 Enter marks : 88.5 --- Student Card --- Name : Ananta Roll No : 101 Age : 18 Marks : 88.5 Grade : B
example 2
2
📐 Rectangle — Area and Perimeter
struct holds length and width — calculate area and perimeter
Geometry
A
Rectangle struct stores length and width as floats. The program computes area (length × width) and perimeter (2 × (length + width)). Also compares two rectangles and finds which is bigger. Clean example of structs for mathematical objects.
#include <stdio.h> typedef struct { float length; float width; } Rectangle; int main() { Rectangle r1 = {8.0, 5.0}; Rectangle r2 = {6.0, 6.0}; float area1 = r1.length * r1.width; float area2 = r2.length * r2.width; float peri1 = 2 * (r1.length + r1.width); float peri2 = 2 * (r2.length + r2.width); printf("Rectangle 1: %.1f x %.1f\n", r1.length, r1.width); printf(" Area = %.2f\n", area1); printf(" Perimeter = %.2f\n", peri1); printf("\nRectangle 2: %.1f x %.1f\n", r2.length, r2.width); printf(" Area = %.2f\n", area2); printf(" Perimeter = %.2f\n", peri2); printf("\nBigger area: Rectangle %d\n", area1 > area2 ? 1 : 2); return 0; }
Rectangle 1: 8.0 x 5.0 Area = 40.00 Perimeter = 26.00 Rectangle 2: 6.0 x 6.0 Area = 36.00 Perimeter = 24.00 Bigger area: Rectangle 1
example 3
3
🏦 Bank Account — Deposit and Withdraw
struct holds account details — deposit, withdraw, show balance
Struct + logic
A
BankAccount struct stores account number, holder name, and balance. The program demonstrates deposit and withdrawal operations by directly modifying the struct's balance field. Checks that withdrawal doesn't exceed balance. Real-world struct use case.
#include <stdio.h> #include <string.h> typedef struct { int accNo; char holder[25]; double balance; } BankAccount; int main() { BankAccount acc = {100123, "Ananta Sharma", 15000.00}; double amount; printf("Account No : %d\n", acc.accNo); printf("Holder : %s\n", acc.holder); printf("Balance : Rs %.2f\n", acc.balance); /* Deposit */ amount = 5000.00; acc.balance += amount; printf("\nDeposited Rs %.2f\n", amount); printf("New balance: Rs %.2f\n", acc.balance); /* Withdraw */ amount = 3000.00; if (amount > acc.balance) { printf("\nInsufficient funds!\n"); } else { acc.balance -= amount; printf("\nWithdrew Rs %.2f\n", amount); printf("New balance: Rs %.2f\n", acc.balance); } return 0; }
Account No : 100123 Holder : Ananta Sharma Balance : Rs 15000.00 Deposited Rs 5000.00 New balance: Rs 20000.00 Withdrew Rs 3000.00 New balance: Rs 17000.00
example 4
4
👔 Employee Salary Calculator
Array of 4 employees — calculate gross, tax, net salary each
Array of structs
An array of 4
Employee structs. For each employee: gross = basic + HRA + DA. Tax = 10% if gross > 30000. Net = gross − tax. Prints a payslip table. Shows how arrays of structs handle multiple records cleanly.
#include <stdio.h> typedef struct { char name[20]; int id; double basic; double hra; /* house rent allowance */ double da; /* dearness allowance */ } Employee; int main() { Employee emp[4] = { {"Ananta", 1001, 25000, 5000, 3000}, {"Priya", 1002, 32000, 6000, 4000}, {"Rahul", 1003, 18000, 3000, 2000}, {"Sneha", 1004, 40000, 8000, 5000} }; int i; double gross, tax, net; printf("%-10s %6s %8s %8s %8s\n", "Name","ID","Gross","Tax","Net"); printf("-------------------------------------------\n"); for (i = 0; i < 4; i++) { gross = emp[i].basic + emp[i].hra + emp[i].da; tax = (gross > 30000) ? gross * 0.10 : 0; net = gross - tax; printf("%-10s %6d %8.0f %8.0f %8.0f\n", emp[i].name, emp[i].id, gross, tax, net); } return 0; }
Name ID Gross Tax Net ------------------------------------------- Ananta 1001 33000 3300 29700 Priya 1002 42000 4200 37800 Rahul 1003 23000 0 23000 Sneha 1004 53000 5300 47700
Tax only applies when gross > 30000. Notice Rahul's tax is 0 because his gross (23000) is below the threshold. The ternary operator handles this in one clean line.
example 5
5
📦 Inventory — Total Stock Value
5 products with name, price, quantity — find total value and costliest item
Real-world
An inventory of 5 products — each
Product struct holds name, price per unit, and quantity in stock. Calculates value = price × quantity for each item, sums all values to get total stock value, and finds the most expensive item.
#include <stdio.h> typedef struct { char name[20]; float price; int qty; } Product; int main() { Product shop[5] = { {"Rice (1kg)", 60.0, 200}, {"Cooking Oil", 180.0, 80}, {"Sugar (1kg)", 45.0, 150}, {"Tea Powder", 220.0, 60}, {"Salt", 20.0, 300} }; int i, costlyIdx = 0; float value, total = 0; printf("%-14s %7s %5s %10s\n", "Product","Price","Qty","Value"); printf("--------------------------------------\n"); for (i = 0; i < 5; i++) { value = shop[i].price * shop[i].qty; total += value; printf("%-14s %7.2f %5d %10.2f\n", shop[i].name, shop[i].price, shop[i].qty, value); if (shop[i].price > shop[costlyIdx].price) costlyIdx = i; } printf("--------------------------------------\n"); printf("Total stock value : Rs %.2f\n", total); printf("Costliest item : %s (Rs %.2f)\n", shop[costlyIdx].name, shop[costlyIdx].price); return 0; }
Product Price Qty Value -------------------------------------- Rice (1kg) 60.00 200 12000.00 Cooking Oil 180.00 80 14400.00 Sugar (1kg) 45.00 150 6750.00 Tea Powder 220.00 60 13200.00 Salt 20.00 300 6000.00 -------------------------------------- Total stock value : Rs 52350.00 Costliest item : Tea Powder (Rs 220.00)
example 6
6
📏 Distance — Add Two Distances
Struct with feet and inches — add two distances with carry
Nested arithmetic
A
Distance struct holds feet and inches. Adding two distances requires carrying — if total inches ≥ 12, convert excess to feet. This shows struct members working together in arithmetic with real-world units.
#include <stdio.h> typedef struct { int feet; int inches; } Distance; int main() { Distance d1 = {5, 9}; /* 5 feet 9 inches */ Distance d2 = {3, 8}; /* 3 feet 8 inches */ Distance total; total.inches = d1.inches + d2.inches; total.feet = d1.feet + d2.feet; /* Carry: if inches >= 12, convert to feet */ if (total.inches >= 12) { total.feet += total.inches / 12; total.inches = total.inches % 12; } printf("Distance 1 : %d ft %d in\n", d1.feet, d1.inches); printf("Distance 2 : %d ft %d in\n", d2.feet, d2.inches); printf("Total : %d ft %d in\n", total.feet, total.inches); return 0; }
Distance 1 : 5 ft 9 in Distance 2 : 3 ft 8 in Total : 9 ft 5 in
The carry: 9 + 8 = 17 inches. 17 ÷ 12 = 1 foot remainder 5 inches. So total feet = 5 + 3 + 1 = 9. Total inches = 5.
example 7
7
🏆 Class Topper Finder
Read 5 students from keyboard — sort by marks — find topper
Input + search
Read 5 student records from the user. Find the topper (highest marks) and rank them 1st to last. Uses a simple comparison loop —
topIdx tracks the index of the current best student. At the end one index gives access to all fields of the winner.
#include <stdio.h> #include <string.h> #define N 5 typedef struct { char name[20]; int roll; float marks; } Student; int main() { Student s[N]; int i, topIdx = 0, lastIdx = 0; /* Input */ for (i = 0; i < N; i++) { printf("Student %d — Name: ", i+1); scanf("%s", s[i].name); printf(" Roll: "); scanf("%d", &s[i].roll); printf(" Marks: "); scanf("%f", &s[i].marks); } /* Find topper and last */ for (i = 1; i < N; i++) { if (s[i].marks > s[topIdx].marks) topIdx = i; if (s[i].marks < s[lastIdx].marks) lastIdx = i; } /* Print all */ printf("\n%-12s %-6s %s\n","Name","Roll","Marks"); printf("---------------------------\n"); for (i = 0; i < N; i++) printf("%-12s %-6d %.1f\n", s[i].name, s[i].roll, s[i].marks); printf("\n🏆 Topper : %s (%.1f)\n", s[topIdx].name, s[topIdx].marks); printf("📉 Lowest : %s (%.1f)\n", s[lastIdx].name, s[lastIdx].marks); return 0; }
Name Roll Marks --------------------------- Ananta 101 87.5 Priya 102 95.0 Rahul 103 62.0 Vikram 104 78.5 Sneha 105 91.0 🏆 Topper : Priya (95.0) 📉 Lowest : Rahul (62.0)
example 8
8
📅 Date — Validate and Display
Date struct with day/month/year — validate input and print formatted
Validation
A
Date struct holds day, month, and year. A validation check ensures month is 1–12 and day is within the correct range for that month (accounting for 30-day and 31-day months). Prints the date in DD/MM/YYYY format.
#include <stdio.h> typedef struct { int day; int month; int year; } Date; char *months[12] = { "January","February","March","April", "May","June","July","August", "September","October","November","December" }; int daysInMonth[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 }; int isValid(Date d) { if (d.month < 1 || d.month > 12) return 0; if (d.day < 1 || d.day > daysInMonth[d.month-1]) return 0; if (d.year < 1900 || d.year > 2100) return 0; return 1; } int main() { Date dates[4] = { {15, 8, 2005}, {31, 4, 2024}, /* invalid: April has 30 days */ {29, 2, 2023}, /* invalid: 2023 is not a leap year */ {1, 1, 2025} }; int i; for (i = 0; i < 4; i++) { if (isValid(dates[i])) printf("%02d %s %d ✓ Valid\n", dates[i].day, months[dates[i].month - 1], dates[i].year); else printf("%02d/%02d/%d ✗ Invalid date!\n", dates[i].day, dates[i].month, dates[i].year); } return 0; }
15 August 2005 ✓ Valid 31/04/2024 ✗ Invalid date! 29/02/2023 ✗ Invalid date! 01 January 2025 ✓ Valid
example 9
9
🔢 Complex Numbers — Add and Multiply
Struct with real and imaginary parts — arithmetic on complex numbers
Mathematics
A
Complex struct holds the real and imaginary parts of a complex number. Implements addition (add reals, add imaginaries) and multiplication using the formula (a+bi)(c+di) = (ac−bd) + (ad+bc)i. Prints results in a+bi form.
#include <stdio.h> typedef struct { float real; float imag; } Complex; void printC(Complex c) { if (c.imag >= 0) printf("%.1f + %.1fi", c.real, c.imag); else printf("%.1f - %.1fi", c.real, -c.imag); } Complex addC(Complex a, Complex b) { Complex result; result.real = a.real + b.real; result.imag = a.imag + b.imag; return result; } Complex mulC(Complex a, Complex b) { Complex result; /* (a+bi)(c+di) = (ac-bd) + (ad+bc)i */ result.real = a.real*b.real - a.imag*b.imag; result.imag = a.real*b.imag + a.imag*b.real; return result; } int main() { Complex c1 = {3.0, 2.0}; /* 3 + 2i */ Complex c2 = {1.0, -4.0}; /* 1 - 4i */ printf("c1 = "); printC(c1); printf("\n"); printf("c2 = "); printC(c2); printf("\n"); printf("\nc1 + c2 = "); printC(addC(c1, c2)); printf("\n"); printf("c1 * c2 = "); printC(mulC(c1, c2)); printf("\n"); return 0; }
c1 = 3.0 + 2.0i c2 = 1.0 - 4.0i c1 + c2 = 4.0 - 2.0i c1 * c2 = 11.0 - 10.0i
A function can return a struct! Both
addC() and mulC() return a Complex struct — not just an int or float. This is one of the most powerful features of structs in C.example 10
10
📚 Library System — Search by Title
5 books with title, author, year, price — display all and search
Complete system
A mini library catalogue — 5 books in an array of
Book structs. Displays all books in a formatted table, then searches by title using strstr() (partial match — finds the book even if you only type part of the title).
#include <stdio.h> #include <string.h> typedef struct { char title[40]; char author[25]; int year; float price; } Book; int main() { Book lib[5] = { {"Let Us C", "Y. Kanetkar", 2020, 350.0}, {"C Programming Language", "K&R", 2019, 499.0}, {"Head First C", "D. Griffiths", 2021, 699.0}, {"C By Example", "Greg Perry", 2018, 280.0}, {"Expert C Programming", "P. van Linden", 2020, 560.0} }; int i, found = 0; char query[40]; /* Display all books */ printf("%-26s %-16s %5s %7s\n", "Title","Author","Year","Price"); printf("%s\n", "------------------------------------------------------"); for (i = 0; i < 5; i++) printf("%-26s %-16s %5d %7.2f\n", lib[i].title, lib[i].author, lib[i].year, lib[i].price); /* Search — partial title match with strstr() */ printf("\nSearch book (partial title): "); scanf("%s", query); printf("\nResults:\n"); for (i = 0; i < 5; i++) { if (strstr(lib[i].title, query) != NULL) { printf(" Found: \"%s\" by %s — Rs %.2f\n", lib[i].title, lib[i].author, lib[i].price); found++; } } if (!found) printf(" No books found.\n"); return 0; }
Title Author Year Price ------------------------------------------------------ Let Us C Y. Kanetkar 2020 350.00 C Programming Language K&R 2019 499.00 Head First C D. Griffiths 2021 699.00 C By Example Greg Perry 2018 280.00 Expert C Programming P. van Linden 2020 560.00 Search book (partial title): C Results: Found: "Let Us C" by Y. Kanetkar — Rs 350.00 Found: "C Programming Language" by K&R — Rs 499.00 Found: "Head First C" by D. Griffiths — Rs 699.00 Found: "C By Example" by Greg Perry — Rs 280.00 Found: "Expert C Programming" by P. van Linden — Rs 560.00
strstr(haystack, needle) returns a pointer if the needle string is found anywhere inside haystack. If not found, returns NULL. This gives partial matching — searching "C" finds every book with C in the title.
checklist
- Ex 1 — fgets for full name input, strcspn to strip the newline
- Ex 2 — struct members used in arithmetic: r1.length * r1.width
- Ex 3 — struct balance updated directly: acc.balance += amount
- Ex 4 — array of structs with for loop: emp[i].basic, emp[i].hra
- Ex 5 — costlyIdx tracks the index of the most expensive item
- Ex 6 — carry logic: if total inches ≥ 12, convert to feet
- Ex 7 — topIdx and lastIdx both found in a single loop pass
- Ex 8 — isValid() takes a struct by value and returns 0 or 1
- Ex 9 — a function CAN return a struct (Complex addC returns Complex)
- Ex 10 — strstr() for partial title search, returns NULL if not found