Created
August 8, 2023 00:38
-
-
Save rphuber/0a598113303d50aa8cd8a67a68653ceb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io; | |
fn main() { | |
println!("Enter -1 to exit"); | |
loop { | |
let n = get_isize("Enter a number: "); | |
if n == -1 { | |
break; | |
} | |
println!("fibonacci of {} is {}", n, fibonacci(n)); | |
} | |
} | |
fn factorial(n: isize) -> isize { | |
// base case | |
if n == 0 { | |
1 | |
} else { | |
// recursive case | |
n * factorial(n - 1) | |
} | |
} | |
fn fibonacci(n: isize) -> isize { | |
// base cases | |
if n == 0 { | |
0 | |
} else if n == 1 { | |
1 | |
} else { | |
fibonacci(n - 1) + fibonacci(n - 2) | |
} | |
} | |
fn get_isize(prompt: &str) -> isize { | |
print!("{}", prompt); | |
let mut input = String::new(); | |
io::stdin() | |
.read_line(&mut input) | |
.expect("Failed to read line"); | |
input.trim().parse().expect("Please type a number!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment