Fibonacci series using user input ( for loop )
So here is the code given below how to use for loop in C++. So here we go to the code. Just don't copy the code just go for its explanation given below the code. It may guide/help your for your learning and remembrance of the code.
Fibonacci series
#include<iostream.h>
#include<conio.h>
void main(){
clrscr();
int prev, curr, next, num;
cout<<"\n\t Enter previous number : ";
cin>>prev;
cout<<"\n\t Enter current number : ";
cin>>curr;
cout<<"\n\t Enter the count of elements : ";
cin>>num;
cout<<prev<<" "<<curr<<" ";
for( int i = 2; i < num; i++ ){
next = prev + curr;
cout<<next<<" ";
prev = curr;
curr = next;
}
getch();
}
Explanation of Code
- The header tags.
#include<iostream.h>
#include<conio.h>
- Then the main() function is declared.
void main()
- clrscr(); is a function use to clear the output console screen.
int prev = 0, curr = 1, next, num;
- cout is use to display/output of the declared variables.
cout<<"\n\t Enter previous number : ";
cout<<"\n\t Enter current number : ";
cout<<"\n\t Enter the count of elements : ";
- cin is use to connect with it for an input value in it
cin>>prev;
cin>>curr;
cin>>num;
- cout is use to display/output of the declared variables.
cout<<prev<<" "<<curr<<" ";
- for loop is use for continuation to check the conditions entered in loop and to perform the action.
for( int i = 2; i < num; i++ ){
next = prev + curr;
cout<<next<<" ";
prev = curr;
curr = next;
}
Whereas, int i = 2 is define in a loop to state there are already two variables declared with there values, i < num is to check whether i variable's value is less than ( < ) the entered value in num variable. And lastly the i++ is use to increase the value of i variable.
Note : i = i + 1 ( i is equals to i plus one ) is written as i++ ( i plus plus ) in the given program.
- \n it displays the output in each new line accordingly. \t is a tab use to give 3 white space in an output of program accordingly.
cout<<"\n\t";
- getch(); is the function use to get the characters directly from the keyboard.
getch();
Screenshots :
Code