In java, how would I find the nth Fibonacci number?
In your code, num
starts as the 0th Fibonacci number, and num1
as the 1st. So to find the nth, you have to iterate the step n
times:
for (loop = 0; loop < n; loop ++)
{
fibonacci = num + num2;
num = num2;
num2 = fibonacci;
}
System.out.print(num);
and only print it when you've finished.
When the loop counter loop
has the value k
, num
holds the kth Fibonacci number and num2
the (k+1)th.