C Online Compiler
Example: Fibonacci Sequence Generation in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Fibonacci Sequence Generation #include <stdio.h> int fibonacci(int n) { // Step 1: Define the base cases // The first two Fibonacci numbers are 0 and 1. if (n == 0) { return 0; } else if (n == 1) { return 1; } // Step 2: Define the recursive step // F(n) = F(n-1) + F(n-2) return fibonacci(n - 1) + fibonacci(n - 2); } int main() { // Step 1: Declare a variable for the Nth term int n_term = 10; // Find the 10th Fibonacci number (0-indexed) // Step 2: Call the recursive fibonacci function int result = fibonacci(n_term); // Step 3: Print the result printf("The %dth Fibonacci number is %d\n", n_term, result); // Optional: Print the first few Fibonacci numbers printf("Fibonacci sequence up to %d terms: ", n_term); for (int i = 0; i < n_term; i++) { printf("%d ", fibonacci(i)); } printf("\n"); return 0; }
Output
Clear
ADVERTISEMENTS