One-Dimensional Array - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript One-Dimensional Array - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Friday, March 15, 2019

One-Dimensional Array

One-Dimensional Array

üCreating an array is a two steps process:

  1. type var_name[];

     2. var_name = new type [size];

üExample: int month_days [];

                    month_days = new int [12];

     - first line declares month_days as an array variable, no array actually exists.

     - Actual, physical array of integers, is allocated using new
     and assign it to month_days.

     -The elements of array are automatically initialized to 0.

üint month_days [] = new int[12];


üOnce array is created, a specific element in the array can be accessed by specifying its index within square brackets.


     Example: month_days[0]=31;
           month_days[1]=28;

üArrays can be initialized when they are declared.
  Example:

  int month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31,  
                                     30, 31};
Features of Java to Manipulate Array

üAll arrays are dynamically allocated.

üSize of the array can be specified at the runtime.

üIndex type is integer and the index range must be 0 to n-1, where n is the number of elements.

üJava runtime system will check to be sure that all array indexes are in the correct range. Incorrect reference will generate ArrayIndexOutofBoundsException.

Example


import java.util.Scanner;


class array_avg

{

  public static void main(String args[])

  {

  int i,sum=0;

  float avg;
 
  int a[] = new int[5];
 
  Scanner test=new Scanner(System.in);
 
  System.out.println("Enter the input:");
 
  for(i=0;i<5;i++)

  {

  if(test.hasNextInt())

  {

  a[i]=test.nextInt();

  sum=sum+a[i];

  }

  }

  avg=sum/5;
 
  System.out.println("The average value is: " + avg);
 
  }

}

No comments:

Post a Comment

Post Top Ad