nth Fibonacci Number

Program to find the nth Fibonacci number

BeginnerTopic: Loop Programs
Back

C++ nth Fibonacci Number Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

int main() {
    int n, first = 0, second = 1, next;
    
    cout << "Enter the position (n): ";
    cin >> n;
    
    if (n == 1) {
        cout << "Fibonacci number at position " << n << " is: " << first << endl;
    } else if (n == 2) {
        cout << "Fibonacci number at position " << n << " is: " << second << endl;
    } else {
        for (int i = 3; i <= n; i++) {
            next = first + second;
            first = second;
            second = next;
        }
        cout << "Fibonacci number at position " << n << " is: " << second << endl;
    }
    
    return 0;
}
Output
Enter the position (n): 10
Fibonacci number at position 10 is: 34

Understanding nth Fibonacci Number

Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34... Each number is the sum of the two preceding ones. We use two variables to track the previous two numbers and calculate the next one iteratively.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents