Can someone explain to me this Fibonacci program?

Hello :)
Can you please explain this code to me and its output, thank you


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package sample;
import java.util.Scanner;
public class fibonacci {
public static void main(String[]args){
Scanner in=new Scanner (System.in);
int num,c,next=0,first=0,second=1;
System.out.print("Enter number: ");
num=in.nextInt();
System.out.print("Fibonacci Series: ");
for(c=0;c<num;c++){
  if(c<=1)
    next = c;
  else{
    next = first + second;
    first = second;
    second = next;
  }
  System.out.print(" "+next);
  }
 } 
}


Output: 


Enter number: 9
Fibonacci Series:  0 1 1 2 3 5 8 13 21


This is not a Java forum.
Also, you should try to think about the problem.

It works on the fact that you can calculate the next Fibonacci number knowing only the previous two.
in C++:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

int main()
{
  int num, c, next = 0, first = 0, second = 1;

  cout << "Enter number: ";
  cin >> num;

  cout << "Fibonacci Series: ";

  for (c = 0; c < num; c++)
  {
    if ( c <= 1 )
      next = c;
    else
    {
      next = first + second;
      first = second;
      second = next;
    }
    cout << " " << next;
  }
}
Enter number: 9 
Fibonacci Series: 0 1 1 2 3 5 8 13 21 
Last edited on
Topic archived. No new replies allowed.