Search code examples
c++compiler-errorsbraces

Why do I get a compiling error that says error: ‘else’ without a previous ‘if’?


When I try to compile the code I get an error that says else without a previous if:

// Fibonacci series using recursion
#include <iostream>
using namespace std;
int fib (int n);

int main()
{
     int n, answer;

     cout << "\n\n\t\tEnter number to find: ";
     cin >> n;
     cout << "\n\n";

     answer = fib(n);

     if(n < 3 && n > 1)
         cout << answer << " is the " << n;
         cout << "nd Fibonacci number\n";
     {
         if(n < 3)
             cout << answer << " is the " << n;
             cout << "st Fibonacci number\n";
         else
             cout << answer << " is the " << n;
             cout << "rd Fibonacci number\n";
     }
     else
         cout << answer << " is the " << n;
         cout << "th Fibonacci number\n";

     return 0;
}

int fib (int n)
{
     cout << "Processing fib (" << n << ")... ";

     if (n < 3)
     {
         cout << "Return 1!\n";
         return 1;
     }
     else
     {
         cout << "Call fib(" << n-2 << ") ";
         cout << "and fib(" << n-1 << ").\n";
         return(fib(n-2) + fib(n-1));
     }
}

Solution

  • You're missing accolades (curly brackets) after your if:

    if(n < 3 && n > 1)
        cout << answer << " is the " << n;
        cout << "nd Fibonacci number\n";
    {
        if(n < 3)
    

    means

     if(n < 3 && n > 1)
     {
         cout << answer << " is the " << n;
     } // end of if
     cout << "nd Fibonacci number\n"; // always executed
     { // new anonymous block
         if(n < 3)