c
exercises
exercises.cđ§c
/*
* ============================================================================
* INPUT/OUTPUT IN C - EXERCISES
* ============================================================================
* Complete these exercises to master printf and scanf.
*
* Compile: gcc -Wall exercises.c -o exercises
* Run: ./exercises
* ============================================================================
*/
#include <stdio.h>
#include <string.h>
/*
* ============================================================================
* EXERCISE 1: Basic printf
* ============================================================================
* Difficulty: Easy
*
* Task: Print the following information about a student:
* - Name: Alice Johnson
* - Age: 20
* - GPA: 3.85
* - Grade: A
*
* Expected Output:
* Student Information
* -------------------
* Name: Alice Johnson
* Age: 20 years old
* GPA: 3.85
* Grade: A
*/
void exercise_1() {
printf("\n=== Exercise 1: Basic printf ===\n");
// TODO: Declare variables for name, age, gpa, and grade
// TODO: Print the student information using printf
}
/*
* ============================================================================
* EXERCISE 2: Format Specifiers
* ============================================================================
* Difficulty: Easy
*
* Task: Print the number 255 in different formats:
* - Decimal
* - Octal
* - Hexadecimal (lowercase)
* - Hexadecimal (uppercase)
* - With 0x prefix
*
* Expected Output:
* Decimal: 255
* Octal: 377
* Hex (lowercase): ff
* Hex (uppercase): FF
* Hex with prefix: 0xff
*/
void exercise_2() {
printf("\n=== Exercise 2: Format Specifiers ===\n");
int num = 255;
// TODO: Print num in different formats
}
/*
* ============================================================================
* EXERCISE 3: Width and Precision
* ============================================================================
* Difficulty: Medium
*
* Task: Create a simple price list with aligned columns.
*
* Expected Output:
* ITEM PRICE QTY
* ---- ----- ---
* Apple $ 1.50 10
* Banana $ 0.75 25
* Orange $ 2.25 15
* Pineapple $ 4.99 5
*/
void exercise_3() {
printf("\n=== Exercise 3: Width and Precision ===\n");
// TODO: Print the header row
// TODO: Print separator
// TODO: Print each item row with proper alignment
// Item name: left-aligned, width 10
// Price: right-aligned, width 6, 2 decimal places
// Quantity: right-aligned, width 4
}
/*
* ============================================================================
* EXERCISE 4: Escape Sequences
* ============================================================================
* Difficulty: Easy
*
* Task: Print the following using escape sequences:
* 1. A string with a tab between words
* 2. A multi-line quote
* 3. A file path (with backslashes)
* 4. A percentage
*
* Expected Output:
* Column1 Column2 Column3
* "Hello," she said.
* "How are you?"
* Path: C:\Users\John\Documents
* Progress: 75%
*/
void exercise_4() {
printf("\n=== Exercise 4: Escape Sequences ===\n");
// TODO: Print tabbed columns
// TODO: Print multi-line quote with quotation marks
// TODO: Print Windows file path
// TODO: Print percentage
}
/*
* ============================================================================
* EXERCISE 5: Basic scanf
* ============================================================================
* Difficulty: Easy
*
* Task: Create a program that reads user information:
* - Age (integer)
* - Height in meters (float)
* - First initial (character)
* Then print all the information.
*
* Expected Interaction:
* Enter your age: 25
* Enter your height (m): 1.75
* Enter your first initial: J
*
* Your info: Age 25, Height 1.75m, Initial J
*/
void exercise_5() {
printf("\n=== Exercise 5: Basic scanf ===\n");
// TODO: Declare variables
// TODO: Prompt and read age
// TODO: Prompt and read height
// TODO: Prompt and read initial (remember the space before %c!)
// TODO: Print all information
}
/*
* ============================================================================
* EXERCISE 6: Reading Strings
* ============================================================================
* Difficulty: Medium
*
* Task: Read a full name (with spaces) and print a greeting.
*
* Expected Interaction:
* Enter your full name: John Doe
* Hello, John Doe! Welcome!
*/
void exercise_6() {
printf("\n=== Exercise 6: Reading Strings ===\n");
char fullName[100];
// TODO: Prompt for full name
// TODO: Read the full name (including spaces)
// Use either fgets() or scanf with %[^\n]
// TODO: Print the greeting
}
/*
* ============================================================================
* EXERCISE 7: Input Validation
* ============================================================================
* Difficulty: Medium
*
* Task: Create a number reader that validates input.
* If the user enters non-numeric input, print an error message.
*
* Expected Interaction (valid):
* Enter a number: 42
* You entered: 42
*
* Expected Interaction (invalid):
* Enter a number: abc
* Error: Invalid input. Please enter a number.
*/
void exercise_7() {
printf("\n=== Exercise 7: Input Validation ===\n");
int num;
// TODO: Prompt for number
// TODO: Read number and check scanf return value
// TODO: If valid, print the number. If invalid, print error.
}
/*
* ============================================================================
* EXERCISE 8: Calculator Input
* ============================================================================
* Difficulty: Medium
*
* Task: Read two numbers and an operator, then perform the calculation.
*
* Expected Interaction:
* Enter expression (num1 operator num2): 10 + 5
* Result: 10 + 5 = 15
*
* Enter expression (num1 operator num2): 20 * 3
* Result: 20 * 3 = 60
*/
void exercise_8() {
printf("\n=== Exercise 8: Calculator Input ===\n");
// TODO: Declare variables for two numbers and an operator
// TODO: Prompt and read the expression
// TODO: Perform calculation based on operator
// Handle: +, -, *, /
// TODO: Print the result
}
/*
* ============================================================================
* EXERCISE 9: Table Formatting
* ============================================================================
* Difficulty: Hard
*
* Task: Create a multiplication table (1-5) with borders.
*
* Expected Output:
* âââââŹââââŹââââŹââââŹââââŹââââ
* â Ă â 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 â
* âââââ´ââââ´ââââ´ââââ´ââââ´ââââ
*/
void exercise_9() {
printf("\n=== Exercise 9: Multiplication Table ===\n");
// TODO: Print the multiplication table with borders
// Use loops to generate the table
// Each cell should be width 3
}
/*
* ============================================================================
* EXERCISE 10: sprintf Practice
* ============================================================================
* Difficulty: Medium
*
* Task: Build formatted strings using sprintf:
* 1. Create a date string: "August 15, 2024"
* 2. Create a price tag: "$19.99"
* 3. Create a temperature: "72.5°F"
*
* Expected Output:
* Date: August 15, 2024
* Price: $19.99
* Temperature: 72.5°F
*/
void exercise_10() {
printf("\n=== Exercise 10: sprintf ===\n");
char dateStr[50];
char priceStr[20];
char tempStr[20];
// Data
char month[] = "August";
int day = 15;
int year = 2024;
float price = 19.99f;
float temp = 72.5f;
// TODO: Build date string
// TODO: Build price string
// TODO: Build temperature string
// TODO: Print all strings
}
/*
* ============================================================================
* BONUS: Survey Form
* ============================================================================
* Difficulty: Hard
*
* Task: Create a survey form that collects:
* - Name (full name with spaces)
* - Age (integer)
* - Email (string, no spaces)
* - Satisfaction (1-5, integer)
* - Comments (optional, full line)
*
* Then display a formatted summary.
*/
void bonus_exercise() {
printf("\n=== BONUS: Survey Form ===\n");
// TODO: Declare all necessary variables
// TODO: Create prompts and read each field
// Remember to handle the newline issues
// TODO: Display formatted summary
// Example:
// ââââââââââââââââââââââââââââââââââââââââââ
// â SURVEY RESPONSE â
// â âââââââââââââââââââââââââââââââââââââââââŁ
// â Name: John Doe â
// â Age: 30 â
// â Email: john@example.com â
// â Satisfaction: â
â
â
â
â (4/5) â
// â Comments: Great product! â
// ââââââââââââââââââââââââââââââââââââââââââ
}
/*
* ============================================================================
* MAIN FUNCTION
* ============================================================================
*/
int main() {
printf("ââââââââââââââââââââââââââââââââââââââââââââââââââ\n");
printf("â INPUT/OUTPUT - EXERCISES â\n");
printf("â Complete each exercise to practice â\n");
printf("ââââââââââââââââââââââââââââââââââââââââââââââââââ\n");
// Uncomment each exercise as you complete it
// exercise_1();
// exercise_2();
// exercise_3();
// exercise_4();
// exercise_5(); // Interactive
// exercise_6(); // Interactive
// exercise_7(); // Interactive
// exercise_8(); // Interactive
// exercise_9();
// exercise_10();
// bonus_exercise(); // Interactive
printf("\n=== Uncomment exercises in main() to run them ===\n");
return 0;
}
/*
* ============================================================================
* ANSWER KEY
* ============================================================================
*
* Exercise 1:
* char name[] = "Alice Johnson";
* int age = 20;
* float gpa = 3.85f;
* char grade = 'A';
* printf("Student Information\n");
* printf("-------------------\n");
* printf("Name: %s\n", name);
* printf("Age: %d years old\n", age);
* printf("GPA: %.2f\n", gpa);
* printf("Grade: %c\n", grade);
*
* Exercise 2:
* printf("Decimal: %d\n", num);
* printf("Octal: %o\n", num);
* printf("Hex (lowercase): %x\n", num);
* printf("Hex (uppercase): %X\n", num);
* printf("Hex with prefix: %#x\n", num);
*
* Exercise 3:
* printf("%-10s %6s %4s\n", "ITEM", "PRICE", "QTY");
* printf("%-10s %6s %4s\n", "----", "-----", "---");
* printf("%-10s $%5.2f %4d\n", "Apple", 1.50, 10);
* // etc.
*
* Exercise 4:
* printf("Column1\tColumn2\tColumn3\n");
* printf("\"Hello,\" she said.\n\"How are you?\"\n");
* printf("Path: C:\\Users\\John\\Documents\n");
* printf("Progress: 75%%\n");
*
* Exercise 5:
* scanf("%d", &age);
* scanf("%f", &height);
* scanf(" %c", &initial); // Note space before %c
*
* Exercise 6:
* // Using fgets:
* fgets(fullName, sizeof(fullName), stdin);
* fullName[strcspn(fullName, "\n")] = '\0'; // Remove newline
* // OR using scanf:
* scanf(" %99[^\n]", fullName);
*
* Exercise 7:
* if (scanf("%d", &num) == 1) {
* printf("You entered: %d\n", num);
* } else {
* printf("Error: Invalid input...\n");
* }
*
* Exercise 8:
* int num1, num2;
* char op;
* scanf("%d %c %d", &num1, &op, &num2);
* switch(op) {
* case '+': result = num1 + num2; break;
* case '-': result = num1 - num2; break;
* case '*': result = num1 * num2; break;
* case '/': result = num1 / num2; break;
* }
*
* Exercise 10:
* sprintf(dateStr, "%s %d, %d", month, day, year);
* sprintf(priceStr, "$%.2f", price);
* sprintf(tempStr, "%.1f°F", temp);
*
* ============================================================================
*/