Write a Java program demonstrating a method with varargs that calculates the sum of even indices in an array of integers
There's a method called calculateEvenIndexSum, which takes a variable number of integers as input. This method calculates the sum of the numbers located at even indices (0-indexed) in the input array. It iterates through the array using a for loop with a step size of 2, starting from index 0, and adds the numbers at even indices to a running total.
The main method serves as the entry point of the program. Inside main, it calls the calculateEvenIndexSum method with the numbers 10, 20, 30, 40, and 50 as arguments. It stores the result in the variable evenIndexSum.
Finally, it prints out the result using System.out.println, displaying "Sum of even indices : " followed by the calculated sum of numbers located at even indices in the array.
public class EvenIndexSumCalculator { static int calculateEvenIndexSum(int... numbers) { int sum = 0; for (int i = 0; i < numbers.length; i += 2) { sum += numbers[i]; } return sum; } public static void main(String[] args) { int evenIndexSum = calculateEvenIndexSum(10, 20, 30, 40, 50); System.out.println("Sum of even indices : " + evenIndexSum); } }
Sum of even indices : 90
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions