Search⌘ K
AI Features

Solution: Compute the Fibonacci Number

Understand how to write a C function to compute Fibonacci numbers by managing variables and loops. This lesson helps you grasp base cases, iterative calculations, and variable updates to produce the correct Fibonacci sequence efficiently using modular function design.

We'll cover the following...
C
#include <stdio.h>
int fib(int n)
{
int i;
if ((n == 0) || (n == 1))
return n;
int a = 0;
int b = 1;
int tmp;
for (i = 2; i <= n; i++) {
tmp = b;
b = a + b; // Now b contains the i^th Fibonacci number
a = tmp;
}
return b;
}
int main(void)
{
int n = 10;
printf("Fibonacci number at position %d is %d\n", n, fib(n));
return 0;
}
...