w3resource

Rust Function: Calculate rectangle area

Rust Functions and Control Flow: Exercise-1 with Solution

Write a Rust function that calculates the area of a rectangle given its width and height.

Sample Solution:

Rust Code:

// Define a function named 'calculate_rectangle_area' that takes width and height as parameters and returns the area
fn calculate_rectangle_area(width: f64, height: f64) -> f64 {
    // Calculate the area of the rectangle using the formula: area = width * height
    let area = width * height;
    area // Return the calculated area
}

fn main() {
    let width = 12.0; // Define the width of the rectangle
    let height = 15.0; // Define the height of the rectangle

    // Call the 'calculate_rectangle_area' function with the specified width and height
    let area = calculate_rectangle_area(width, height);

    // Print the calculated area
    println!("Area of the rectangle: {}", area);
}

Output:

Area of the rectangle: 180

Explanation:

Here's a brief explanation of the above Rust code:

  • 'fn calculate_rectangle_area(width: f64, height: f64) -> f64 { ... }': This is a function named 'calculate_rectangle_area' that takes two parameters 'width' and 'height', both of type 'f64' (64-bit floating-point numbers), and returns a 'f64' representing the area of the rectangle.
  • 'let area = width height;': This line calculates the rectangle area using the formula 'area = width height'.
  • 'area': This line returns the calculated area as the result of the function.
  • 'fn main() { ... }': This is the program's entry point.
  • 'let width = 12.0;' and 'let height = 15.0;': These lines define the rectangle's width and height.
  • 'let area = calculate_rectangle_area(width, height);': This line calls the 'calculate_rectangle_area' function with the specified width and height, and stores the result in the variable 'area'.
  • 'println!("Area of the rectangle: {}", area);': This line prints the calculated area of the rectangle.

Rust Code Editor:

Previous: Rust Functions and Control Flow Exercises.
Next: Rust Function: Check Prime number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-functions-and-control-flow-exercise-1.php