JAVA- one dimensional Array

The one dimensional array is the simplest form of the array. And is used for the multiple values in a single variable.

Declaration syntax:  

data-type  array-name[ ];

e.g:      int student[ ];

giving memory: After declaration of array we have to create it into the memory so the ‘new’ keyword is used for this.

Syntax:           

array-name = new data-type[size];

e.g       student = new int[20];

in the above example we have array with the name of student and the size is 20. That means we can store 20 values in this array. And the computer reserves 20 locations for the array. And ‘new’ operator is used to assign memory to these 20 locations.

Representation of the array values and can be assigned as follows:

student[0]=1001

student[1]=1002

student[2]=1003

student[3]=1004

.

.

.

student[19]=1020

 

Initialization:

 a.      Compile time: the initialization is the same as we initialize the variables, but the difference only we gives the list of values. As follows:

Declaration syntax:   data-type array-name[size]={list of values};

e.g:  int student[5]={1,2,3};

in the above example the values 1,2,3 are initialized to array starting from 0. And the rest of locations are initialized to 0 automatically.

b.      Run time: we can assign the values with the loop.

For e.g:

Initialize the values of array:

e.g:

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

{

If(i>5)

number[i]  = 6;

else

number[i] = 8;

}

To print the values:

e.g:

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

{

system.out.println(number[i]);

}

Program:

//5.PROGRAM TO FIND THE SUM OF ELEMENTS OF A GIVEN ARRAY

class sumArray

{

int a[ ]={3,6,9,35,11,12,13},s=0,i;

int sum( )

{

for(i=0;i<=6;i++)

{

s=s+a[i];

}

return s;

}

public static void main(String args[ ])

{

int a;

sumArray s1=new sumArray( );

a=s1.sum( );

System.out.println(“Elements of array are: 3,6,9,35,11,12,13″);

System.out.println(“Sum of array elements is: “+a);

}

}

Leave a Reply

Your email address will not be published. Required fields are marked *