Rust program to print the Fibonacci series using recursion

Rust | Fibonacci Series using Recursion: Write a program to print the Fibonacci series using recursion.
Submitted by Nidhi, on October 10, 2021

Problem Solution:

In this program, we will create a recursive function to print the Fibonacci series.

Program/Source Code:

The source code to print the Fibonacci series using recursion is given below. The given program is compiled and executed successfully.

// Rust program to print the 
// Fibonacci using recursion

fn printFibonacci(mut a:i32, mut b:i32, n:i32) {
	if n > 0 {
		let sum = a + b;
		print!("{} ", sum);
		a = b;
		b = sum;
		printFibonacci(a, b, n-1);
	}
}

fn main() {
    let mut a:i32 = 0;
    let mut b:i32 = 1;
    let n:i32 = 8;

    println!("Fibonacci series:");
    printFibonacci(a, b, n);
    println!();
}

Output:

Fibonacci series:
1 2 3 5 8 13 21 34

Explanation:

In the above program, we created two functions printFibonacci() and main(). The printFibonacci() function is a recursive function, which is used to print the Fibonacci series.

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

Rust Functions Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.