In: Computer Science
Here is a program that computes Fibonacci series.
Can you add comments to variables and functions of every functions? For example, what are these variables meaning? What "for" function do on this program?
Describe important section of code to text file. For example, which section of this code important? Why?
Thank you all of help.
#include<iostream>
using namespace std;
int main()
{
int arr[100];
int n1, n2;
cin>>n1;
arr[0] = 0;
arr[1] = 1;
for(int i = 2;i<n1;i++){
arr[i] = arr[i-1]+arr[i-2];
}
cout<<arr[n1-1]<<endl;
cin>>n2;
bool found = false;
for(int i = 0;i<n1;i++){
if(arr[i] == n2){
found = true;
break;
}
}
if(found){
cout<<n2<<" is a Fibonacci number"<<endl;
}
else{
cout<<n2<<" is not a Fibonacci number"<<endl;
}
for(int i = 0;i<10 && i<n1;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
return 0;
}
#include<iostream>
using namespace std;
int main() {
int arr[100];
int n1, n2;
cin >> n1; // how many fibonacci numbers to be generated
arr[0] = 0; // initialize first fibonacci number to 0
arr[1] = 1; // initialize first fibonacci number to 1
for (int i = 2; i < n1; i++) { // run this loop n1-2 times
/**
* we know that f(n) = f(n-1) + f(n-2)
* arr[i-1] represents f(n-1)
* arr[i-2] represents f(n-2)
* so, generate new fibonacci number f(n) by adding last two elements from array which represents f(n-1) and f(n-2)
*/
arr[i] = arr[i - 1] + arr[i - 2];
}
cout << arr[n1 - 1] << endl; // print n1th fibonacci number, which was generated using last for loop
cin >> n2; // read a number from user to check if it's a fibonacci number
bool found = false; // initially set found to false, indicating that the number is not found in the array
for (int i = 0; i < n1; i++) { // go through all elements in the array
if (arr[i] == n2) { // if any of the elements of the array equals the entered number n2
found = true; // then set found is true
break;
}
}
if (found) { // if number was found in the given for loop
cout << n2 << " is a Fibonacci number" << endl; // then print that the number is a fibonacci number
} else { // if number was not found in the given for loop
cout << n2 << " is not a Fibonacci number" << endl; // then print that the number is not a fibonacci number
}
for (int i = 0; i < 10 && i < n1; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}