Why am I getting the 'expected expression' error?

Hi,

I'm writing a program in Xcode about Fibonacci Series. When I use the for statement, I keep getting the error "expected expression" and the small arrow points to the 'for' in my code. Here is my code:


#include <iostream>


usingnamespacestd;


int main()

{


int n, firstTerm = 1, secondTerm = 1, nextTerm;

cout<<"Enter the number of terms: ";

cin>>n;

cout <<"Fibonacci Series: " << firstTerm << " + " << secondTerm <<

for (int i = 1; i <= n-2; ++i) { //This line is where I'm getting the error. It looks correct to me.

nextTerm = firstTerm + secondTerm;

cout<<nextTerm<<" + ";

firstTerm = secondTerm;

secondTerm = nextTerm;

}

return 0;

}

Posted on Jun 3, 2015 9:02 PM

Reply
4 replies

Jun 3, 2015 9:54 PM in response to Undergroundkinng

I'm guessing that the line before the "for" line:


cout <<"Fibonacci Series: " << firstTerm << " + " << secondTerm <<


is not properly terminated, it looks like a ";" is missing and that you have a "<<" to much.

The compiler is basically seeing something like:


cout <<"Fibonacci Series: " << firstTerm << " + " << secondTerm << for (int i = 1; i <= n-2; ++i) { .... }

Jun 4, 2015 5:11 AM in response to VikingOSX

Another (faster) variation on Fibonacci that uses memoization techniques to avoid costly recalculations. This was translated from an existing Python solution.


// memoized version of Fibonacci sequence

// Prior results are stored/searched to avoid expensive recalculations

// More: http://xlinux.nist.gov/dads/HTML/memoize.html

// clang++ -Wall -O2 -o fib_memo fib_memo.C -std=c++11 -stdlib=libc++


#include <iostream>

#include <locale>

#include <map>


using namespace std;


// key/value pair associative array

std::map<u_long, u_long> alreadyknown;


u_long n=0, newvalue=0;


u_long fib(u_long n) {

// not found is a true condition here

if (alreadyknown.find(n) == alreadyknown.end()) {

newvalue = fib(n-1) + fib(n-2);

alreadyknown[n] = newvalue;

}

return alreadyknown[n];

}


int main(int argc, char* argv[]) {


// initialize memoization key/value pair

alreadyknown[0] = 0;

alreadyknown[1] = 1;


cout<<"Enter the number of terms: ";

cin>>n;

std::locale mylocale("");

std::cout.imbue(mylocale); // use locale number formatting style

cout<<fib(n) << endl;

return0;

}

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

Why am I getting the 'expected expression' error?

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.