Java Array Sum of Even Index Elements

--- Sum of elements at even index in an array (Java – explained simply) Imagine you’re sitting in front of me and you ask: 👉 “How do I add only the elements that are at even index positions in an array?” Let me explain it step by step 👇 --- 🔹 First, understand the idea of index In Java arrays, index always starts from 0. Example array: Index → 0 1 2 3 4 Array → 5 8 2 7 6 👉 Even indexes are: 0, 2, 4 👉 Elements at those indexes are: 5, 2, 6 So the answer will be: 5 + 2 + 6 = 13 --- 🔹 How do we solve this in Java? 1. Create a variable sum and initialize it to 0 2. Loop through the array 3. Check if the index is even (i % 2 == 0) 4. If yes, add that element to sum --- 💻 Java Code: int[] arr = {5, 8, 2, 7, 6}; int sum = 0; for (int i = 0; i < arr.length; i++) { if (i % 2 == 0) { sum = sum + arr[i]; } } System.out.println(sum); --- 🔹 What’s happening here? i % 2 == 0 → checks whether the index is even arr[i] → element present at that index Only elements at even index positions are added 📌 Output: 13 --- 🧠 One-line explanation: > “We loop through the array and add only those elements whose index is even.” This small logic helps you understand: ✔ index-based conditions ✔ loops with filtering ✔ problem-solving thinking in Java Perfect for DSA & interview basics 🚀 #Java #DSA #Array #Programming #CodingBasics #LearnJava #InterviewPrep

To view or add a comment, sign in

Explore content categories