0
0
C++programming~20 mins

Switch vs if comparison in C++ - Hands-On Comparison

Choose your learning style9 modes available
Switch vs if comparison
📖 Scenario: Imagine you are building a simple program that tells the day of the week based on a number input. You want to compare two ways to do this: using switch and using if statements.
🎯 Goal: You will create a program that takes a number from 1 to 7 and prints the corresponding day name. You will first set up the input number, then create a variable to hold the day name, then use switch statement to assign the correct day name to dayName, and finally print the result.
📋 What You'll Learn
Create an integer variable called dayNumber with the value 3
Create a string variable called dayName initialized to an empty string
Use a switch statement on dayNumber to assign the correct day name to dayName
Print the value of dayName
💡 Why This Matters
🌍 Real World
Programs often need to choose actions based on a value, like days of the week or menu options.
💼 Career
Understanding switch and if statements is essential for writing clear, efficient decision-making code in many software jobs.
Progress0 / 4 steps
1
Set up the day number
Create an integer variable called dayNumber and set it to 3.
C++
Need a hint?

Use int dayNumber = 3; to create the variable.

2
Create the day name variable
Create a string variable called dayName and initialize it to an empty string "".
C++
Need a hint?

Use std::string dayName = ""; to create the variable.

3
Assign day name using switch
Use a switch statement on dayNumber to assign the correct day name to dayName. Use these mappings: 1 = "Monday", 2 = "Tuesday", 3 = "Wednesday", 4 = "Thursday", 5 = "Friday", 6 = "Saturday", 7 = "Sunday". Include a default case that assigns "Invalid day".
C++
Need a hint?

Use switch(dayNumber) { case 1: dayName = "Monday"; break; ... default: dayName = "Invalid day"; }

4
Print the day name
Write a std::cout statement to print the value of dayName followed by a newline.
C++
Need a hint?

Use std::cout << dayName << std::endl; to print the day name.