Robotics C++ Physics II AP Physics B Electronics Java Astronomy Other Courses Summer Session  

One-Dimensional Arrays

 

Introduction

Initialization using a Loop, Finding the Largest Element and The Sum

Other Ways to Initialize

Passing and Receiving Arrays

Exercises

 

 

Introduction                         

 

Arrays are data structures

 

They contain data - variables - of same type (Integer, Double, for example)

 

The size of an array (how many elements if contains) is fixed once it is created

 

An array named c with 12 elements

 

    c is the name of the array

 

    Position number is in parentheses - it must be positive integer - first element has position

    number 0

 

Initialization Using a Loop

 

public class ArraysExample

{

    public static void main(String[] args)

    {

        int sum = 0;

        int myArray[] = new int[5];

        for (int i = 0; i< myArray.length; i++)

          {

               myArray[i] = 3*i;

          }

         System.out.println("The elements of the array are");

         for (int j = 0; j < myArray.length; j++)

        {

            System.out.println(myArray[j]);

        }

            for (int k = 0; k < myArray.length; k++)

        {

              sum = sum + myArray[k];

        }

             System.out.println("The sum is: " + sum);

          int largest = myArray[0];

          for (int m = 0; m < myArray.length; m++)

            {

             if (myArray[m] > largest)

                largest = myArray[m];

            }

                System.out.println("Largest element is: " + largest);

     }

}

 

Output

 

The elements of the array are

0

3

6

9

12

The sum is: 30

Largest element is: 12

 

Other Ways to Initialize

 

 

Direct Assignment:  A[0] = 4    A[1] = 10, etc

 

Initializer List: A[ ] = {1, 4, 5, 7};

 

Passing and Receiving Arrays

 

 

When you call a method from the main and pass the array, you insert the name of the array in the parameter list. For example, if you a calling a method named

PrintArray and passing an integer array named theArray, you use the following line of code

 

    PrintAray(theArray); 

 

The method receives the array as follows

 

   public static void PrintArray(int theArray[ ])

   {

      //code goes here 

   }