Challenge: Sum 1 to N
Completed
Read a whole number n and print the sum 1 + 2 + ... + n.
Input
One whole number n (1 ≤ n ≤ 10000).
Output
The sum.
Example
Input
5
Output
15
Editor
Java
Hints
Start with sum = 0.
Loop i from 1 to n and add i each time.
Solution explanation
A for loop visits every number from 1 to n; sum += i keeps a running total.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println(sum);
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module