cpp
io exercises
03_io_exercises.cpp⚙️cpp
/**
* ============================================================
* C++ INPUT/OUTPUT EXERCISES WITH SOLUTIONS
* ============================================================
*
* Practice exercises for I/O operations.
* Try to solve each exercise before looking at the solution!
*
* Compile: g++ -std=c++17 -Wall 03_io_exercises.cpp -o io_exercises
* Run: ./io_exercises
*
* ============================================================
*/
#include <iostream>
#include <iomanip>
#include <string>
#include <limits> // For numeric_limits
using namespace std;
// Function prototypes
void exercise1_PersonalInfo();
void exercise2_Calculator();
void exercise3_TemperatureConverter();
void exercise4_FormattedTable();
void exercise5_InputValidation();
int main() {
int choice;
do {
cout << "\n============================================" << endl;
cout << " I/O EXERCISES MENU" << endl;
cout << "============================================" << endl;
cout << "1. Personal Information Form" << endl;
cout << "2. Simple Calculator" << endl;
cout << "3. Temperature Converter" << endl;
cout << "4. Formatted Table" << endl;
cout << "5. Input Validation" << endl;
cout << "0. Exit" << endl;
cout << "============================================" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1: exercise1_PersonalInfo(); break;
case 2: exercise2_Calculator(); break;
case 3: exercise3_TemperatureConverter(); break;
case 4: exercise4_FormattedTable(); break;
case 5: exercise5_InputValidation(); break;
case 0: cout << "Goodbye!" << endl; break;
default: cout << "Invalid choice!" << endl;
}
} while (choice != 0);
return 0;
}
// ============================================================
// EXERCISE 1: Personal Information Form
// ============================================================
/*
* TASK: Create a program that:
* 1. Asks for the user's full name
* 2. Asks for their age
* 3. Asks for their city
* 4. Displays a formatted summary
*/
void exercise1_PersonalInfo() {
cout << "\n--- PERSONAL INFORMATION FORM ---\n" << endl;
string fullName, city;
int age;
// Clear input buffer
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Enter your full name: ";
getline(cin, fullName);
cout << "Enter your age: ";
cin >> age;
cin.ignore(); // Clear newline
cout << "Enter your city: ";
getline(cin, city);
// Display formatted summary
cout << "\n" << string(40, '=') << endl;
cout << " PERSONAL SUMMARY" << endl;
cout << string(40, '=') << endl;
cout << left << setw(15) << "Name:" << fullName << endl;
cout << left << setw(15) << "Age:" << age << " years old" << endl;
cout << left << setw(15) << "City:" << city << endl;
cout << string(40, '=') << endl;
// Fun message based on age
if (age < 18) {
cout << "You're still young! Enjoy your youth!" << endl;
} else if (age < 30) {
cout << "Your 20s are for exploring!" << endl;
} else if (age < 50) {
cout << "Prime of your life!" << endl;
} else {
cout << "Wisdom comes with experience!" << endl;
}
}
// ============================================================
// EXERCISE 2: Simple Calculator
// ============================================================
/*
* TASK: Create a calculator that:
* 1. Takes two numbers as input
* 2. Takes an operator (+, -, *, /, %)
* 3. Displays the result with proper formatting
* 4. Handles division by zero
*/
void exercise2_Calculator() {
cout << "\n--- SIMPLE CALCULATOR ---\n" << endl;
double num1, num2, result;
char op;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter operator (+, -, *, /, %): ";
cin >> op;
cout << "Enter second number: ";
cin >> num2;
bool valid = true;
switch (op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 == 0) {
cerr << "ERROR: Division by zero!" << endl;
valid = false;
} else {
result = num1 / num2;
}
break;
case '%':
if (num2 == 0) {
cerr << "ERROR: Modulo by zero!" << endl;
valid = false;
} else {
result = static_cast<int>(num1) % static_cast<int>(num2);
}
break;
default:
cerr << "ERROR: Invalid operator!" << endl;
valid = false;
}
if (valid) {
cout << "\n" << string(30, '-') << endl;
cout << fixed << setprecision(2);
cout << num1 << " " << op << " " << num2 << " = " << result << endl;
cout << string(30, '-') << endl;
}
}
// ============================================================
// EXERCISE 3: Temperature Converter
// ============================================================
/*
* TASK: Create a temperature converter that:
* 1. Asks user for a temperature value
* 2. Asks which scale it's in (C/F/K)
* 3. Converts to all three scales
* 4. Displays with proper formatting
*/
void exercise3_TemperatureConverter() {
cout << "\n--- TEMPERATURE CONVERTER ---\n" << endl;
double temp;
char scale;
double celsius, fahrenheit, kelvin;
cout << "Enter temperature value: ";
cin >> temp;
cout << "Enter scale (C/F/K): ";
cin >> scale;
scale = toupper(scale); // Convert to uppercase
// Convert to Celsius first
switch (scale) {
case 'C':
celsius = temp;
break;
case 'F':
celsius = (temp - 32) * 5.0 / 9.0;
break;
case 'K':
celsius = temp - 273.15;
break;
default:
cerr << "Invalid scale! Use C, F, or K." << endl;
return;
}
// Convert from Celsius to all scales
fahrenheit = celsius * 9.0 / 5.0 + 32;
kelvin = celsius + 273.15;
// Display results
cout << "\n" << string(35, '=') << endl;
cout << " TEMPERATURE CONVERSIONS" << endl;
cout << string(35, '=') << endl;
cout << fixed << setprecision(2);
cout << left << setw(20) << "Celsius:" << celsius << " °C" << endl;
cout << left << setw(20) << "Fahrenheit:" << fahrenheit << " °F" << endl;
cout << left << setw(20) << "Kelvin:" << kelvin << " K" << endl;
cout << string(35, '=') << endl;
// Physical state of water
if (celsius <= 0) {
cout << "Water state: SOLID (ice)" << endl;
} else if (celsius < 100) {
cout << "Water state: LIQUID" << endl;
} else {
cout << "Water state: GAS (steam)" << endl;
}
}
// ============================================================
// EXERCISE 4: Formatted Table
// ============================================================
/*
* TASK: Create a formatted multiplication table:
* 1. Display numbers 1-10 across the top
* 2. Display numbers 1-10 down the side
* 3. Show all products with aligned columns
*/
void exercise4_FormattedTable() {
cout << "\n--- MULTIPLICATION TABLE ---\n" << endl;
const int SIZE = 10;
const int WIDTH = 5;
// Header row
cout << setw(WIDTH) << "X" << " |";
for (int i = 1; i <= SIZE; i++) {
cout << setw(WIDTH) << i;
}
cout << endl;
// Separator line
cout << string(WIDTH, '-') << "-+" << string(SIZE * WIDTH, '-') << endl;
// Table body
for (int row = 1; row <= SIZE; row++) {
cout << setw(WIDTH) << row << " |";
for (int col = 1; col <= SIZE; col++) {
cout << setw(WIDTH) << (row * col);
}
cout << endl;
}
cout << endl;
}
// ============================================================
// EXERCISE 5: Input Validation
// ============================================================
/*
* TASK: Create a program that:
* 1. Asks for a number between 1 and 100
* 2. Keeps asking until valid input is received
* 3. Handles non-numeric input gracefully
*/
void exercise5_InputValidation() {
cout << "\n--- INPUT VALIDATION ---\n" << endl;
int number;
bool valid = false;
while (!valid) {
cout << "Enter a number between 1 and 100: ";
// Check if input is numeric
if (!(cin >> number)) {
// Non-numeric input
cerr << "ERROR: Please enter a valid number!" << endl;
cin.clear(); // Clear error flags
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Discard bad input
}
// Check if number is in range
else if (number < 1 || number > 100) {
cerr << "ERROR: Number must be between 1 and 100!" << endl;
}
else {
valid = true;
}
}
cout << "\n" << string(30, '=') << endl;
cout << "SUCCESS! You entered: " << number << endl;
cout << string(30, '=') << endl;
// Fun facts about the number
cout << "\nFun facts about " << number << ":" << endl;
cout << "- Square: " << number * number << endl;
cout << "- Is even: " << (number % 2 == 0 ? "Yes" : "No") << endl;
cout << "- Is prime: ";
bool isPrime = (number > 1);
for (int i = 2; i * i <= number && isPrime; i++) {
if (number % i == 0) isPrime = false;
}
cout << (isPrime ? "Yes" : "No") << endl;
}
// ============================================================
// ADDITIONAL EXERCISES (Try on your own!)
// ============================================================
/*
* 6. Create a program that reads a paragraph and counts:
* - Total characters
* - Total words
* - Total sentences
*
* 7. Create a "Mad Libs" style story game that asks for
* nouns, verbs, adjectives and creates a funny story
*
* 8. Create a progress bar function that takes a percentage
* and displays: [========> ] 60%
*
* 9. Create a program that formats phone numbers:
* Input: 1234567890
* Output: (123) 456-7890
*
* 10. Create a hexdump display:
* Input: "Hello"
* Output: 48 65 6C 6C 6F |Hello|
*/