-
loop help
Hey everyone, im new here and i would really appreciate some help. I missed 1 lecture and i just cant seem to get the loop to work.
Heres the question:
The sequence of Fibonacci numbers begins with the integers
1,1,2,3,5,8,13,21....
where each number after the first two is the sum of the two preceding numbers.
Write a loop to display the Fibonacci numbers less than 500.
Im really stuck! Please help.
-
im not that great at programming, but ill try to give you what help i can:
i know (or at least im pretty sure) that you are going to want to use an array. define an array of 500 ints (we will call it fibonachi in this example [and please excuse my poor spelling]), with the first 2 having a value of 1. then you will have a loop of something to this effect:
Code:
for (int i = 3; i < 500; i++)
{
fibonachi[i] = fibonachi[i-1] + fibonachi[i-2];
cout <<fibonachi[i];
}
i think that will work, i didnt actually test the code, just wrote it as i made the post, and as i stated before, im not the greatest at programming, but as far as i can tell it works.
-
Thanks for the help but I dont think an array is used at all. At the time of doing that, we hadnt even started arrays and I seriously doubt he would have thrown us in at the deep end.
Thanks anyway mate.
-
Code:
#include <iostream>
int main()
{
int f;
int f1 = 0;
int f2 = 1;
cour <<"The first number is 0.\nThe second number is 1.\n";
for (int i = 3; i < 500; i++)
{
f = f1 + f2;
cout <<"The " <<i <<" number is " <<f <<".\n";
f2 = f1;
f1 = f;
}
return 0;
}
<edit>it quickly gets too large to be of any use, though</edit>
-
Howabout this:
Code:
int i, z, tmp;
cout << 1 << endl; //EDIT: this will make the whole sequence correct
for(i = 0, z = 1; i + z <= 500;) { // allows you to test its < 500 and stop
cout << (i+z) << endl; // outpuput to screec
tmp = i; // remember what this was
i = z; // move the numbers "back" one
z += tmp; // Algorithmic increment
}
[EDIT] no smileys
[ANOTHER EDIT] I compiled it and it gave me:
1
1
2
3
5
8
13
21
34
55
89
144
233
377
as output. I do believe this is correct.