Rust Age Calculator: Calculate Age based on birth year and current year
Rust Variables and Data Types: Exercise-1 with Solution
Write a Rust program that declares a variable birth_year and calculates the age based on the current year and the user's birth year.
Sample Solution:
Rust Code:
use std::io; // Import the standard library's input/output module
fn main() {
println!("Please enter your birth year:"); // Prompt the user to enter their birth year
let mut input = String::new(); // Create a mutable string to store user input
io::stdin().read_line(&mut input).expect("Failed to read line"); // Read the user's input
let birth_year: u32 = input.trim().parse().expect("Invalid input"); // Parse the input as an unsigned 32-bit integer
let current_year = 2024; // Define the current year
let age = current_year - birth_year; // Calculate the age by subtracting the birth year from the current year
println!("Your age is {} years old.", age); // Print the calculated age
}
Output:
Please enter your birth year: Your age is 57 years old.
Explanation:
Here's a brief explanation of the above Rust code:
- use std::io;: This line imports the standard library's input/output module, which is required for reading user input.
- fn main() { ... }: This is the entry point of the program.
- println!("Please enter your birth year:");: This line prints a prompt asking the user to enter their birth year.
- let mut input = String::new();: This line creates a mutable string named 'input' to store the user's input.
- io::stdin().read_line(&mut input).expect("Failed to read line");: This line reads the user's input from the standard input and stores it in the 'input' variable. If an error occurs while reading the input, it will print an error message.
- let birth_year: u32 = input.trim().parse().expect("Invalid input");: This line trims any whitespace from the input, parses it as an unsigned 32-bit integer, and stores it in the birth_year variable. If the input cannot be parsed as an integer, it prints an error message.
- let current_year = 2024;: This line defines the current year. You may need to update this value to the current year when running the program.
- let age = current_year - birth_year;: This line calculates the age by subtracting the birth_year from the current_year.
- println!("Your age is {} years old.", age);: This line prints the calculated age to the console.
Rust Code Editor:
Previous: Rust Variable and Data Types Exercises.
Next: Rust: Calculate circumference from diameter and PI.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/rust/basic/rust-variables-and-data-types-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics