33
Total Posts
3
Categories
24/7
Updated

C++

Write a program to generate the Fibonacci sequence using recursion and find the number that are perfect square.

Published on Dec 22, 2025
#include <iostream>
#include <cmath>
using namespace std;

// Recursive function for Fibonacci
int fib(int n) {
    if (n == 0)
        return 0;
    else if (n == 1)
        return 1;
    else
        return fib(n - 1) + fib(n - 2);
}

// Function to check perfect square
bool isPerfectSquare(int num) {
    int root = sqrt(num);
    return (root * root == num);
}

int main() {
    int n, count = 0;

    cout << "Enter number of terms: ";
    cin >> n;

    cout << "\nFibonacci Series:\n";
    for (int i = 0; i < n; i++) {
        int f = fib(i);
        cout << f << " ";

        if (isPerfectSquare(f)) {
            count++;
        }
    }

    cout << "\n\nNumber of Fibonacci numbers that are perfect squares: "
         << count << endl;

    return 0;
}

Documentation

Input

Enter number of terms: 10

Output

Fibonacci Series:
0 1 1 2 3 5 8 13 21 34

Number of Fibonacci numbers that are perfect squares: 3


(Perfect squares here: 0, 1, 1)

✔ Generates the Fibonacci sequence using recursion
✔ Checks and counts Fibonacci numbers that are perfect squares


Logic Used

  1. Use a recursive function to generate Fibonacci numbers

  2. Use a helper function to check perfect square

  3. Generate first n Fibonacci numbers

  4. Display Fibonacci numbers that are perfect squares