Fix the program
The following program prints the first 20 values of the Fibonacci sequence.
The Fibonacci sequence is a series of numbers where a number is the sum of the two numbers before it. Starting from 0, 1, the sequence goes 1, 1, 2, 3, 5, 8, 13, 21, and so on.
However, the variables don't retain their value between loops, so it doesn't work. Fix the program by moving 2 lines of code.
#include <iostream>
int main() {
int i = 1;
while (i <= 20) {
// Declare the variables for the last and current terms
int lastTerm = 0;
int currentTerm = 1;
// Output the current term
std::cout << currentTerm << " ";
// Calculate the next term in the sequence based on the current and last term
int nextTerm = lastTerm + currentTerm;
// Update the last and current terms
lastTerm = currentTerm;
currentTerm = nextTerm;
// Increment the counter
i++;
}
std::cout << "\n";
return 0;
}
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Desired output
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
Answer
#include <iostream>
int main() {
// Declare the variables for the last and current terms
int lastTerm = 0;
int currentTerm = 1;
int i = 1;
while (i <= 20) {
// Output the current term
std::cout << currentTerm << " ";
// Calculate the next term in the sequence based on the current and last term
int nextTerm = lastTerm + currentTerm;
// Update the last and current terms
lastTerm = currentTerm;
currentTerm = nextTerm;
// Increment the counter
i++;
}
std::cout << "\n";
return 0;
}
Moving the variable declarations lastTerm and currentTerm out of the loop lets them retain their value between loop cycles.