0

I was programming right now and I wanted to modify the value of ten variables that shared their name but had a different index at the end. For example:

    int number1
    int number2
    int number3
    int number4
    ...

If I want to put the same value in all the variables, for example initialize them at 0, Is there any way to do this with a loop in which I only have to modify the index?

Something like this:

    for(int i=0;i<=10;i++) {
       number"i" = 0; }

Probably it is a silly question, but I can't find the solution. Thank you very much :)

2 Answers2

1

As mentioned in the comment, go for an array.

From the loop given in your question, it seems as if you want 10 numbers. In that case something like

int[] arNum = new int[10];

should declare the array.

To initialize the array with all 0, try

for (int i = 0; i < 10; i++)
    arNum[i] = 0;

Note: Array indexes always start at 0.

aliasm2k
  • 883
  • 6
  • 12
0

Just use an array:

int[] arr = new int[10];

To be clear:

Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10) [...] For type int, the default value is zero, that is, 0.

Taken from here. You might also want to take a look here.

Community
  • 1
  • 1
pzaenger
  • 11,381
  • 3
  • 45
  • 46