- C Programs
- C Programs - Home
Basics of C Programming (Introductory Programs)
- Hello World
- Print your name, age, and address
- Display "C Programming is Powerful"
- Input and display integer, float, and character
- Swap two numbers (using third variable)
- Swap two numbers (without third variable)
- Find ASCII value of a character
- Find size of data types (int, float, etc.)
- Convert Celsius to Fahrenheit
- Convert Fahrenheit to Celsius
- Convert kilometers to miles
- Area and perimeter of a rectangle
- Area and circumference of a circle
- Menu-Driven Shape Calculations
- Menu-Driven Geometry Calculations
- Menu-Driven Extended Geometry Calculations
- Complete 2D + 3D Geometry Calculator
- Volume of a Cube
- Volume of a Cuboid
- Volume of a Sphere
- Volume of a Cylinder
- Volume of a Cone
- Surface Area of a Cube
- Surface Area of a Cuboid
- Surface Area of a Sphere
- Surface Area of a Cylinder
- Surface Area of a Cone
- Surface Area of a Hemisphere
- Financial Programs in C
- Simple interest calculation
- Compound interest calculation
- Simple Interest and Compound Interest Difference Calculation
- Simple Interest vs Compound Interest Year wise Table Calculation
- Graphically Compare of Simple Interest vs Compound Interest using ASCII bars Program
- Menu Driven Simple Interest and Compound Interest Program
- Mini Banking System with Simple Interest and Compound Interest Program
- EMI Calculator Program
- Menu Driven Loan Calculator
- Loan Amortization Table Program
- Total Payment and Total Interest Paid on a Loan Program
- EMI Comparison with Different Tenures and Rates Program
- Calculate gross salary
- Convert days to years, weeks, days
- Evaluate arithmetic expression
- Display ASCII table
Control Statements & Loops in C
- Decision Making Programs in C
- Check whether a number is positive, negative, or zero
- Check whether a number is even or odd
- Check whether a number is Positive, Negative, or Zero and Even or Odd
- Menu-Driven Number Check of Positive, Negative, or Zero and Even or Odd
- Find the largest of two numbers
- Find the largest of three numbers
- Check whether a year is a leap year
- Check whether a character is a vowel or consonant
- Check whether a character is uppercase, lowercase, digit, or special symbol
- Find the grade of a student (marks-based)
- Check whether a person is eligible to vote
- Find absolute value of a number
- Simple calculator using if-else
- Simple calculator using switch-case
- Print day of week (switch-case)
- Check whether triangle is valid (angles sum = 180)
- Check whether triangle is equilateral, isosceles, or scalene
- Find roots of quadratic equation
- Electricity bill calculation (slab-based)
- Calculate bonus for employee based on salary & service years
- Check whether a character is alphabet or not
- Check whether a character is a digit or special character
- Check whether a number is divisible by 5 and 11
- Menu-driven program: area of circle, rectangle, triangle
- Find greatest among four numbers (nested if)
- Find greatest among four numbers (ternary operators)
- Loop Programs in C
- Print first N natural numbers
- Print Natural Numbers from N down to 1 (Reverse Order)
- Print first N even numbers
- Print first N odd numbers
- Print multiplication table of a number
- Print sum of first N natural numbers
- Print sum of first N even numbers
- Print sum of first N odd numbers
- Print factorial of a number (loop)
- Generate Fibonacci series up to N terms
- Print reverse of a number
- Print reverse of a Negative number
- Count digits in a number
- Sum of digits of a number
- Product of digits of a number
- Check whether a number is palindrome (loop)
- Check whether a number is Armstrong (loop)
- Check whether a number is Strong Number (loop)
- Check whether a number is Perfect Number (loop)
- Check whether a number is prime (loop)
- Print all prime numbers between 1 and N
- Print all Armstrong numbers between 1 and N
- Print all palindrome numbers in a given range
- Print all factors of a number
- Find HCF (GCD) of two numbers (loop)
- Find LCM of two numbers (loop)
- Print pyramid pattern (star *)
- Print inverted pyramid pattern
- Print Floyd’s triangle (1, 2, 3...)
- Print Pascal’s triangle (loop)
- Print Number Pyramid Pattern
- Print Inverted Number Pyramid Pattern
- Print Number Diamond Pattern
Functions
- Function to add two numbers
- Function to subtract two numbers
- Function to multiply two numbers
- Function to divide two numbers
- Function for factorial (iteration)
- Factorial (recursion)
- Fibonaaci Series (iteration)
- Fibonacci (recursion)
- GCD using function
- GCD using Recursive function
- LCM using function
- LCM using Recursive function
- LCM using GCD Recursive function
- Swap numbers using function
- Prime number check using function
- Prime number check using Recursive function
- Palindrome check using function
- Palindrome check using Recursive function
- Armstrong Number check using function
- Armstrong Number check using Recursive function
- Function returning array maximum
- Function returning Array Minimum
- Recursive Function to print sum of digits of a number
- Recursive Function to reverse a number
- Recursive Function for power calculation
- Function to check strong number
- Function for perfect number
- Function overloading using macros (simulate)
- Nested function calls example
Arrays
- Input and display array elements
- Sum of array elements
- Average of array elements
- Maximum in array
- Minimum in array
- Linear Search Program
- Binary Search Program
- Bubble Sort Program
- Selection Sort Program
- Insertion Sort Program
- Merge Sort Program
- Quick Sort Program
- Merge two arrays
- Merge Two Sorted Arrays (Sorted Merge)
- Copy array to another
- Reverse array elements
- Count even and odd numbers in array
- Sum of Even and Odd Elements in Array
- Count positive, negative, and zero elements in an array
- Sum of Positive and Negative Numbers in Array
- Frequency of array elements
- Find unique elements in an array
- Find duplicate elements in an array
- Remove duplicate elements
- Find second largest element
- Find second smallest element
- Rotate array left
- Rotate array right
- Matrix addition (2D array)
- Matrix Subtraction (2D array)
- Matrix multiplication (2D array)
- Transpose of a matrix
- Sum of diagonals of a Square Matrix
- Display Matrix Upper and Lower Triangle
- Matrix Sum (Row-wise and Column-wise)
Strings
- Input and display string
- Find string length (without strlen())
- Copy string (without strcpy())
- Concatenate two strings
- Compare two strings
- Reverse string
- Check palindrome string
- Count vowels, consonants
- Count digits, spaces, special chars
- Count words in string
- Convert string to uppercase
- Convert string to lowercase
- Toggle case of characters
- Find frequency of characters
- Remove vowels from string
- Remove spaces from string
- Remove All Digits from a String
- Remove Special Characters from a String
- Remove duplicate characters
- Check anagram strings
- Sort characters in string
- Sort array of strings
- Longest word in a sentence
- Shortest word in a sentence
- Count Occurrences of a Word in a Sentence
Pointers
- Pointer basics (address, value)
- Pointer arithmetic
- Add two numbers using pointers
- Swap numbers using pointers
- Sum of array using pointers
- Find length of string using pointers
- Reverse string using pointers
- Compare two strings using pointers
- Concatenate strings using pointers
- Pointer to pointer (double pointer)
- Function returning pointer
- Pass array to function using pointers
- Dynamic array with pointers
- Matrix addition using pointers
- Matrix multiplication using pointers
- Matrix Transpose using pointers
- Matrix Trace and Sum of Diagonals using Pointers
- Sum of Rows and Columns using Pointers
- Interchange rows and columns (Matrix Swap) using Pointers
- Matrix Scalar Multiplication using Pointers
- Compare Two Matrices using Pointers
- Pointer to structure
- Structure with Dynamic Memory Allocation using Pointer
- Access structure elements with pointer
- Array of Structures Using Pointers
- Array of pointers
- String array with pointers
- Pointer and function (call by reference)
- Swap two arrays using pointers
Structures and Unions
- Student structure (input & display)
- Array of structures (students list)
- Nested structures (employee with address)
- Array of Nested Structures (Multiple Employees with Address)
- Passing structure to function
- Returning structure from function
- Complex number addition using structures
- Compare two dates using structures
- Bank account management (structure)
- Store book details using structure
- Store employee details (salary, age, etc.)
- Find student with highest marks (array of structures)
- Sort students by marks
- Demonstrate Memory Sharing in Union
- Structure vs Union (Memory Allocation & Data Sharing)
- Store cricket players’ details
- Store car details (company, model, price)
- Store hospital patient details
- Online shopping cart using structures
- Store weather report data
- Library management using structures
- Store exam records with pass/fail result
Dynamic Memory Allocation
- Allocate array using malloc()
- Allocate array using calloc()
- Reallocate array using realloc()
- Free memory using free()
- Input & print dynamic array
- Average of dynamic array
- Dynamic string input
- Reverse string using dynamic memory
- Dynamic matrix allocation
- Matrix addition using dynamic memory
- Matrix multiplication using dynamic memory
- Dynamic structure allocation (student info)
- Linked list creation with malloc()
- Insert node dynamically in linked list
- Delete node dynamically in linked list
- Stack using dynamic memory
- Queue using dynamic memory
- Dynamic 2D array (pointer-to-pointer)
- Dynamic 2D array (integer matrix) using pointer to pointer and returning it from a function
- Dynamic array resizing at runtime
- Dynamic sorting of array
- Dynamic string concatenation
File Handling
- Create and write to a file
- Read from a file
- Append to a file
- Copy file contents
- Count characters in file
- Count words in file
- Count lines in file
- Count vowels, consonants, digits and space in file
- Check whether file exists
- Merge two files into one
- Find frequency of a word in file
- Store student records in file
- Retrieve student records from file
- Student Record Management System using File Handling
- Update student record in file
- Delete student record from file
- Sort student records stored in file
- Encrypt file content
- Decrypt file content
- Find largest word in a file
- Find smallest word in a file
- Store employee payroll system in file
- Payroll Generation for employee
- Employee Payroll System with Payslip File Export
- Implement mini database using file handling
Data Structures in C
- Singly linked list creation
- Display linked list
- Insert node at beginning
- Insert node at end
- Insert node at position
- Delete node from beginning
- Delete node from end
- Delete Node from a Specific Position
- Delete node by Value
- Search element in Linked List
- Count Total Nodes in a Linked List
- Sum of all Nodes in a Linked List
- Maximum and Minimum Element in Linked List
- Reverse a Singly Linked List
- Doubly Linked List - Creation
- Doubly Linked List - Insert Node at the Beginning
- Doubly Linked List - Insert Node at the End
- Doubly Linked List - Insert Node at a Specific Position
- Deletion Operations in a Doubly Linked List - Beginning, End, and Position
- Reversal of Doubly Linked List
- Circular Linked List Creation
- Circular Linked List - Insertion Operations
- Circular Linked List - Deletion Operations
- Circular Linked List - Insertion, Deletion, Traversal Operations
- Stack Implementation Using Array
- Stack Implementation Using Linked List
- Queue Implementation Using Array
- Queue Implementation Using Linked List
- Circular Queue Implementation Using Array
- Circular Queue Implementation Using Linked List
- Circular Queue Implementation - Real World Example
- Binary Tree Creation
- Inorder Traversal in Binary Tree
- Inorder Traversal - Iterative Method
- Preorder Traversal in Binary Tree
- Postorder Traversal in Binary Tree
- Binary Search Tree Insertion
- Binary Search Tree (BST) — Search Operation
- Binary Search Tree (BST) — Deletion Operation
- Binary Search Tree Traversals
- Binary Search Tree — Level Order Traversal (BFS)
- Binary Search Tree — Height and Leaf Node Count of BST
- Binary Search Tree — Counting Total Nodes and Internal Nodes of BST
- Binary Search Tree — Mirror Image Creation
- Binary Search Tree — Counting Left and Right Subtree Nodes
- Binary Search Tree — Finding Minimum and Maximum Element in a BST
- Binary Search Tree — Searching for an Element in a BST
- Binary Search Tree — Deleting a Node from a Binary Search Tree
- Binary Search Tree — Finding the Height (or Depth) of a BST
- Binary Search Tree — Counting Total Number of Nodes, Leaf Nodes, and Internal Nodes
- Graph Representation (Adjacency Matrix)
- Graph Representation using Adjacency List
- BFS (Breadth First Search)
- DFS (Depth First Search)
- Graph Cycle Detection using DFS (Depth-First Search)
- Bubble Sort
- Quick Sort
- Merge Sort
- Heap Sort
- Binary Search
- Hash Table Basics
Advanced C Programs
- Command line arguments sum
- Command line arguments word count
- Display environment variables
- Bitwise AND, OR, XOR
- Bitwise left shift, right shift
- Check if number is power of 2
- Find number of set bits (Brian Kernighan’s algorithm)
- Endianness check
- Macro definition demo
- Create header file and include it
- Error handling using errno
- Pointer to function example
- Function pointer for callback
- Matrix multiplication (optimized)
- Sparse matrix representation
- Polynomial addition using linked list
- Polynomial multiplication using linked list
- Mini calculator with functions + switch
- Tic-tac-toe game
- Snake game (console-based)
- Student grading system with structures + files
- Hospital management mini project
- Bank management mini project
User-Defined Number Programs in C
- Check whether a number is even or odd
- Find the largest of two numbers (without built-in max)
- Find the largest of three numbers
- Check whether a number is prime
- Display all prime numbers between 1 and N
- Check whether a number is palindrome
- Check whether a number is Armstrong
- Find factorial of a number (loop)
- Factorial using recursion
- Generate Fibonacci series (loop)
- Generate Fibonacci series (recursion)
- Reverse a number
- Sum of digits of a number
- Product of digits of a number
- Count digits in a number
- Find GCD of two numbers (loop)
- Find LCM of two numbers
- Check whether a number is strong (sum of factorial of digits = number)
- Check whether a number is perfect (sum of divisors = number)
- Find power of a number (without pow())
- Convert decimal to binary
- Convert binary to decimal
- Convert octal to decimal
- Convert decimal to octal
- Convert decimal to hexadecimal
- Check whether number is automorphic (square ends with same digits)
- Check whether number is neon (sum of digits of square = number)
- Print factors of a number
- Sum of N natural numbers (loop)
- Sum of N natural numbers (recursion)
User-Defined String Programs in C
- Find length of a string (without strlen())
- Copy one string to another (without strcpy())
- Concatenate two strings (without strcat())
- Compare two strings (without strcmp())
- Reverse a string (user-defined)
- Check whether a string is palindrome
- Convert string to uppercase (without strupr())
- Convert string to lowercase (without strlwr())
- Toggle case of each character
- Count vowels in a string
- Count consonants in a string
- Count digits in a string
- Count special characters in a string
- Count words in a string
- Remove all vowels from a string
- Remove all spaces from a string
- Remove duplicate characters
- Frequency of each character in string
- Find the longest word in a sentence
- Find the shortest word in a sentence
- Sort characters of string in ascending order
- Sort array of strings alphabetically
- Check whether two strings are anagrams
- Find first non-repeating character
- Replace a character in a string with another
- Remove particular character from string
- Count occurrences of a given word in string
- Check substring existence (without strstr())
- Extract substring (user-defined)
- Rotate string left/right by N characters
(using if, if-else, nested if, switch-case)
(using for, while, do-while loops)
C Programs
![]() Share with a Friend |
File Handling in C
Employee Payroll System with Payslip File Export
Employee Payroll System so that every time you generate a payslip, it is also saved automatically as a .txt file (for example: Payslip_102.txt).
This allows employees (or users on your ITDeveloper.in site) to download or print their salary slips easily.
C Program: Employee Payroll System with Payslip File Export
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Employee {
int id;
char name[50];
float basicSalary;
float hra, da, gross, tax, net;
};
// Function to calculate salary components
void calculateSalary(struct Employee *e) {
e->hra = e->basicSalary * 0.20; // 20% HRA
e->da = e->basicSalary * 0.10; // 10% DA
e->gross = e->basicSalary + e->hra + e->da;
// Simple tax logic
if (e->gross > 50000)
e->tax = e->gross * 0.10; // 10% tax
else if (e->gross > 30000)
e->tax = e->gross * 0.05; // 5% tax
else
e->tax = 0;
e->net = e->gross - e->tax;
}
// Add employee record
void addEmployee() {
FILE *fp;
struct Employee e;
fp = fopen("payroll.dat", "ab");
if (!fp) {
printf("Error opening file!\n");
return;
}
printf("\nEnter Employee ID: ");
scanf("%d", &e.id);
printf("Enter Name: ");
scanf("%s", e.name);
printf("Enter Basic Salary: ");
scanf("%f", &e.basicSalary);
calculateSalary(&e);
fwrite(&e, sizeof(e), 1, fp);
fclose(fp);
printf("Employee record added successfully!\n");
}
// Display all employees
void displayEmployees() {
FILE *fp;
struct Employee e;
fp = fopen("payroll.dat", "rb");
if (!fp) {
printf("No records found!\n");
return;
}
printf("\n--- Employee Payroll Records ---\n");
printf("%-10s %-15s %-12s %-10s %-10s %-10s %-10s\n",
"ID", "Name", "Basic", "HRA", "DA", "Gross", "Net");
while (fread(&e, sizeof(e), 1, fp)) {
printf("%-10d %-15s %-12.2f %-10.2f %-10.2f %-10.2f %-10.2f\n",
e.id, e.name, e.basicSalary, e.hra, e.da, e.gross, e.net);
}
fclose(fp);
}
// Generate payslip and save to text file
void generatePayslip() {
FILE *fp, *slipFile;
struct Employee e;
int id, found = 0;
char filename[100];
fp = fopen("payroll.dat", "rb");
if (!fp) {
printf("Error opening payroll file!\n");
return;
}
printf("\nEnter Employee ID to generate payslip: ");
scanf("%d", &id);
while (fread(&e, sizeof(e), 1, fp)) {
if (e.id == id) {
found = 1;
// Generate file name
sprintf(filename, "Payslip_%d.txt", e.id);
slipFile = fopen(filename, "w");
if (!slipFile) {
printf("Error creating payslip file!\n");
fclose(fp);
return;
}
// Write formatted payslip to file
fprintf(slipFile, "==============================================\n");
fprintf(slipFile, " EMPLOYEE PAYSLIP\n");
fprintf(slipFile, "==============================================\n");
fprintf(slipFile, "Employee ID : %d\n", e.id);
fprintf(slipFile, "Employee Name : %s\n", e.name);
fprintf(slipFile, "----------------------------------------------\n");
fprintf(slipFile, "Basic Salary : %.2f\n", e.basicSalary);
fprintf(slipFile, "HRA (20%%) : %.2f\n", e.hra);
fprintf(slipFile, "DA (10%%) : %.2f\n", e.da);
fprintf(slipFile, "Gross Salary : %.2f\n", e.gross);
fprintf(slipFile, "Tax Deduction : %.2f\n", e.tax);
fprintf(slipFile, "----------------------------------------------\n");
fprintf(slipFile, "Net Salary : %.2f\n", e.net);
fprintf(slipFile, "==============================================\n");
fclose(slipFile);
// Display message
printf("\nPayslip generated successfully!\n");
printf("Saved as: %s\n\n", filename);
// Also print on screen
printf("==============================================\n");
printf(" EMPLOYEE PAYSLIP\n");
printf("==============================================\n");
printf("Employee ID : %d\n", e.id);
printf("Employee Name : %s\n", e.name);
printf("----------------------------------------------\n");
printf("Basic Salary : %.2f\n", e.basicSalary);
printf("HRA (20%%) : %.2f\n", e.hra);
printf("DA (10%%) : %.2f\n", e.da);
printf("Gross Salary : %.2f\n", e.gross);
printf("Tax Deduction : %.2f\n", e.tax);
printf("----------------------------------------------\n");
printf("Net Salary : %.2f\n", e.net);
printf("==============================================\n");
break;
}
}
if (!found)
printf("Employee not found!\n");
fclose(fp);
}
// Main menu
int main() {
int choice;
do {
printf("\n===== Employee Payroll System =====\n");
printf("1. Add Employee\n");
printf("2. Display All Employees\n");
printf("3. Generate Payslip (Save as File)\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1: addEmployee(); break;
case 2: displayEmployees(); break;
case 3: generatePayslip(); break;
case 4: printf("Exiting...\n"); break;
default: printf("Invalid choice!\n");
}
} while (choice != 4);
return 0;
}
Output
OUTPUT :
Generated File Content (Payslip_102.txt)
==============================================
EMPLOYEE PAYSLIP
==============================================
Employee ID : 102
Employee Name : Alice
----------------------------------------------
Basic Salary : 45000.00
HRA (20%) : 9000.00
DA (10%) : 4500.00
Gross Salary : 58500.00
Tax Deduction : 5850.00
----------------------------------------------
Net Salary : 52650.00
==============================================
How It Works
- When you choose Option 3: Generate Payslip,
- The program looks up the employee by ID.
- Creates a text file like Payslip_102.txt.
- Writes the formatted salary details into it.
- Displays the same payslip on screen.
- You can open this file in any text editor (Notepad, etc.) or even provide a download button if used in a web-based system.
