Java Program to calculate the sum of numbers from 1 to 10.
Objective
Write a Java program to calculate and display the sum of the first 10 natural numbers using a loop.
Algorithm / Approach
- Initialize an integer variable
sumto 0. - Start a
forloop with a counteriinitialized to 1. - Run the loop as long as
i ≤ 10. - In each iteration, add the value of
itosum(sum = sum + i). - Increment
iby 1 after each iteration. - Once the loop finishes, print the final value of
sum.
Test.java
class Test {
public static void main(String[] a)
{
int sum =0;
for(int i =0;i<=10;i++) {
sum = sum+i;
}
System.out.print("Sum = "+sum);
}
}
Expected Output
Sum = 55
Explanation of the Program
- This program demonstrates basic iteration using a
forloop. - The loop executes 10 times. In the first iteration, 1 is added to the sum. In the second, 2 is added, and so on until 10.
- The variable
sumacts as an accumulator. It must be initialized to 0 because adding to an uninitialized variable would cause a compilation error in Java.
Complexity
Time Complexity
O(1) - The loop runs a fixed number of times (10).
Space Complexity
O(1)
Common Mistakes
- Declaring the
sumvariable inside the loop, which resets it to 0 on every iteration and makes it inaccessible outside the loop. - Using
i < 10instead ofi <= 10, which would miss the number 10 and result in 45 instead of 55.