Saturday 8 November 2014

Arrays

One dimensional arrays

 As we have seen earlier simple variables stores single value. If we want to store multiple values of same type in single variable we can use arrays.
Structure
int arr[];
arr=new int[10];
Let us have a look at this one
As I told you earlier here arr is a variable of data type integer but in addition to that we have a new symbol [] which says that arr is a array variable. This is just declaration.

arr=new int[10] this line says that arr is capable of storing 10 integer values and you can access each one of them by their index value which starts from 0 onwards.
So the first element can be accesses by arr[0] and second one by arr[1] and so on and the 10th one can be accesses by arr[9];
Here arr[i] where 0<=i<=10 is equal to a single integer. Whatever operations we have performed on integer variables all of them are applicable to arr[i] also.
Lets take an example 
class arraydemo{
         public static void main(String args[]){
                int arr[]=new int[5];
                arr[0]=0;
               arr[1]=1;
               arr[2]=2;
               arr[3]=3;
               arr[4]=4;
               int x=arr[1]+arr[4];
               System.out.println(x);
        }
}
Output of this code is 5.
Think and understand why this is 5.
We can define arrays in another way also.
 int arr[]=new int[6];
arr[]={1,2,3,4,5,6};
We can assign all the elements at a time.
Here I will give you a small introduction about 2D-arrays.
int arr[][]=new int [2][3];
arr[]={1,2,3,4,5,6};
Now this means that arr has two rows and three columns
If declare like this first 3 elements in the array joins the first row and next 3 joins next row and so on
Accessing the elements will be same.
As the dimensions increases the complexity of visualizing will increase. Try visualizing 3D array.
For better understanding go through Next topic.

No comments:

Post a Comment