Java Online Compiler
Example: Sum of Squares - Enhanced For Loop in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Sum of Squares - Enhanced For Loop public class Main { public static void main(String[] args) { // Step 1: Define the input array int[] numbers = {1, 2, 3, 4, 5}; // Step 2: Initialize a variable to store the sum of squares long sumOfSquares = 0; // Step 3: Iterate through the array using an enhanced for-each loop for (int number : numbers) { // Step 4: Square each element and add it to the sum sumOfSquares += (long) number * number; } // Step 5: Print the result System.out.println("Array elements: [1, 2, 3, 4, 5]"); System.out.println("Sum of squares (Enhanced For Loop): " + sumOfSquares); } }
Output
Clear
ADVERTISEMENTS