Array: Divide current element in loop by previous element
Hello,
I am going crazy with a simple issue on Arrays. I have spent hours on this (beginner!) I am trying to have an array and divide the second element by the first, the third by the second, the fourth by the third....
In other words,
int [] test ={a, b, c, d};//Using letters for illustrative purposes
//desired code is "divide b by a, c by b, d by c...
========================
My code looks like this:
publicclass ArrayTest{
/**
* @param args
*/
publicstaticvoid main(String[] args){
int[] stock ={1,2,5,8};
for(int x : stock){
System.out.println("This is the element value:" + x);
for(int i = 0; i < 5 ; i++){
int y = stock[i + 1] / stock[i];
System.out.println(y);
}
}
}
}
If anyone could help me or guide me to the right resources.
Thanks,
SymDev
[1745 byte] By [
SymDeva] at [2007-11-27 0:19:18]

> ...
> If anyone could help me or guide me to the right
> resources.
>
> Thanks,
> SymDev
You haven't told us what's wrong with it!
But I can make a decent guess though. You're getting unexpected values, right? That's how integer division works: everything gets floored to closest whole number. So if you divide 5/3 the outcome will be 1, not 1.6666....
What you need to do is chagne all int's to double's.
One other thing: never use magic numbers, like 5 in this line:for(int i = 0; i < 5 ; i++) {
because if you change the number of values in your stock array, you also need to change your magic number. It is a recipe for buggy code!
Better do it like this:int[] stock = {1,2,5,8};
// ...
for(int i = 0; i < stock.length-1; i++) {
Note that I added the -1 because you're accessing stock[i+1] in your for-statement and you'd get an ArrayIndexOutOfBoundsException while running your code.
Good luck.
Thanks for your feedback. After several hours, I figured out my problem. I had to use in my loop more than just i. I added j so that I could keep track of each index position (current divided by previous).
I will post the code later today for other beginners interested in the answer.
SymDev