Generate Multiplication Table
Rust Programming Language
Problem
Rust program that generates a multiplication table for a given number.
Input
use std::io;fn main() {println!("Please enter a number:");let mut input = String::new();io::stdin().read_line(&mut input).expect("Failed to read line");let number: i32 = match input.trim().parse() {Ok(num) => num,Err(_) => {println!("Invalid input, please enter a valid number");return;}};println!("Multiplication table for {}", number);for i in 1..=10 {println!("{} x {} = {}", number, i, number * i);}}{codeBox}
Output
Please enter a number:5Multiplication table for 55 x 1 = 55 x 2 = 105 x 3 = 155 x 4 = 205 x 5 = 255 x 6 = 305 x 7 = 355 x 8 = 405 x 9 = 455 x 10 = 50{codeBox}
Explanation
In this example, we first use Rust's standard library's io module to read input from the user. We print a prompt to the console using println!("Please enter a number:");.
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 number and continue executing the program. If the parsing fails, we print an error message and return early using return;.
We then print a message indicating the number for which we are generating the multiplication table using println!("Multiplication table for {}", number);.
Finally, we use a for loop to generate the multiplication table. We loop from 1 to 10 using for i in 1..=10 and print each multiplication using println!("{} x {} = {}", number, i, number * i);.
This shows the program prompting the user for input, the user entering the number 5, and the program generating the multiplication table for 5.