There are multiple way to find sum of numbers from 1 to 100.
for loop :-
- Start for loop initialize with i = 1.
- Write testing condition in for loop as i <= 100.
- Add increment in for loop as i++
- Initialize a variable sum with 0.
- Start adding i with the sum at each iteration of for loop.
- Print sum at the end for loop.
while loop :-
- Start initialize with j = 1.
- Initialize a variable add with 0.
- In while loop condition as j <= 100
- Start adding j with sum at each iteration of while loop and print j.
- Add increment statement as j++
- Print add value at the end of while loop.
IntStream method :-
- IntStream range(int startValue, int endValue) returns a stream of numbers starting from start value but stops before reaching the end value.
- Start adding value with the sum in between range.
- Return type is int and print sum of value.
Syntax : static IntStream range(int startInclusive, int endExclusive)
mathematical formula method :-
- In this program, we have used mathematical formula to find the sum of numbers from 1 to 100.
formula s = n * (n + 1) / 2;
import java.util.stream.IntStream;
public class FindSum {
public static void main(String[] args) {
// from for loop
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum = sum + i;
}
System.out.println("from for loop method value :- " + sum);
// from while loop
int add = 0;
int j = 1;
while (j <= 100) {
add = add + j;
j++;
}
System.out.println("from while loop method value :- " + add);
// from IntStream java 8 method
int sm = IntStream.range(1, 101).sum();
System.out.println("IntStream sum value :- " + sm);
// from do while loop
int k = 1, addition = 0;
do {
addition = addition + k;
k++;
} while (k <= 100);
System.out.println("from do while loop value :- " + addition);
// from mathematical formula method
int n = 100;
int s = n * (n + 1) / 2;
System.out.println("using mathematical (n+1) method :- " + s);
}
}
Output :-
from for loop method value :- 5050
from while loop method value :- 5050
IntStream sum value :- 5050
from do while loop value :- 5050
using mathematical (n+1) method :- 5050