Advertisement
AshfaqFardin

Fibonacci Sequence: Nth Term

Jul 30th, 2021
1,079
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.67 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7.     int N = 0;
  8.     cin >> N;
  9.    
  10.     int fib1 = 0;
  11.     int fib2 = 1;
  12.     int nextNum = 0;
  13.    
  14.     // if N = 10, print N numbers of fib
  15.     for(int i = 1; i <= N; i++){
  16.         if(i == 1){
  17.             cout << fib1 << " ";
  18.             continue; // to increase the value of i after printing
  19.         }
  20.         if(i == 2){
  21.             cout << fib2 << " ";
  22.             continue; // to increase the value of i after printing
  23.         }
  24.        
  25.         nextNum = fib1 + fib2;
  26.         fib1 = fib2;
  27.         fib2 = nextNum;
  28.        
  29.         cout << nextNum << " ";
  30.        
  31.     }
  32.    
  33.     return 0;
  34. }
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement