Java Online Compiler
Example: Sum of Squares - Iterative For Loop in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Sum of Squares - Iterative 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; // Use long to prevent overflow for larger sums // Step 3: Iterate through the array using a traditional for loop for (int i = 0; i < numbers.length; i++) { // Step 4: Square each element and add it to the sum sumOfSquares += (long) numbers[i] * numbers[i]; } // Step 5: Print the result System.out.println("Array elements: [1, 2, 3, 4, 5]"); System.out.println("Sum of squares (Basic For Loop): " + sumOfSquares); } }
Output
Clear
ADVERTISEMENTS