Practical C programs demonstrating input/output operations: calculators, temperature converters, pattern printing, menu-driven programs, and formatted output. Complete I/O examples with explanations.
The best way to solidify your understanding of C input/output is through practice. This collection of practical programs demonstrates how to combine printf(), scanf(), fgets(), getchar(), and other I/O functions to build real, useful programs. Each example is complete and ready to compile.
Program 1: Simple Calculator
#include <stdio.h>
int main() {
float num1, num2, result;
char operator;
printf("========== Simple Calculator ==========\n");
printf("Enter expression (e.g., 5 + 3): ");
scanf("%f %c %f", &num1, &operator, &num2);
switch (operator) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/':
if (num2 == 0) {
printf("Error: Division by zero!\n");
return 1;
}
result = num1 / num2;
break;
case '%':
result = (int)num1 % (int)num2;
break;
default:
printf("Error: Invalid operator '%c'\n", operator);
return 1;
}
printf("%.2f %c %.2f = %.2f\n", num1, operator, num2, result);
return 0;
}
========== Simple Calculator ==========
Enter expression (e.g., 5 + 3): 15.5 * 3.2
15.50 * 3.20 = 49.60
Program 2: Temperature Converter
#include <stdio.h>
int main() {
float temp;
int choice;
printf("===== Temperature Converter =====\n");
printf("1. Celsius to Fahrenheit\n");
printf("2. Fahrenheit to Celsius\n");
printf("3. Celsius to Kelvin\n");
printf("Choose conversion (1-3): ");
scanf("%d", &choice);
printf("Enter temperature: ");
scanf("%f", &temp);
switch (choice) {
case 1:
printf("%.2f°C = %.2f°F\n", temp, (temp * 9.0/5.0) + 32);
break;
case 2:
printf("%.2f°F = %.2f°C\n", temp, (temp - 32) * 5.0/9.0);
break;
case 3:
printf("%.2f°C = %.2f K\n", temp, temp + 273.15);
break;
default:
printf("Invalid choice!\n");
}
return 0;
}
===== Temperature Converter =====
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
3. Celsius to Kelvin
Choose conversion (1-3): 1
Enter temperature: 100
100.00°C = 212.00°F
Program 3: Student Report Card
#include <stdio.h>
int main() {
char name[50];
int roll;
float marks[5];
float total = 0, percentage;
char *subjects[] = {"Math", "Science", "English", "History", "Computer"};
printf("===== Student Report Card =====\n\n");
printf("Enter student name: ");
scanf(" %[^\n]", name);
printf("Enter roll number: ");
scanf("%d", &roll);
printf("\nEnter marks (out of 100):\n");
for (int i = 0; i < 5; i++) {
printf(" %s: ", subjects[i]);
scanf("%f", &marks[i]);
total += marks[i];
}
percentage = total / 5;
printf("\n╔══════════════════════════════════╗\n");
printf("║ REPORT CARD ║\n");
printf("╠══════════════════════════════════╣\n");
printf("║ Name: %-25s ║\n", name);
printf("║ Roll: %-25d ║\n", roll);
printf("╠══════════════════════════════════╣\n");
printf("║ %-10s %10s %10s ║\n", "Subject", "Marks", "Grade");
printf("║ %-10s %10s %10s ║\n", "-------", "-----", "-----");
for (int i = 0; i < 5; i++) {
char grade;
if (marks[i] >= 90) grade = 'A';
else if (marks[i] >= 80) grade = 'B';
else if (marks[i] >= 70) grade = 'C';
else if (marks[i] >= 60) grade = 'D';
else grade = 'F';
printf("║ %-10s %10.1f %10c ║\n", subjects[i], marks[i], grade);
}
printf("╠══════════════════════════════════╣\n");
printf("║ Total: %8.1f / 500 ║\n", total);
printf("║ Percent: %8.2f%% ║\n", percentage);
printf("║ Result: %-8s ║\n",
(percentage >= 40) ? "PASS" : "FAIL");
printf("╚══════════════════════════════════╝\n");
return 0;
}
===== Student Report Card =====
Enter student name: John Smith
Enter roll number: 101
Enter marks (out of 100):
Math: 85
Science: 92
English: 78
History: 65
Computer: 95
╔══════════════════════════════════╗
║ REPORT CARD ║
╠══════════════════════════════════╣
║ Name: John Smith ║
║ Roll: 101 ║
╠══════════════════════════════════╣
║ Subject Marks Grade ║
║ ------- ----- ----- ║
║ Math 85.0 B ║
║ Science 92.0 A ║
║ English 78.0 C ║
║ History 65.0 D ║
║ Computer 95.0 A ║
╠══════════════════════════════════╣
║ Total: 415.0 / 500 ║
║ Percent: 83.00% ║
║ Result: PASS ║
╚══════════════════════════════════╝
Program 4: Number System Converter
#include <stdio.h>
int main() {
int num;
printf("Enter a decimal number: ");
scanf("%d", &num);
printf("\n=== Number System Conversions ===\n");
printf("Decimal: %d\n", num);
printf("Octal: %o\n", num);
printf("Hexadecimal: %X\n", num);
// Binary conversion
printf("Binary: ");
if (num == 0) {
printf("0");
} else {
int binary[32];
int i = 0;
int temp = num;
while (temp > 0) {
binary[i++] = temp % 2;
temp /= 2;
}
for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]);
}
}
printf("\n");
printf("\nFormatted outputs:\n");
printf("With prefix: 0%o (octal), 0x%X (hex)\n", num, num);
printf("Padded hex: %08X\n", num);
return 0;
}
Enter a decimal number: 255
=== Number System Conversions ===
Decimal: 255
Octal: 377
Hexadecimal: FF
Binary: 11111111
Formatted outputs:
With prefix: 0377 (octal), 0xFF (hex)
Padded hex: 000000FF
#include <stdio.h>
int main() {
int n;
printf("Enter number of rows: ");
scanf("%d", &n);
// Right-aligned number triangle
printf("\n--- Right Triangle ---\n");
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n - i; j++) {
printf(" ");
}
for (int j = 1; j <= i; j++) {
printf("%2d", j);
}
printf("\n");
}
// Multiplication table (formatted)
printf("\n--- Multiplication Table (1-%d) ---\n", n);
printf("%4s", "");
for (int i = 1; i <= n; i++) {
printf("%4d", i);
}
printf("\n ");
for (int i = 1; i <= n; i++) {
printf("----");
}
printf("\n");
for (int i = 1; i <= n; i++) {
printf("%2d |", i);
for (int j = 1; j <= n; j++) {
printf("%4d", i * j);
}
printf("\n");
}
return 0;
}
Enter number of rows: 5
--- Right Triangle ---
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
--- Multiplication Table (1-5) ---
1 2 3 4 5
--------------------
1 | 1 2 3 4 5
2 | 2 4 6 8 10
3 | 3 6 9 12 15
4 | 4 8 12 16 20
5 | 5 10 15 20 25#include <stdio.h>
#include <string.h>
int main() {
int choice;
char input[100];
do {
printf("\n===== Text Utility Menu =====\n");
printf("1. Count characters\n");
printf("2. Convert to uppercase\n");
printf("3. Reverse string\n");
printf("4. Check palindrome\n");
printf("0. Exit\n");
printf("Choice: ");
scanf("%d", &choice);
while (getchar() != '\n'); // Clear buffer
if (choice == 0) break;
if (choice >= 1 && choice <= 4) {
printf("Enter text: ");
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = '\0';
}
switch (choice) {
case 1:
printf("Length: %lu characters\n", strlen(input));
break;
case 2:
printf("Uppercase: ");
for (int i = 0; input[i]; i++) {
if (input[i] >= 'a' && input[i] <= 'z')
putchar(input[i] - 32);
else
putchar(input[i]);
}
putchar('\n');
break;
case 3:
printf("Reversed: ");
for (int i = strlen(input) - 1; i >= 0; i--) {
putchar(input[i]);
}
putchar('\n');
break;
case 4: {
int len = strlen(input);
int isPalin = 1;
for (int i = 0; i < len / 2; i++) {
if (input[i] != input[len - 1 - i]) {
isPalin = 0;
break;
}
}
printf("\"%s\" is %sa palindrome\n", input, isPalin ? "" : "NOT ");
break;
}
default:
printf("Invalid choice!\n");
}
} while (choice != 0);
printf("Goodbye!\n");
return 0;
}
===== Text Utility Menu =====
1. Count characters
2. Convert to uppercase
3. Reverse string
4. Check palindrome
0. Exit
Choice: 2
Enter text: hello world
Uppercase: HELLO WORLD
===== Text Utility Menu =====
1. Count characters
2. Convert to uppercase
3. Reverse string
4. Check palindrome
0. Exit
Choice: 4
Enter text: racecar
"racecar" is a palindrome
===== Text Utility Menu =====
Choice: 0
Goodbye!
#include <stdio.h>
int main() {
char items[5][30];
float prices[5];
int quantities[5];
int n;
printf("How many items (max 5)? ");
scanf("%d", &n);
while (getchar() != '\n');
for (int i = 0; i < n; i++) {
printf("\nItem %d name: ", i + 1);
fgets(items[i], sizeof(items[i]), stdin);
items[i][strcspn(items[i], "\n")] = '\0';
printf("Price: $");
scanf("%f", &prices[i]);
printf("Quantity: ");
scanf("%d", &quantities[i]);
while (getchar() != '\n');
}
// Print receipt
float subtotal = 0;
printf("\n");
printf("┌────────────────────────────────────────┐\n");
printf("│ SHOPPING RECEIPT │\n");
printf("├──────────────────┬─────┬───────┬───────┤\n");
printf("│ %-16s │ Qty │ Price │ Total │\n", "Item");
printf("├──────────────────┼─────┼───────┼───────┤\n");
for (int i = 0; i < n; i++) {
float total = prices[i] * quantities[i];
subtotal += total;
printf("│ %-16.16s │ %3d │ %5.2f │%6.2f │\n",
items[i], quantities[i], prices[i], total);
}
float tax = subtotal * 0.08;
printf("├──────────────────┴─────┴───────┼───────┤\n");
printf("│ Subtotal: │%6.2f │\n", subtotal);
printf("│ Tax (8%%): │%6.2f │\n", tax);
printf("│ TOTAL: │%6.2f │\n", subtotal + tax);
printf("└────────────────────────────────┴───────┘\n");
return 0;
}
How many items (max 5)? 3
Item 1 name: Laptop
Price: $999.99
Quantity: 1
Item 2 name: Mouse
Price: $29.99
Quantity: 2
Item 3 name: USB Cable
Price: $9.99
Quantity: 3
┌────────────────────────────────────────┐
│ SHOPPING RECEIPT │
├──────────────────┬─────┬───────┬───────┤
│ Item │ Qty │ Price │ Total │
├──────────────────┼─────┼───────┼───────┤
│ Laptop │ 1 │999.99 │999.99 │
│ Mouse │ 2 │ 29.99 │ 59.98 │
│ USB Cable │ 3 │ 9.99 │ 29.97 │
├──────────────────┴─────┴───────┼───────┤
│ Subtotal: │1089.94│
│ Tax (8%): │ 87.20 │
│ TOTAL: │1177.14│
└────────────────────────────────┴───────┘
#include <stdio.h>
#include <string.h>
int main() {
char buffer[100];
int age;
int valid;
// Robust input validation
do {
printf("Enter your age (1-150): ");
fgets(buffer, sizeof(buffer), stdin);
valid = sscanf(buffer, "%d", &age);
if (valid != 1) {
printf("Error: Please enter a number.\n");
} else if (age < 1 || age > 150) {
printf("Error: Age must be between 1 and 150.\n");
valid = 0;
}
} while (!valid);
printf("Your age is: %d\n", age);
if (age < 13) printf("Category: Child\n");
else if (age < 18) printf("Category: Teenager\n");
else if (age < 60) printf("Category: Adult\n");
else printf("Category: Senior\n");
return 0;
}
Enter your age (1-150): abc
Error: Please enter a number.
Enter your age (1-150): 200
Error: Age must be between 1 and 150.
Enter your age (1-150): 25
Your age is: 25
Category: Adult
Interview Questions
Q1: How would you read a full line of input that may contain spaces?
Use fgets(buffer, size, stdin) or scanf(" %[^\n]", buffer). The %[^\n] scanset reads everything until a newline. Never use gets() — it's unsafe and removed from C11. After fgets(), remove the trailing newline with buffer[strcspn(buffer, "\n")] = '\0'.
Q2: How do you handle invalid input gracefully in C?
Check scanf()'s return value — it returns the number of items successfully read. If it returns 0, the input didn't match. Use fgets() + sscanf() for more robust handling: read the entire line first, then parse it. Always clear the input buffer after failed reads with while(getchar() != '\n');.
Q3: How do you create aligned table output in C?
Use width specifiers in printf(): %-15s for left-aligned strings in a 15-char field, %8.2f for right-aligned floats with 2 decimal places in an 8-char field. Combine - flag for left alignment and numeric width for consistent column sizes.
Q4: What is the difference between printf() and puts() for printing strings?
puts(str) is equivalent to printf("%s\n", str) — it outputs the string and adds a newline. puts() cannot format variables; it only prints raw strings. It's slightly faster because there's no format parsing. Use puts() for simple string output and printf() when formatting is needed.
Summary
- Combine
printf() formatting with scanf()/fgets() for interactive programs - Use width specifiers and alignment flags for professional table output
- Always validate user input — check
scanf() return values and use range checks fgets() + sscanf() is the safest pattern for robust input handling- Menu-driven programs use loops with switch statements and proper buffer clearing
- Format specifiers like
%-10s, %8.2f, %05d give precise output control - Clear the input buffer between different types of reads to avoid issues