Is this the shortest way to find Fibonacci numbers?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
int main()
{
         int limit, num1 = 0, num2 = 1, num3; 
	cout<<"Enter a limit: ";
	cin>>limit;

	do{
		cout<< num1 << " ";
		num3 = num1 + num2;
		num1 = num2;
		num2 = num3;
	}while(num1 <= limit);

         cout<<'\n';
	system("pause");
	return 0;
}


Fibonacci Sequence = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,...
Sorry, if things came out sloppy...This is my first post.
What are you wanting to make this for? Just curious, I have no answers for you.
I'm doing this for my homework. I'm scared that my code might end up getting too long and I might get some points off for inefficiency/having a code that's too long.

As of now, that code I posted above works like it's supposed to but I have this weird feeling that my code is the "long-cut"...
It's 19 lines of code, I don't think your Professor will get mad. Especially in programs as short as this, where the code is easy to follow it's more important for it to run efficiently. At the moment your calculations should be fine, I would say the only parts that will be CPU-Intensive is all of the output and the system commands. If you're really nervous that your code is too long/hard to follow, I would just add some comments in.

Personally, when I need to calculate the sequence I write it as follows:
1
2
3
4
5
6
7
int previous = -1;
int result = 1;
for( unsigned int i = 0; i <= n; ++i ) {
    int sum = result + previous;
    previous = result;
    result = sum;
}
Last edited on
Okay, thanks
Topic archived. No new replies allowed.