Day 2 Java Arrays

Day 2: Arrays – Traversals, Operations & Basic Problems

🎯 Goals of the Day

  • Understand 1D array declaration and initialization in Java

  • Learn array traversal techniques

  • Solve beginner-level problems on arrays


📘 1. Arrays in Java – The Basics

An array is a collection of elements of the same type stored in contiguous memory.

🔹 Declaration:


int[] arr = new int[5]; // creates an array of size 5 int[] nums = {1, 2, 3, 4, 5}; // directly initialized

🔹 Access:


System.out.println(arr[0]); // prints the first element arr[2] = 10; // sets the third element to 10

🔁 2. Traversal of Arrays

🔹 Using For Loop:

for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]); }

🔹 Using Enhanced For Loop:

for (int num : arr) {
System.out.println(num); }

✍️ 3. Input in Arrays


Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); }

🔎 4. Basic Problems to Practice

🧠 Problem 1: Find the maximum element in an array


int max = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) max = arr[i]; } System.out.println("Max: " + max);

🧠 Problem 2: Reverse the array


int start = 0, end = arr.length - 1; while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; }

🧠 Problem 3: Sum of all elements


int sum = 0; for (int num : arr) { sum += num; } System.out.println("Sum = " + sum);

🧠 Problem 4: Check if array is sorted


boolean isSorted = true; for (int i = 0; i < arr.length - 1; i++) { if (arr[i] > arr[i + 1]) { isSorted = false; break; } } System.out.println(isSorted ? "Sorted" : "Not Sorted");

📚 5. Practice Questions for Today

Try solving these on any coding platform:

  • Find the second largest element in an array

  • Count frequency of an element in an array

  • Left rotate an array by 1 position

  • Move all 0s to the end of the array (maintaining order)


🔥 Bonus Tip:

Create reusable methods in Java to solve problems:


public static int findMax(int[] arr) { int max = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) max = arr[i]; } return max; }

Comments

Popular posts from this blog

Raster scan Vs Vector Scan

Inheritance

unit -1 Introduction of Image processing