C Program: Generate Fibonacci Numbers

The Fibonacci Sequence is one of the most well-known series in Mathematics, where each number is a sum of its two preceding numbers, starting from 0 and 1. It is named after the Italian mathematician Leonardo Pisano who introduced it to the west in his book Liber Abaci (AD 1202).

The sequence is usually denoted by $F_{n}$ where $n \geq 0$. Therefore,

$F_{0} = 0$, $F_{1} = 1$, and for values of $n > 1$,

$F_{n} = F_{n-1} + F_{n-2}$

The sequence begins as: 0, 1, 1, 2, 3, 5, 8, 13, ...

leonardo fibonacci Leonardo Fibonacci. Public Domain

Below is a simple C program that prints Fibonacci Numbers upto a given number $n$.

				
				#include <stdio.h>

				int main() {
					unsigned long int n, first = 0, second = 1, next, i;

					printf("Enter a natural number: ");
					scanf("%lu", &n);

					for(i = 0; i < n; i++) {
						if(i <=1) {
							next = i;
						} else {
							next = first + second;
							first = second;
							second = next;
						}

						printf("%lu, ", next);
					}
					
					return 0;
				}
				
			

We can also use a recursive function to print out Fibonacci Numbers as shown in the program below.

				
				#include <stdio.h>
				unsigned long fibonacci(unsigned long);

				int main() {
					unsigned long int n, first = 0, second = 1, next, i;

					printf("Enter a natural number: ");
					scanf("%lu", &n);

					for(i = 0; i < n; i++) {
						printf("%lu, ", fibonacci(i));
					}

					return 0;
				}

				unsigned long fibonacci(unsigned long n) { 
				   	if (n <= 1) { 
				      	return n;
				    } else {
				   		return fibonacci(n-1) + fibonacci(n-2);
				   	} 
				}