easyProgramming Fundamentals
For, While & Do-While Loops
Use a loop to add every integer from 1 through n.
Work through the cases
3 examplesInput notation
An integer n, where 0 <= n <= 100000.Expected result
The sum; print 0 for n = 0.Case 1
Input
5
Expected output
15
Case 2
Input
0
Expected output
0
Case 3
Input
1
Expected output
1
These notes use simplified input/output notation. The linked platform defines the method signature and judge format.
FROM IDEA TO IMPLEMENTATION
Understand the approach.
Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.
Add every value from 1 through n. This exercise deliberately practices a loop. Time: O(n). Extra space: O(1).
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Long> values = new ArrayList<>();
while (in.hasNextLong()) values.add(in.nextLong());
long[] a = values.stream().mapToLong(Long::longValue).toArray();
long n = a[0];
long total = 0; for (long i = 1; i <= n; i++) total += i; System.out.println(total);
}
}
Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.