Arrays in Java
Theory • Examples • Programs •
Homework
What is an Array?
• Array = collection of same-type elements
stored in contiguous memory.
• Index starts at 0.
Example:
int[] arr = {10, 20, 30};
Why Arrays?
✅ Store multiple values easily
✅ Easy access using index
✅ Reduces repeated variables
✅ Works well with loops
1D Array Example
int[] arr = {10, 20, 30, 40, 50};
for(int i=0;i<[Link];i++){
[Link](arr[i]);
}
Sum of Array Elements
int[] arr = {10,20,30,40,50};
int sum = 0;
for(int num : arr){ sum += num; }
[Link]("Sum = " + sum);
Largest and Smallest
int[] arr = {45,12,89,33,22};
int max=arr[0], min=arr[0];
for(int i=1;i<[Link];i++){
if(arr[i]>max) max=arr[i];
if(arr[i]<min) min=arr[i];
}
Reverse an Array
int[] arr={10,20,30,40,50};
for(int i=[Link]-1;i>=0;i--){
[Link](arr[i]+" ");
}
2D Array Example
int[][] m = {{1,2,3},{4,5,6},{7,8,9}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
[Link](m[i][j]+" ");
}
[Link]();
}
Homework
11️⃣Find average of array
2️⃣Count even & odd numbers
3️⃣Find 2nd largest number
4️⃣Copy one array to another
5️⃣Add two 2D matrices
6️⃣Sum of diagonals
7️⃣Sort array without [Link]()
Viva Questions
1. What is an array?
2. Array index starts at?
3. Can arrays store different types?
4. Default int value?
5. How to find array length?
6. What is contiguous memory?