Check Leap Year
Rust Programming Language
Problem
Rust program that checks whether a given year is a leap year or not.
Input
use std::io;fn main() {println!("Please enter a year:");let mut input = String::new();io::stdin().read_line(&mut input).expect("Failed to read line");let year: i32 = match input.trim().parse() {Ok(num) => num,Err(_) => {println!("Invalid input, please enter a valid year");return;}};if year % 4 == 0 && year % 100 != 0 || year % 400 == 0 {println!("{} is a leap year", year);} else {println!("{} is not a leap year", year);}}{codeBox}
Output
Please enter a year:20242024 is a leap year{codeBox}
Explanation
In this example, we use Rust's standard library's io module to read input from the user. We first print a prompt to the console using println!("Please enter a year:");.
We then create a new String called input and use the stdin() function from the io module to read a line of input from the user into input.
We then use Rust's match expression to parse the input string into an integer. If the parsing is successful, we store the resulting integer in a variable called year and continue executing the program. If the parsing fails, we print an error message and return early using return;.
We then use the following condition to check whether the entered year is a leap year or not:
If the year is divisible by 4 and not divisible by 100, or if it is divisible by 400, then it is a leap year.
Finally, we print the result using either println!("{} is a leap year", year); or println!("{} is not a leap year", year);.
This shows the program prompting the user for input, the user entering the year 2024, and the program printing a message indicating that it is a leap year.