+ 1

How to assign an array position number plus 1 to as value of the array ?

how to set a range eg I would.like an array of 125 with values of 1-126

21st Sep 2017, 7:01 PM
Agnesness
Agnesness - avatar
9 Answers
+ 4
Simple loop will accomplish that. Just assign the i+1 value to it as it iterates through the loop.
21st Sep 2017, 7:12 PM
AgentSmith
+ 3
If I understood your question, maybe this is what you're trying to do? (I set the array to 5 because it's easier to test that way. You can set it to 126, and that'll generate the result you seek.) https://code.sololearn.com/cY45Lc35Z5pp/#java int[] intArray = new int[5]; int counter = 0; while( counter < intArray.length ) { intArray[counter] = counter + 1; System.out.println("Index " + counter + ": " + intArray[counter] ); counter++; }
21st Sep 2017, 7:32 PM
AgentSmith
+ 2
@Anges No problem. To the best of my knowledge, I don't think the fill method allows you to specify a range of integers to use for the value. I'll poke around and see what I can track down for you though. Also, you could always create a class for your own custom functions, and just create a method to accomplish this goal. Then you can use your own custom functions in any of your other code when you need to do something like this.
21st Sep 2017, 7:51 PM
AgentSmith
+ 1
Yes I think this will work, thank you. would have been nice if I could make the fill method work int [] decasc =new int[125]; Arrays.fill(decasc,1-125); for(int value:decasc){ System.out.println(" the range is "+value); but cannot find the right syntax. tried 1..125 1 to 125
21st Sep 2017, 7:40 PM
Agnesness
Agnesness - avatar
+ 1
@Anges Here you go bro: This will give you the "fill" affect you're looking for, except you control the value range and it'll be sequential. https://code.sololearn.com/cTClm1rdPk1W/#java import java.util.stream.IntStream; public class Program { public static void main(String[] args) { int[] intArray = IntStream.rangeClosed(1, 126).toArray(); for(int x : intArray) { System.out.println(x); } } }
21st Sep 2017, 7:59 PM
AgentSmith
+ 1
yeay thank you so much, this is perfect
21st Sep 2017, 8:00 PM
Agnesness
Agnesness - avatar
+ 1
@Anges Okay, excellent! I'm glad it'll be of some use to you. Best of luck with whatever you're working on!
21st Sep 2017, 8:02 PM
AgentSmith
0
I'm not sure but I think this would do it #include <iostream> using namespace std; int main() { int x; int arr[125]; while (x != 125) { x++; arr[x] = x; } return 0; }
21st Sep 2017, 7:13 PM
ReimarPB
ReimarPB - avatar
0
thank you I tried the int [] decasc =new int[126]; Arrays.fill(decasc,+1); but that didnt work out well
21st Sep 2017, 7:16 PM
Agnesness
Agnesness - avatar