Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to calculate the sum of numbers from 1 to 10.

Java Code Example — Simple Programs

ADVERTISEMENT

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

  1. Initialize an integer variable sum to 0.
  2. Start a for loop with a counter i initialized to 1.
  3. Run the loop as long as i ≤ 10.
  4. In each iteration, add the value of i to sum (sum = sum + i).
  5. Increment i by 1 after each iteration.
  6. 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 for loop.
  • 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 sum acts 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 sum variable inside the loop, which resets it to 0 on every iteration and makes it inaccessible outside the loop.
  • Using i < 10 instead of i <= 10, which would miss the number 10 and result in 45 instead of 55.
ADVERTISEMENT