Printing an Array

From CompSciWiki
Revision as of 10:31, 8 April 2010 by JustinS (Talk | contribs)

Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

This problem involves you printing out an array of integers using a for loop. You want to make an array of 10 integers with values you can hard code into the program. Use System.out.println() to print out the integers. Remember that you can create an array of any type with hard coded values like this:

int[] array = {1, 2, 3};

Also remember that arrays start their indexing at 0 and you can check the length of an array in Java this way:

int length = array.length;
 

Introducing Arrays

Wiki array01.jpg

Solution

This problem is meant to give you a quick introduction to indexing arrays in a loop, specifically a for loop. For loops are the most common type of loop to use when working with arrays because of the fact that arrays have a set size. It is better style and proper coding practice to use a for loop in this instance instead of a while loop. We start this program by declaring our array. This is done by doing this:

int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

In order to declare an array we need the "[]" after the variable type to tell the compiler that we are using an array here. By using the {} we can initialize the array with values already inside of it instead of creating it with either 0's or null's. The next step is to simply iterate through our array with a for loop and at each iteration print out the number that is contained in the index.

for (int i = 0; i < array.length; i++)
  System.out.println(array[i]);

The reason we only go less than the array's length is because of our indexes start at 0. This means that an array with length 9 will have indexes 0, 1, 2,..., 8. This is a very common issue to run into when first starting to deal with arrays. If you forget it, Java will through you an Array Out Of Bounds Exception when your program runs. Always make sure to check your array indexes to make sure they will not go out of bounds.

Code

Solution Code

Back to the Program-A-Day homepage