Rust Program to Generate Multiplication Table


Generate Multiplication Table

Rust Programming Language


Generate Multiplication Table


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:
5
Multiplication table for 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 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.



Post a Comment