167k views
3 votes
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.

User Jelinson
by
8.2k points

1 Answer

7 votes

Here's the same program in Rust and Python:

(Rust)

use std::io;

fn main() -> io::Result<()> {

const DAYS: [&str; 7] = [

"Monday",

"Tuesday",

"Wednesday",

"Thursday",

"Friday",

"Saturday",

"Sunday",

];

let num = loop {

if let Ok(num) = get_input() {

if (1..=7).contains(&num) {

break num;

} else {

eprintln!("Error: Number out of range ({})", num);

}

}

};

println!("Your day is: {}", DAYS[num - 1]);

Ok(())

}

fn get_input() -> io::Result<usize>

let mut buf = String::new();

println!("Enter a number between 1 and 7: ");

io::stdin().read_line(&mut buf)?;

buf.trim()

.parse()

.map_err(

(Python)

num = int(input("Enter a number between 1 and 7: "))

while not (num >= 1 and num <= 7):

print(f"Error: Number out of range ({num})")

num = int(input("Enter a number between 1 and 7: "))

days = [

"Monday",

"Tuesday",

"Wednesday",

"Thursday",

"Friday",

"Saturday",

"Sunday",

]

print(f"Your day is: {days[num-1]}")

User NiranjanBhat
by
7.5k points

No related questions found