Array Introduction
- A variable which can hold multiple values of similar data type.
- Each element is differentiated by a number called
index number. - Index number starts with
0. - Use
newkeyword to create an array. - Or Array is the collection of
homogeneous(same ) type values . - Array take sequential memory allocation.
Syntax :
datatype []variable=new datatype[size];
Types of arrays
Arrays can be of two types
- Single Dimensional Array(1-D)
- Multi Dimensional Array(2-D)
1. Single Dimensional Array
- An array having only one row and multiple columns.
- Every array provides length property.
int []num=new int[6];
Array Initialization
int num[]={60,50,40,30,20,10};
- We can create an array of user defined size.
- Use length property to know the size of array.
Example
WAP to ask the user for the size. Create an array of that size, input the data into the array and show the sum and average of all those numbers.
import static java.lang.System.*;
import java.util.Scanner;
public class ArrayTest
{
public static void main(String args[])
{
Scanner sc=new Scanner(in);
out.print("Enter the size : ");
int size=sc.nextInt();
int []ar=new int[size];
for(int i=0;i<ar.length;i++)
{
out.printf("Enter data %d : ",i+1);
ar[i]=sc.nextInt();
}
int sum=0;
for(int i=0;i<ar.length;i++)
sum=sum+ar[i];
float avg=(float)sum/ar.length;
out.println("Sum is "+sum+" and average is "+avg);
}
}



