878891. For Loop - 2
Basic
For Loop - 2
Summary
The problem requires you to write a program that uses a for loop to calculate the sum of squares of all numbers from 1 to n. The key concept involved is the use of for loops in programming.
Detailed Explanation
To solve this problem, we can start by initializing a variable sum to zero, which will store the sum of squares. Then, we use a for loop that runs from 1 to n (inclusive). Inside the loop, we calculate the square of the current number and add it to sum. Finally, we print out the calculated sum.
Here's the step-by-step breakdown:
public class ForLoop {
public static void main(String[] args) {
int n = 5;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i * i;
}
System.out.println(sum);
}
}