We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7
Arrays: One-Dimensional,
Multidimensional
Module - 1
Dr.M.Gunasekar, AP-SCOPE, VIT
Array • Array is a collection of similar data items stored at contiguous memory locations. • It is the simplest data structure where each data element can be accessed directly by only using its index number. • Array declaration Syntax: • int [] array_name; or int array_name[]; • Array initialization: • Static: int [] a={1,2,3,4,5}; • Dynamic: int [] a=new int[5]; //Creates an array of length 5 with default values (0 for int)
Dr.M.Gunasekar, AP-SCOPE, VIT Java Programming 2
Example (1D array) int [] a={10, 20, 30, 40, 50} Indexes 0 1 2 3 4
Values 10 20 30 40 50
a[0] = 10 a[1] = 20 a[3] = 30 a[4] = 40 a[5] = 50
Dr.M.Gunasekar, AP-SCOPE, VIT Java Programming 3
Example Program – 1D Array import java.util.*; int sum=0; class OnedArray{ /* add all the integers in the array ‘a’ and public static void main (String args[]) print the sum*/ { for(int i=0;i<a.length;i++) int [] a=new int[5]; { /*read input from user using scanner sum=sum+a[i]; class*/ } Scanner sc=new Scanner(System.in); System.out.println("The sum of the for(int i=0;i<a.length;i++) integers in array a is " +sum); { }} a[i]=sc.nextInt(); }
Dr.M.Gunasekar, AP-SCOPE, VIT Java Programming 4
Dr.M.Gunasekar, AP-SCOPE, VIT 5 Two Dimensional Array • Syntax: Data_type [][] array_name = new data_type[row_size][column_size];
• Example: int [][] A=new int[3][2];
Dr.M.Gunasekar, AP-SCOPE, VIT Java Programming
2D Array example: Matrix Multiplication class MatrixMultiplication{ for(int k=0; k<B.length; k++) public static void main(String a[]){ { /*declaring and initializing a 2D array*/ //array multiplication int A[][]={{1,2,3},{2,3,4}}; C[i][j]+=A[i][k]*B[k][j]; int B[][]={{1,1},{2,2},{3,3}}; }}} //declaring 2d array //print the resultant matrix C int C[][]=new int [A.length][B[0].length]; for(int i=0; i<C.length; i++) for(int i=0; i<A.length; i++) { { for(int j=0; j<C[0].length; j++) for(int j=0; j<B[0].length; j++) { { System.out.println(C[i][j]); /*initializing the value of C[i][j] to 0 else garbage value would }}}} be considered*/ C[i][j]=0;