Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to print DAY according to user input for day count

C++ Code Example — Conditional Programs

ADVERTISEMENT

WAP to print DAY according to user input for day count

Objective

Write a C++ program to print the string name of a Day given its number using switch-case.

Algorithm / Approach

  1. Read a day number a.
  2. Pass the variable into a switch block: switch(a).
  3. Create cases for each day: case 1: cout << "Monday"; break;.
  4. Include a default: block to handle invalid numbers.
main.cpp
#include<iostream>
using namespace std;
int main() {
 int a;
 cout<<"Enter Day Number: ";
 cin>>a;
 switch(a) {
  case 1:
   cout<<"Day is Monday\n";
   break;
  case 2:
   cout<<"Day is Tuesday\n";
   break;
  case 3:
   cout<<"Day is Wednesday\n";
   break;
  case 4:
   cout<<"Day is Thursday\n";
   break;
  case 5:
   cout<<"Day is Friday\n";
   break;
  case 6:
   cout<<"Day is Saturday\n";
   break;
  case 7:
   cout<<"Day is Sunday\n";
   break;
  default:
   cout<<"Wrong Choice\n";
  }
 return 0;
}

Expected Output

Enter Day Number: 4
Day is Thursday

Explanation of the Program

  • The switch statement is a cleaner, more readable alternative to writing a massive block of else if statements when you are comparing a single integer or character against exact constant values.
  • The break keyword is mandatory at the end of every case. If you forget it, the program will suffer from "fall-through" and execute all the cases below the matching one as well.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT