Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning values of an array in a for loop java

Tags:

java

Im still starting out in java - and any guidance would be great on this. I'm basically hoping to create an array, then assign values to that array in a for loop. The code I have at the moment is:

int i;
int[] testarray = new int[50];

for (i = 0; i <=50; i++) {  
testarray[i]=i;
}

All i wanna do is make an array with each entry the number of the iteration (using this method) I know its really simple, but I feel as if I have missed something important during learning the basics! Thanks!

like image 647
Michael M Avatar asked Jul 15 '12 19:07

Michael M


People also ask

Can we declare array in for loop in Java?

Java Array is a collection of elements stored in a sequence. You can iterate over the elements of an array in Java using any of the looping statements.

How do you assign values to an array?

Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.


1 Answers

Everything is fine except the stop condition:

for (i = 0; i < 50; i++) {  

Since your array is of size 50, and indices start at 0, the last index is 49.

You should reduce the scope of i, avoid hard-coding the length everywhere (don't repeat yourself principle), and respect the camelCase naming conventions:

int[] testArray = new int[50];

for (int i = 0; i < testArray.length; i++) {  
    testArray[i]=i;
}
like image 130
JB Nizet Avatar answered Sep 28 '22 05:09

JB Nizet