Here are four exercises to practice if and switch (or equivalent) control structures.
Exercise 1: Check If a Number is Positive, Negative, or
Zero Task: Write a program that takes a number as input and determines whether it is positive, negative, or zero.
Steps:
1. Prompt the user to enter a number.
2. Use an if-else structure to: Print "The number is positive" if the number is greater than 0. Print "The number is negative" if the number is less than 0. Print "The number is zero" if the number equals 0.
Exercise 2: Grade Classification
Task: Write a program that takes a student's grade (0–100) as input and outputs the letter grade using if-else .
Steps:
1. Prompt the user to enter a grade.
2. Use if-else to classify the grade: A: 90–100 B: 80–89 C: 70–79 D: 60–69 F: below 60
3. Print the corresponding letter grade.
Exercise 3: Day of the Week (Switch)
Task: Write a program that takes a number (1–7) as input and prints the corresponding day of the week using a switch statement.
Steps:
1. Prompt the user to enter a number between 1 and 7.
2. Use a switch statement to: Print "Monday" for 1. Print "Tuesday" for 2. Print "Wednesday" for 3. Print "Thursday" for 4. Print "Friday" for 5. Print "Saturday" for 6. Print "Sunday" for 7. 3. Print "Invalid input" for numbers outside the range.
Exercise 4: Calculator (Switch)
Task: Write a program that acts as a simple calculator using a switch statement.
Steps:
1. Prompt the user to enter two numbers and an operator ( + , - , * , / ).
2. Use a switch statement to: Add the two numbers if the operator is + . Subtract the two numbers if the operator is - . Multiply the two numbers if the operator is * . Divide the two numbers if the operator is / . 3. Print the result for each case. 4. Print "Invalid operator" for any other input.