PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, June 25, 2022

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

 June 25, 2022     braces, c++, compiler-errors     No comments   

Issue

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)


Answered By - Bruce
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing