ADVERTISEMENT
ADVERTISEMENT

Rust program to calculate the power of a given number using recursion

Rust | Calculate Power: Write a program to calculate the power of a given number using recursion.
Submitted by Nidhi, on October 10, 2021

Problem Solution:

In this program, we will create a recursive function to calculate the power of a given number using recursion and return the result to the calling function.

Program/Source Code:

The source code to calculate the power of a given number using recursion is given below. The given program is compiled and executed successfully.

// Rust program to calculate the power 
// of given number using recursion

fn CalculatePower(num:i32, power:i32)->i32 {
	let mut result:i32 = 1;
	if power > 0 {
		result = num * (CalculatePower(num, power-1));
	}
	return result;
}

fn main() {
    let mut res:i32=0;
    
    res=CalculatePower(3,4);
    println!("Result is: {}",res);
}

Output:

Result is: 81

Explanation:

In the above program, we created two functions CalculatePower() and main(). The CalculatePower() function is a recursive function, which is used to calculate the power of a given number and return the result to the calling function.

In the main() function, we called CalculatePower() function and printed the result.

Rust Functions Programs »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.