Let's say that you want to create a program that will hold as many Fibonacci numbers as you input. This seems possible with what we know, we could just use a for loop that counts up to the imputed number, defining a variable for each value. This may seem like it would work however, how you need create a variable for EACH number they enter, which could be infinity large. This means that you must define infinity many variables to do this. This may seem impossible, however it is easy if you use an array.
An array is what is called a data structure, meaning that it holds a bunch of variables. A string for example is just a collection of chars, meaning that a string is an array. So, getting back to the Fibonacci problem, you could create an array that contains the entered number of Fibonacci numbers. Here is my code for solving this problem:
import java.util.Scanner;
public class test2{
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.println("how many numbers?");
int HowMany = scan.nextInt();
int [] test = new int [HowMany];
test[0]=1;
test[1]=1;
for(int runs = 2; runs<HowMany; runs++){
test[runs]=((test[runs-1])+(test[runs-2]));
}
for(int runs = 0; runs<HowMany; runs++){
System.out.print(test[runs]+" ");
}
}
}
In this code, test is an array, and when I wanted to use or edit a value of a number in the array, I put test[x], where x is the index that you want to reference. If any of this is confusing to you, please tell me, and I will do my best to clarify for you. Hopefully you learned a thing or two about arrays and java.
ps, for Halloween, I dressed up as windows vista =)
No comments:
Post a Comment