Java Arrays
Java Arrays
Introduction to Arrays
• An array is a collection of similar data types stored in contiguous
memory locations.
• Instead of writing:
int num1 = 10;
int num2 = 20;
int num3 = 30;
• We can write:
int[] numbers = {10, 20, 30};
[Link](arr[0]);
o/p-10
[Link](marks[1]);
o/p-20
• To access full array :-
then we use for loop
Two-Dimensional Array:-
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
• For each loop:-
• Limitations of Arrays
Fixed size — cannot grow or shrink after creation.
Only stores elements of same data type.
Assignments on arrays
• Level 1: Basic Array Practice
• Create and display array elements
• Write a program to store 5 numbers in an array and display them using a for loop.
• Input from user
• Take 5 integer inputs from user and print them using a for loop.
(Hint: Use Scanner class)
• Access specific element
• Print the first and last element of an integer array.
• Find sum of array elements
• Take 10 integers in an array and print their total sum.
• Find average of array elements
• Store marks of 5 subjects and find average marks.
• Print array in reverse order
• Print elements from last to first using a loop.
• Count even and odd numbers
• Input 10 numbers and count how many are even and how many are odd.
• Level 2: Intermediate Practice
• Find maximum and minimum element
• Input an array of integers and print the largest and smallest number.
• Search an element in array
• Input an element from user and check whether it exists in the array.
• Copy one array into another
• Copy all elements of one array into another using a loop.
• Sort an array (ascending order)
• Sort array elements manually (without using [Link]()).
• Find second largest element
• Write a program to find the second largest number in an array.
• Count positive, negative, and zero elements
• Input numbers and count how many are positive, negative, or zero.
• Calculate frequency of each element
• Input elements and print how many times each element appears.
(Hint: Use nested loops)
• Level 3: Slightly Advanced
• Merge two arrays
• Input two arrays and store elements into a third array.
• Remove duplicate elements
• Write a program to remove duplicate numbers from an array.
• Find the smallest and largest number without sorting
• Find min and max using a single loop.
• Reverse array using a new array
• Create a second array to store reversed elements.
• Sum of even-position elements
• Calculate sum of elements present at even indexes only.
• Find common elements between two arrays
• Print all elements that exist in both arrays.