Question #207894

  • 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


Expert's answer

#include <iostream>
using namespace std;


int main() {
	int counter=0;
    int numbers[20] = {1,1};
	for (int i = 2; i < 20; i++) {
		numbers[i] = numbers[i - 1] + numbers[i - 2];
	}
	cout << "The first 20 elements of Fibonacci sequence:\n";
	for (int i = 0; i < 19; i++) {
		cout << numbers[i] << ", ";
	}
	cout << numbers[19];
	cin>>counter;
    return 0;
}
LATEST TUTORIALS
APPROVED BY CLIENTS