Thursday, 23 May 2013

IMPLEMENTING ARRAYS IN JAVA

Arrays are the contiguous and homogeneous collection of data, that can be referred through a common name. Arrays come under the static data types. In this post I will be explaining how to implement arrays in Java. Arrays of any type can be created and can have one or more dimensions. Any element of array can be accessed through a common array name and using the index number. Unlike C and C++, arrays in java essentially start with index number 0. Also while declaring any array in java, we should allot memory to that array using the new operator, as you can recall, this was not a necessary thing in C or C++.

The following program illustrates the implementation of arrays in java and lets you enter the maximum number of elements and the data of array, and then calculates the sum of all these elements.

Source code:-
/****************************************************************************/
 import java.util.Scanner;

//program illustrating arrays implementation
public class arrays {

public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("ENTER THE MAXIMUM NUMBER OF ELEMENTS OF ARRAY");
int num=s.nextInt();
//num contains maximum number of elements of array

int arr[]=new int[num];
int sum=0;
System.out.println("ENTER THE DATA OF ARRAY");
for(int i=0;i<num;i++)
{
arr[i]=s.nextInt();
sum+=arr[i];
}
System.out.println("sum = "+sum);
}

}
/********************************************************************************/

No comments:

Post a Comment