Write a program that asks the user for a number in the range of 1 through 7. The program should display the corresponding day of the week, where 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday, and 7 = Sunday. The program should display an error message if the user enters a number that is outside the range of 1 through 7

Respuesta :

Answer: The c++ program for the given scenario is given below.

#include <iostream>

using namespace std;

int main() {

int day;

string weekdays[7] = {"MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"};

cout<<"Enter the number to display the day of the week : " << endl;

cin >> day;  

// loop begins when the user enters invalid input

// loop continues till the user enters valid input

do

{    

    cout<<"Invalid input. Enter any number from 1 to 7. "<<endl;

    cin >> day;

}while(day<1 || day>7);  

// day-1 is taken since array begins with index 0

// day 1 is stored at index 0 in the array

cout<<"The corresponding weekday is "<<weekdays[day-1]<<endl;

return 0;

}

Explanation:

The program uses a string array to hold the days of the week. The array is declared and initialized at the same time.

string weekdays[7] = {"MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"};

The size of the array is taken 1 more than the number of elements it holds.

Array begins with index 0. The index of 7th day, Sunday, is 6 counting from 0.

Therefore, weekdays[6] holds the string SUNDAY.

Size of the array is taken as 7 since the last index, 7, holds the terminating string.

The user input is stored in the integer variable day.

If the user inputs invalid number, the user is prompted to enter a valid value using a do-while loop.

do

{    

    cout<<"Invalid input. Enter any number from 1 to 7. "<<endl;

    cin >> day;

}while(day<1 || day>7);  

The above loop runs until the user enters a valid number within the range.

Based on the value of the variable day which is 1 more than the index of the actual day stored in the weekdays array, the day of the week is displayed as shown below.

cout<<"The corresponding weekday is "<<weekdays[day-1]<<endl;

The program then ends with a return statement as the main() has return type of integer.