Reputation: 95
I need an array that takes a given int (x) that is the starting number and then count up to a bigger number (y) Any ideas?
int x = 5;
int y = 10;
int b = y - x;
int[] a = new int[b];
for (int i=0; i<b; i++) {
a[i] = i;
System.out.println(a);
}
//Should be: a = {5, 6, 7, 8, 9}
//I get the right length array but not the right vaules
Upvotes: 0
Views: 874
Reputation: 30839
Assignment a[i] = i
assigns values 0,1,2.. to the array elements. Instead, we need to start from min
value (5 in this case). We can do it by declaring anoter variable and incrementing it in the loop (so that the value of original argument won't change) like below:
int start = x;
for (int i=0; i<b; i++) {
a[i] = start++;
System.out.println(a);
}
Upvotes: 2