Arrays in java

“A collection of similar data items that can be stored in continuous memory” – An array.

It has the index starts from 0 to n.

Syntax:

Datatype Array_variable[ index_value];

Eg:

int a[10];

Sample Java program to create and display the array elements:

·       Create a class “arrayEg” and write the main() function inside it.

·       Declare the variable a[] as integer and assign some values.

·       Using a for loop, print the value.

class arrayEg

{

 public static void main(String args[])

 {

  int a[]={11,12,13,14,15,16,17,18,19,20};

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

  for(int i=0;i<10;i++)

  {

   System.out.println(a[i]);

  }

 }

}

Compile and run the program.

C:\raji\blog>javac arrayEg.java

C:\raji\blog>java arrayEg

The array elements are:

11

12

13

14

15

16

17

18

19

20

It is the easy way to use array elements. Next program is to find sum of elements of an array.

#Java program to find Sum of elements program of an array:

·       A special package “java.util.Scanner” is imported in this program.

·       A public class “ArrayEg1” with main() function is written here.

·       Create an object for Scanner class.

·       Read the input from runtime as number of elements.

·       Read the array elements using a for loop.

·       Again, using a for loop, add the array elements to sum variable.

·       Print the sum of elements.

·       Close the scanner.

Program:

import java.util.Scanner;

public class ArrayEg1 {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of elements");

        int no = scanner.nextInt(); // Read the number of elements

        int[] a = new int[no]; // Array declaration

        int j=0, sum=0;

        System.out.println("Enter " + no + " elements: ");

        for (j = 0; j< no; j++) {

            a[j] = scanner.nextInt(); // get the array elements

        }

        for (j = 0; j < no; j++) {

            sum=sum+a[j];

            }

         System.out.println("The sum of elements in the array: "+sum);

        scanner.close(); // Close the scanner

    }

}

The output is shown below.

C:\raji\blog>javac ArrayEg1.java

C:\raji\blog>java ArrayEg1

Enter the number of elements5

Enter 5 elements:

11

22

33

44

55

The sum of elements in the array: 165

This is the way of using Arrays in java.

No comments:

Post a Comment