Exercises · Q10
Q.Write a Java program using a for loop to calculate and print the sum of the first N natural numbers, where N is entered by the user.
ChseodishaTextbookSubjectiveImportance★★★★★est
77% · 10/13 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Complete program:
import java.util.Scanner;
public class SumN {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter N: ");
int n = sc.nextInt();
int sum = 0; // accumulator starts at 0
for (int i = 1; i <= n; i++) {
sum += i; // add each number to the total
}
System.out.println("Sum = " + sum);
}
}
How it works. The variable sum is an accumulator, starting at 0. The for loop runs i from 1 up to n, and each pass adds the current i to sum. When the loop ends, sum holds 1 + 2 + ... + n.
Trace for N = 5:
| i | sum after adding i |
|---|---|
| 1 | 1 |
| 2 | 3 |
| 3 | 6 |
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.