DEV Community

Cover image for Iterative Fibonacci in C++
May Do
May Do

Posted on

Iterative Fibonacci in C++

The Fibonacci sequence is a series of numbers that are made with the last two numbers. It looks something like this:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89... and so on to infinity You can see that starting from the first 1, 1 + 1 will make 2 then 2 + 1 will make 3. This is the pattern we'll use to create our program that will display the sequence. But before we do that, let's ask the user for a number so that we don't end up with an infinite loop! That number will determine how many times we'll iterate through our sequence. The expected outcome for both should look like this:
Alt Text

We're going to set the first 2 numbers, 0 and 1 so that we have some starting numbers to add together. Also, create a variable that will hold the fib sequence number.
int num1 = 0, num2 = 1, nextNum = 0;
After we ask the user how many numbers they want in the sequence, we will use a for loop that starts at 1 and check if the number they inputed is either 1 or 2 since the first two numbers in the sequence are 0 and 1 which does not have two previous numbers.
for (int i = 1; i <= num; i++) {
if (i == 1) {
cout << num1 << " ";
continue;
}
if (i == 2) {
cout << num2 << " ";
continue;
}
}

If the number is anything else, we will then use the pattern mentioned earlier.
nextNum = num1 + num2;
num1 = num2;
num2 = nextNum;
cout << nextNum << " ";

nextNum will hold the sum of the previous two numbers. num1 will now equal the next number in the sequence and num2 will equal the current sum. So let's say the user wanted to see 4 fib sequence numbers. The program will loop 4 times and display num1 which is currently 0 and num2 which is currently 1. When i is greater than 2, nextNum will be the sum of 0 + 1. Now num1 will be 1 and num2 will be 1. For the 4th loop, the previous numbers that will be added for next num will be the sum of 1 + 1. Though we don't use it in this case, num1 will be set to 1 and num2 to 2 so that it will be ready for the next iteration.
And that's all for iterative fibonacci! The codes that were used for the program is down below.
Alt Text

Top comments (1)

Collapse
 
curtisfenner profile image
Curtis Fenner

btw, you can make long blocks of code more readable by using three ticks instead of just one (with a language identifier like cpp right after the first three ticks).