155k views
2 votes
The Fibonacci sequence is a famous sequence in mathematics. The first two elements are defined as 1, 1. Subsequent elements are defined as the sum of the preceding two elements. For example, the third element is 2 (=1+1), the fourth element is 3 (=1+2), the fifth element is 5 (=2+3), and so on.

Required;
Use a for loop to create a vector which contains the first 50 Fibonacci numbers.

User Mduvall
by
6.2k points

1 Answer

3 votes

Answer:

Written using C++

#include <iostream>

#include <vector>

using namespace std;

int main() {

vector<int> fibb;

int n1 = 0;

int n2 = 1;

int temp;

for (int nm= 0; nm < 50;nm++) {

fibb.push_back(n1);

temp = n1 + n2;

n1 = n2;

n2 = temp;

}

for (int nm= 0; nm < 50;nm++) {

{

cout<<fibb.at(nm)<<" ";

}

return 0;

}

Step-by-step explanation:

#include <iostream>

#include <vector>

using namespace std;

int main() {

This line declares the vector as integer

vector<int> fibb;

This line initializes the first term to 0

int n1 = 0;

This line initializes the second term to 1

int n2 = 1;

This line declares a temporary variable

int temp;

The following iteration populates the vector with first 50 Fibonacci series

for (int nm= 0; nm < 50;nm++) {

This push an entry into the vector

fibb.push_back(n1);

The following generate the next Fibonacci element

temp = n1 + n2;

n1 = n2;

n2 = temp;

}

The following iteration prints the generated series

for (int nm= 0; nm < 50;nm++) {

cout<<fibb.at(nm)<<" ";

}

return 0;

}

User NiravPatel
by
5.8k points