Skip to content

Commit 1814be2

Browse files
committed
feat: Calculate sum of first n natural numbers using formula
🧠 Logic: - Read user input `n` using `Scanner`. - Apply the formula `sum = n * (n + 1) / 2` for the sum of first `n` natural numbers. - Display the result with a descriptive message. Signed-off-by: Somesh diwan <[email protected]>
1 parent ad3408d commit 1814be2

File tree

1 file changed

+2
-53
lines changed

1 file changed

+2
-53
lines changed

Section9ArrayAB/Array 2.0/src/SumOfTheNumbers.java

Lines changed: 2 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,65 +1,14 @@
1-
// Program to Print the Sum of First 10 Natural Numbers Using while Loop
2-
3-
//public class SumOfTheNumbers {
4-
// public static void main(String[] args) {
5-
// int i = 1; // Initialize the counter
6-
// int sum = 0; // Variable to store the sum
7-
//
8-
// while (i <= 10) {
9-
// sum += i; // Add the current number to the sum
10-
// i++; // Increment the counter
11-
// }
12-
//
13-
// System.out.println("Sum of first 10 natural numbers: " + sum);
14-
// }
15-
//}
16-
17-
18-
// Input from the user
19-
201
import java.util.Scanner;
21-
//public class SumOfTheNumbers
22-
//{
23-
// public static void main(String[] args)
24-
// {
25-
// Scanner scanner = new Scanner(System.in);
26-
27-
// Input from the user
28-
// System.out.print("Enter the value of n: ");
29-
// int n = scanner.nextInt();
30-
31-
// Initialize variables
32-
// int sum = 0;
33-
// int counter = 1;
34-
35-
// While loop to calculate the sum
36-
// while (counter <= n)
37-
// {
38-
// sum += counter;
39-
// counter++;
40-
// }
41-
42-
// Display the result
43-
// System.out.println("The sum of the first " + n + " natural numbers is: " + sum);
44-
// scanner.close();
45-
// }
46-
//}
47-
482

49-
public class SumOfTheNumbers
50-
{
51-
public static void main(String[] args)
52-
{
3+
public class SumOfTheNumbers {
4+
public static void main(String[] args) {
535
Scanner scanner = new Scanner(System.in);
546

55-
// Input from the user
567
System.out.print("Enter the value of n: ");
578
int n = scanner.nextInt();
589

59-
// Calculate sum using the formula
6010
int sum = n * (n + 1) / 2;
6111

62-
// Display the result
6312
System.out.println("The sum of the first " + n + " natural numbers is: " + sum);
6413

6514
scanner.close();

0 commit comments

Comments
 (0)