|
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 | | - |
20 | 1 | 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 | | - |
48 | 2 |
|
49 | | -public class SumOfTheNumbers |
50 | | -{ |
51 | | - public static void main(String[] args) |
52 | | - { |
| 3 | +public class SumOfTheNumbers { |
| 4 | + public static void main(String[] args) { |
53 | 5 | Scanner scanner = new Scanner(System.in); |
54 | 6 |
|
55 | | -// Input from the user |
56 | 7 | System.out.print("Enter the value of n: "); |
57 | 8 | int n = scanner.nextInt(); |
58 | 9 |
|
59 | | -// Calculate sum using the formula |
60 | 10 | int sum = n * (n + 1) / 2; |
61 | 11 |
|
62 | | -// Display the result |
63 | 12 | System.out.println("The sum of the first " + n + " natural numbers is: " + sum); |
64 | 13 |
|
65 | 14 | scanner.close(); |
|
0 commit comments