Lecture#04_Arrays
Lecture#04_Arrays
PROGRAMMING
ARRAY
S
OUTLINE
◾ Arrays
◾ One-Dimensional Arrays
◾ Multidimensional Arrays
◾ int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
INPUT IN A N ARRAY FRO M KEYBOARD
◾ Java does not provide any direct way to take array input.
◾ But we can take array input by using the method of the
Scanner class.
import java.util.Scanner; //creates an array in the memory
public class ArrayInputExample1 of length 10
{ int[] array = new int[n];
public static void main(String[] args) System.out.println("Enter elements of
{ the arra y: ");
int n; for(int i=0; i<n; i++){
Scanner sc=new Scanner(System.in); //reading array elements
System.out.print("Enter the number from the user
of elements y ou want to store: "); array[i]=sc.nextInt();
//reading the number of elements }
from the that we want to enter System.out.println("Array
n=sc.nextInt(); elements are: ");
// accessing array elements using
the for loop for (int i=0; i<n; i+
+)
{
MULTIDIMENSIONAL ARRAYS
◾ Example:
[0] [0] [0] [1] [0] [2] [0] [3] [0] [4]
Left index
[1] [0] [1] [1] [1] [2] [1] [3] [1] [4]
determines row
[2] [0] [2] [1] [2] [2] [2] [3] [2] [4]
[3] [0] [3] [1] [3] [2] [3] [3] [3] [4]
◾ Example
double m[][] = {
◾ The square brackets follow the type specifier, and not the name
of the array variable.
◾ The following two declarations are equivalent:
◾ int a1[] = new int[3];
◾ int[] a1 = new int[3];
FINDING LENGTH OF A N ARRAY
/ This program demonstrates the length array
member. class Length {
public static void main(String args[]) {
int a1[] = new int[10];
int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};
int a3[] = {4, 3, 2, 1};
System.out.println("length of a1 is " +
a1.length); System.out.println("length of
a2 is " + a2.length); Output
}System.out.println("length of a3 is " + length of a1 is 10
length of a2 is 8
} a3.length); length of a3 is 4
PROGRAMMING EXERCISES
◾ Matrix Manipulation
◾ Addition of two matrices
◾ Displaying 2D Arrays