• Create a C++ program using Fibonacci sequence is a numerical sequence such that after the second element all numbers are equal to the sum of the previous two elements.
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Write a program to calculate and print the first 20 elements of this sequence. Use a 20-element array to perform this task.
#include <iostream>
using namespace std;
int main() {
int fibonacciSequence[20] = {1,1};
for (int i = 2; i < 20; i++) {
fibonacciSequence[i] = fibonacciSequence[i - 1] + fibonacciSequence[i - 2];
}
cout << "The first 20 elements of Fibonacci sequence:\n";
for (int i = 0; i < 20; i++) {
cout << fibonacciSequence[i] << " ";
}
cin>>fibonacciSequence[0];
return 0;
}
Comments
Leave a comment