Skip to content

Commit 2b8ca1b

Browse files
committed
feat: Calculate sum of first 'n' natural numbers using while loop with user input
🧠 Logic: - Take user input `n` for number of terms. - Initialize `sum = 0` and `counter = 1`. - Use a `while` loop to add each number from 1 to `n` to `sum`. - Print the result after the loop ends. Signed-off-by: Somesh diwan <[email protected]>
1 parent a4b1160 commit 2b8ca1b

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import java.util.Scanner;
2+
public class SumOfTheNumbers3 {
3+
public static void main(String[] args) {
4+
Scanner scanner = new Scanner(System.in);
5+
6+
System.out.print("Enter the value of n: ");
7+
int n = scanner.nextInt();
8+
9+
int sum = 0;
10+
int counter = 1;
11+
12+
// While loop to calculate the sum
13+
while (counter <= n) {
14+
sum += counter; // Add the current number to the sum
15+
counter++;
16+
}
17+
System.out.println("The sum of the first " + n + " natural numbers is: " + sum);
18+
scanner.close();
19+
}
20+
}

0 commit comments

Comments
 (0)