CodeNewbie Community 🌱

Tip Season
Tip Season

Posted on

Carbon language Fibonacci series working example

Carbon language beginner series:

Google introduced Carbon programming language recently.

Carbon language is still in early stages and is not yet ready. However just want to explore it around to learn a new language. After setting up carbon language, tried to run fibonacci series example with iteration but didn't work. So tried a recursive example and it worked. Here is the full working example.

package sample api;

fn Fibonacci(n: i32, a: i32, b: i32) -> i32 {
    Print("{0} ", a);
    if (n == 0) {
        return a;
    }
    return Fibonacci(n - 1, b, a + b);
}


fn Main() -> i32 {
    var n: i32 = 6;
    let nthFibNumber : auto = Fibonacci(n, 1, 1);
    Print("*****");
    Print("(N+1)th fibonacci number : {0}", nthFibNumber);
    return nthFibNumber;
}

Enter fullscreen mode Exit fullscreen mode

Understanding the code:

We use a recursive code to calculate nth fibonacci number .
fib(n) = fib(n-1) + fib(n-2)

To print the sequence, since for loops doesn't work in carbon yet, we will use print nth number using recursion. At each step we will replace the positions of a and b using b and a+b and print the nth number in the starting of recursion.

fn Fibonacci(n: i32, a: i32, b: i32) -> i32 {
    Print("{0} ", a);
    if (n == 0) {
        return a;
    }
    return Fibonacci(n - 1, b, a + b);
}
Enter fullscreen mode Exit fullscreen mode

Finally we call this in the main method. One thing to note is each time the method returns n+1 th fibonacci number in the recursion. So its easier to print nth fibonacci number too.

fn Main() -> i32 {
    var n: i32 = 6;
    let nthFibNumber : auto = Fibonacci(n, 1, 1);
    Print("*****");
    Print("(N+1)th fibonacci number : {0}", nthFibNumber);
    return nthFibNumber;
}
Enter fullscreen mode Exit fullscreen mode

There is an other alternate way to print fibonacci series using while loops + recursion. You can check it out here.

Carbon language Fibonacci series, print nth Fibonacci number

Additional Carbon language Reading:

Carbon language memory management

This is a part of carbon language series for beginners. Feel free to ask any questions regarding Carbon.

Latest comments (0)