---
title: "Write a function to calculate the power of a number (x^n) recursively using Rust."  
description: "Write a function to calculate the power of a number (x^n) recursively using Rust."  
author: "Utpal Vishwas"  
published: 2023-06-22  
updated: 2023-06-23  
canonical: https://www.mindstick.com/forum/158835/write-a-function-to-calculate-the-power-of-a-number-x-n-recursively-using-rust  
category: "rust"  
tags: ["programs", "rust"]  
reading_time: 2 minutes  

---

# Write a function to calculate the power of a number (x^n) recursively using Rust.

Write a [function to calculate](https://www.mindstick.com/forum/158909/how-do-you-use-the-avg-function-to-calculate-the-average-value-of-a-column-in-sql) the [power](https://www.mindstick.com/articles/13106/how-to-manage-power-cords-efficiently) of a number (x^n) recursively using Rust.

## Replies

### Reply by Aryan Kumar

Sure, here is a Rust [function](https://www.mindstick.com/articles/13001/multi-statement-table-valued-user-defined-function-in-sql-server) to calculate the power of a number (x^n) recursively using Rust:

Rust

```plaintext
fn power(x: i32, n: i32) -> i32 {
    if n == 0 {
        return 1;
    } else if n == 1 {
        return x;
    } else {
        return x * power(x, n - 1);
    }
}

fn main() {
    let x = 2;
    let n = 3;
    let result = power(x, n);
    println!("The power of {} to {} is {}", x, n, result);
}
```

This function first defines a function called `power` that takes two i32 numbers as input, x and n, and returns the value of x raised to the power of n. The function uses a recursive approach to calculate the power. The base case is when n is 0. In this case, the function simply returns 1. The recursive case is when n is greater than 0. In this case, the function returns x multiplied by the value of x raised to the power of n-1.

The main function of the program then calls the `power` function with the values 2 and 3 as input. The result of the function call is then printed to the console.

To run the program, you can save it as a file called `power.rs` and then compile it using the following command:

Code snippet

```plaintext
rustc power.rs
```

Once the program is compiled, you can run it using the following command:

Code snippet

```plaintext
./power
```

This will print the following output to the console:

Code snippet

```plaintext
The power of 2 to 3 is 8
```


---

Original Source: https://www.mindstick.com/forum/158835/write-a-function-to-calculate-the-power-of-a-number-x-n-recursively-using-rust

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
