Tuesday, April 16, 2013

Array in Java

Array in Java

Format for array

Int  Arrayname=new arraytype[size of array]

If your array is integer array then
Num=new int[10]

In above example array name is Num
Array type is int(other types float,String)
And array size is 10

We can also stored data directly in array
Format for this
Int arrayname[]={1,2,3,4,5}

Example:


class Array
{

    public static void main(String[] args)
    {
        int add=0,i;
        int number[]={1,2,3,4,5,6,7,8,9,10};
        for(i=0;i<10;i++)
        {
            add=add+number[i];
           
        }
        System.out.println(+add);
    }
}

Explenation of above example
       class Array
        our class name is Array
       public static void main(String[] args)
                declaration of  main mathod
       int add=0,i;
          declare variables 'add'  and ' i'
          add=0 we initialize the value of 'add' variable equal to '0'
         int number[]={1,2,3,4,5,6,7,8,9,10};
            here we initialize the array of size 10
            and having value 1,2,3,4,5,6,7,8,9,10 
always remember that memory aloccation in array is start from 0
means
number[0]=1;
at zero location 1 is presant in array
number[1]=2;
number[2]=3;
number[3]=4;
number[4]=5;
number[5]=6;
number[6]=7;
number[7]=8;
number[8]=9;
number[9]=10;

       for(i=0;i<10;i++)
          its our for loop
          initialization of  i=0;

 then condition is check i<10;
0<10;
condition is true
then execution of boady of for loop
add=add+number[i];
here we have value of add=0;
number[i]=number[0]=1;
then add=0+1;
we get new value for add=1;
after this  increment of i is done by 1
this procedure is continue till for loop condition is false
System.out.println(+add); statement is executed and we
get add=55


No comments:

Post a Comment