- Get link
- X
- Other Apps
Array
In the Datatypes , we learnt about Non-Primitive or derived datatypes. Array is a non-primitive datatype.
An Array is a collection of homogeneous data. Arrays are used to store logically related values.They are useful for writing programs where a large number of data to be used. Array can store values up to n number. For example, we can store integer value in an integer array.
All the array elements must be either of any primitive types like int, float, double, char or they can be reference types like String and classes.Array has index to access the values present in it.Array's index starts from 0.
Declaring an Array
In java, we can declare array by using following syntax:
datatype arrayname[];
or
datatype[] arrayname;
Example:
int[] a;
or
int a[];
"a" is the name of array and we want an integer array so its dataype is "int".
Defining an Array
After declaration, we need to initialized or define array. We can define array using following syntax:
datatype[] arrayname={value1,value2,value3, value4 ... n};
"value1...n" are the values that we want to store in array. We can store up to n values .
Example:
int a={1,2,3,4,5};
We can fix the size by specifying the size of array within square brackets.As int[5] is an array that will contain only 5 values from 0-4.
In the above image, we have defined an array with 8 elements. Array index starts from 0 and ends at 7. Array elements can be accessed using these indexes. If we want to access element 5 of array then we can use a[4] index.
Accessing and Printing Array elements
Array can have many elements of same data type.So, we cannot just print them using single print statement.Therefore , we use for loop to print array elements.
Getting Array elements from user
We can get array elements from user by Scanner class.We require for loop and a scanner object for this.
Now, lets see an example for input and output of an array.
Example: This example will illustrate the input and output of an integer array.
Write a program to get an int array from user and print it on screen
In the above example,
- An array named "array" is defined and initialized with some int values. Then it is printed on screen using for loop. The for loop prints the array element at "i" position. The "i" is a loop variable which gets increased each time the loop runs. For example, When i=0, for loop will print the element present at index 0 as array[0]=1. In this way, all elements are printed on screen.
- In second way, we used the "n" as array size.If user enters 5 then array will be of size 5. After we used Scanner object to get array elements from user. This operation is also performed using for loop.Scanner method "nextInt()" read each array element for index "i".Where "i" gets incremented each time loop executes,
Output:
Experiment: Practice array programs as much as you can. Array plays very important role in coding.
Happy Coding!
Comments
Post a Comment
If you have any doubt, ask here