Arrays with for loops

+1 Alioune Yague · November 30, 2015
How do you use arrays with for loops?

Post a Reply

Replies

Oldest  Newest  Rating
+1 Jagdeep Matharu · November 30, 2015
Here's an eg: For creating an array and summing up all numbers


// Create an array with room for 100 integers
int[] nums = new int[100];

// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
   nums[i] = i + 1;  // +1 since we want 1-100 and not 0-99

// Compute sum
int sum = 0;
for (int n : nums)
   sum += n;

// Print the result (5050)
System.out.println(sum);
0 Nicholas Eason · December 3, 2015
There are a few common ways to use for loops with arrays:

First, we have the "parse through every array item" way:

for(int i = 0; i < arrayName.length; i++){
//Whatever you want to do here
}

Second, maybe you only need to loop through a certain number of the objects in the array?

for(int i = 0; i < 10; i++){
//Whatever you want to do here
}


Lastly, another way to do the "parse through everything" :
for(ArrayDataType i : arrayName){
//Whatever you want here
//i.e if you have an array of Integers, replace ArrayDataType with int
//Note the colon, not a semicolon between the two objects.
}
  • 1

Java / Android Development

107,231 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator