c
exercises
exercises.c🔧c
/*
* ============================================================================
* VARIABLES AND CONSTANTS IN C - EXERCISES
* ============================================================================
* Complete these exercises to master variables and constants.
*
* Compile: gcc -Wall exercises.c -o exercises
* Run: ./exercises
* ============================================================================
*/
#include <stdio.h>
/*
* ============================================================================
* EXERCISE 1: Basic Variable Declaration
* ============================================================================
* Difficulty: Easy
*
* Task: Declare and initialize variables of different types, then print them.
*
* Expected Output:
* Name: John
* Age: 25
* Height: 5.90
* Grade: A
* Is Student: 1
*/
void exercise_1() {
printf("\n=== Exercise 1: Basic Declaration ===\n");
// TODO: Declare a string (char array) for name, initialize to "John"
// TODO: Declare an integer for age, initialize to 25
// TODO: Declare a float for height, initialize to 5.9
// TODO: Declare a char for grade, initialize to 'A'
// TODO: Declare an int for isStudent, initialize to 1 (true)
// TODO: Print all variables with appropriate labels
}
/*
* ============================================================================
* EXERCISE 2: Variable Naming
* ============================================================================
* Difficulty: Easy
*
* Task: Fix the invalid variable names below (commented out).
* Create valid alternatives with the same meaning.
*
* Expected Output:
* All variables created successfully!
*/
void exercise_2() {
printf("\n=== Exercise 2: Variable Naming ===\n");
// TODO: Create valid alternatives for these invalid names:
// Invalid: int 2ndPlace = 2;
// Valid alternative:
// Invalid: int my-score = 100;
// Valid alternative:
// Invalid: int user name = "Alice";
// Valid alternative:
// Invalid: float float = 3.14;
// Valid alternative:
// Invalid: int total$ = 500;
// Valid alternative:
printf("All variables created successfully!\n");
}
/*
* ============================================================================
* EXERCISE 3: Constants with const
* ============================================================================
* Difficulty: Easy
*
* Task: Create constants for a circle calculation program.
*
* Expected Output:
* Circle with radius 5:
* Circumference: 31.42
* Area: 78.54
*/
void exercise_3() {
printf("\n=== Exercise 3: Constants ===\n");
// TODO: Declare a constant for PI (3.14159)
// TODO: Declare a constant for radius (5)
// TODO: Calculate circumference (2 * PI * radius)
// TODO: Calculate area (PI * radius * radius)
// TODO: Print the results formatted to 2 decimal places
}
/*
* ============================================================================
* EXERCISE 4: #define vs const
* ============================================================================
* Difficulty: Medium
*
* Task: Create an array using #define for size, and const for max value.
* Fill array with numbers and find how many are above a threshold.
*
* Expected Output:
* Array size: 10
* Max allowed value: 100
* Numbers above threshold (50): 5
*/
void exercise_4() {
printf("\n=== Exercise 4: #define vs const ===\n");
// TODO: Define ARRAY_SIZE as 10 using #define (do this above function)
// #define ARRAY_SIZE 10
// TODO: Declare MAX_VALUE as const int = 100
// TODO: Declare THRESHOLD as const int = 50
// TODO: Create an array of ARRAY_SIZE integers
// Initialize with values: 25, 45, 55, 65, 35, 75, 85, 40, 95, 60
// TODO: Count how many values are above THRESHOLD
// TODO: Print results
}
/*
* ============================================================================
* EXERCISE 5: Enumeration
* ============================================================================
* Difficulty: Medium
*
* Task: Create an enum for menu options and use it in a switch statement.
*
* Expected Output:
* Menu Options:
* 1. Create
* 2. Read
* 3. Update
* 4. Delete
* 5. Exit
*
* Selected option 3: Updating record...
*/
void exercise_5() {
printf("\n=== Exercise 5: Enumeration ===\n");
// TODO: Create an enum MenuOption with values:
// CREATE = 1, READ, UPDATE, DELETE, EXIT
// TODO: Print the menu options
// TODO: Create a variable 'selection' of type MenuOption = UPDATE
// TODO: Use switch to print appropriate message for the selection
}
/*
* ============================================================================
* EXERCISE 6: Variable Scope
* ============================================================================
* Difficulty: Medium
*
* Task: Predict and verify what each print statement outputs.
*
* Expected Output:
* Outer x: 10
* Inner x: 20
* After block x: 10
* Function x: 30
* Back in main x: 10
*/
// Global variable for exercise 6
int globalX = 5;
void helperFunction() {
int x = 30;
printf("Function x: %d\n", x);
}
void exercise_6() {
printf("\n=== Exercise 6: Variable Scope ===\n");
int x = 10;
printf("Outer x: %d\n", x);
{
// TODO: Declare a new x with value 20 inside this block
printf("Inner x: %d\n", x);
}
printf("After block x: %d\n", x);
helperFunction();
printf("Back in main x: %d\n", x);
}
/*
* ============================================================================
* EXERCISE 7: Static Variables
* ============================================================================
* Difficulty: Medium
*
* Task: Create a function that remembers how many times it's been called.
*
* Expected Output:
* generateID called: ID = 1001
* generateID called: ID = 1002
* generateID called: ID = 1003
* generateID called: ID = 1004
* generateID called: ID = 1005
*/
// TODO: Create a function generateID that:
// 1. Uses a static variable initialized to 1000
// 2. Increments it each call
// 3. Returns and prints the new ID
void exercise_7() {
printf("\n=== Exercise 7: Static Variables ===\n");
// TODO: Call generateID 5 times
}
/*
* ============================================================================
* EXERCISE 8: Variable Lifetime
* ============================================================================
* Difficulty: Medium
*
* Task: Demonstrate the difference between automatic and static lifetime.
*
* Expected Output:
* === Call 1 ===
* Automatic: 1
* Static: 1
* === Call 2 ===
* Automatic: 1
* Static: 2
* === Call 3 ===
* Automatic: 1
* Static: 3
*/
// TODO: Create a function demonstrateLifetime that:
// 1. Has an automatic variable initialized to 0
// 2. Has a static variable initialized to 0
// 3. Increments both
// 4. Prints both values
void exercise_8() {
printf("\n=== Exercise 8: Variable Lifetime ===\n");
// TODO: Call demonstrateLifetime 3 times with call number printed
}
/*
* ============================================================================
* EXERCISE 9: Initialization Best Practices
* ============================================================================
* Difficulty: Easy
*
* Task: Initialize arrays and structures properly.
*
* Expected Output:
* Scores: 85 90 78 92 88
* Zeros: 0 0 0 0 0
* Point: (10, 20)
* Rectangle: (0, 0) to (100, 50)
*/
void exercise_9() {
printf("\n=== Exercise 9: Initialization ===\n");
// TODO: Initialize an array 'scores' with values 85, 90, 78, 92, 88
// TODO: Initialize an array 'zeros' of 5 elements, all zeros
// TODO: Define a struct Point with x and y
// Initialize a Point 'p' to (10, 20) using designated initializers
// TODO: Define a struct Rectangle with x1, y1, x2, y2
// Initialize to represent a rectangle from (0,0) to (100,50)
// TODO: Print all values
}
/*
* ============================================================================
* EXERCISE 10: Temperature Converter
* ============================================================================
* Difficulty: Medium
*
* Task: Create a program with proper use of constants and variables.
* Convert temperatures between Celsius and Fahrenheit.
*
* Formula: F = C * 9/5 + 32
* C = (F - 32) * 5/9
*
* Expected Output:
* Temperature Conversion:
* 25°C = 77.00°F
* 98.6°F = 37.00°C
* 0°C = 32.00°F (Freezing point)
* 100°C = 212.00°F (Boiling point)
*/
void exercise_10() {
printf("\n=== Exercise 10: Temperature Converter ===\n");
// TODO: Define constants for freezing and boiling points in Celsius
// TODO: Create a function (or inline code) to convert C to F
// TODO: Create a function (or inline code) to convert F to C
// TODO: Test with given values and print results
}
/*
* ============================================================================
* BONUS: Configuration System
* ============================================================================
* Difficulty: Hard
*
* Task: Create a simple configuration system using constants and structures.
*/
void bonus_exercise() {
printf("\n=== BONUS: Configuration System ===\n");
// TODO: Create a Config structure with:
// - app_name (char array)
// - version (float)
// - max_users (int, const)
// - debug_mode (int/bool)
// TODO: Initialize with application settings
// TODO: Print configuration
// Format:
// Application: MyApp
// Version: 1.0
// Max Users: 100
// Debug Mode: ON/OFF
}
/*
* ============================================================================
* MAIN FUNCTION
* ============================================================================
*/
int main() {
printf("╔════════════════════════════════════════════════╗\n");
printf("║ VARIABLES AND CONSTANTS - 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();
// exercise_6();
// exercise_7();
// exercise_8();
// exercise_9();
// exercise_10();
// bonus_exercise();
printf("\n=== Uncomment exercises in main() to run them ===\n");
return 0;
}
/*
* ============================================================================
* ANSWER KEY
* ============================================================================
*
* Exercise 1:
* char name[] = "John";
* int age = 25;
* float height = 5.9f;
* char grade = 'A';
* int isStudent = 1;
*
* Exercise 2 (valid alternatives):
* int secondPlace = 2;
* int myScore = 100;
* char userName[] = "Alice";
* float floatValue = 3.14f;
* int totalAmount = 500;
*
* Exercise 3:
* const float PI = 3.14159f;
* const int radius = 5;
* float circumference = 2 * PI * radius;
* float area = PI * radius * radius;
*
* Exercise 5 (enum):
* enum MenuOption { CREATE = 1, READ, UPDATE, DELETE, EXIT };
* enum MenuOption selection = UPDATE;
*
* Exercise 7 (static):
* int generateID() {
* static int id = 1000;
* id++;
* printf("generateID called: ID = %d\n", id);
* return id;
* }
*
* Exercise 8 (lifetime):
* void demonstrateLifetime() {
* int automatic = 0;
* static int persistent = 0;
* automatic++;
* persistent++;
* printf("Automatic: %d\n", automatic);
* printf("Static: %d\n", persistent);
* }
*
* Exercise 9 (initialization):
* int scores[] = {85, 90, 78, 92, 88};
* int zeros[5] = {0};
* struct Point { int x; int y; };
* struct Point p = {.x = 10, .y = 20};
*
* Exercise 10 (temperature):
* const float FREEZING_C = 0.0f;
* const float BOILING_C = 100.0f;
* float celsiusToFahrenheit(float c) { return c * 9.0f/5.0f + 32.0f; }
* float fahrenheitToCelsius(float f) { return (f - 32.0f) * 5.0f/9.0f; }
*
* ============================================================================
*/