I need a little help with a for loop program?
Hey!
So Im trying to write a program that can find the nth term in the fibonacci type series. It has to be able to take any two numbers from the user, and use them as the first two terms
eg
user inputs f1=2 and f2=3
the series is 2 3 5 8 13 21 etc
the user also is able to input which term they want to come up.
Ive gotten most of the program done (I think)
but I have two problems
1) When finding the nth term the programs has to count f1 and f2 as terms 1 and 2. i cannot get it to do this, it counts the 3rd number as the first one
2)The program prints out all the numbers up to the nth term, but I want it to only print out the nth term
Ive been at this for a while now, Im pretty new to java, I took a intro class in it 2 years ago, now Im in the next class up, having a little trouble
so any help would be appreciated! thanks in advance :)
also, sorry, Im not sure how to write my program here in the fancy way!
import java.util.Scanner;
public class fibs
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in); // readying keyboard for input
int f1, f2, n, fib;
System.out.println("Please enter a vaule for F(1):");
f1 = keyboard.nextInt();
System.out.println("Please enter a vaule for F(2):");
f2 = keyboard.nextInt();
System.out.println("Please enter a vaule for n :");
n = keyboard.nextInt();
if ((f1<0)||(f2<0)||(f1>1000)||(f2>1000)||(n<1))
{
System.out.println("Please try again");
return;
}
else
{
int i;
for (i=0; i<n; i++)
{
fib=f1+f2;
f1=f2;
f2=fib;
System.out.println( fib );
}
}
}
}
Re: I need a little help with a for loop program?
Hi Jean,
For your first issue, your for loop is starting from 0 which is the first term of the sequence when you have already defined the first and second. The start from the third term you need to start your loop from index 2 or reduce n by two prior to use. (You may need to change the condition of n in the if statement).
For the second issue, you have put the print statement within the for loop so it will print out the value on each iteration. To correct this mmove the statment to below the next curly brace.
The two ways to resolve this issue is to either start from index 2 or reduce n by two.
Regards.
Re: I need a little help with a for loop program?
Thank you so much! Now its working :)