๐ก Introduction:
Natural numbers are the numbers used for counting — 1, 2, 3, 4, 5, ….
To find the sum of the first n natural numbers, we can use either a loop or a mathematical formula.
The formula is:
[
\text{Sum} = \frac{n(n + 1)}{2}
]
๐ง Java Program using Formula:
import java.util.Scanner;
public class SumOfNaturalNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Taking input from user
System.out.print("Enter a number (n): ");
int n = sc.nextInt();
// Using the mathematical formula
int sum = n * (n + 1) / 2;
// Displaying the result
System.out.println("The sum of first " + n + " natural numbers is: " + sum);
sc.close();
}
}
๐งพ Example Output:
Enter a number (n): 10
The sum of first 10 natural numbers is: 55
๐ Explanation:
-
Step 1: The user enters a number, say
n = 10. -
Step 2: The program calculates the sum using the formula
n*(n+1)/2. -
Step 3: It prints
55as the sum of the first 10 natural numbers.
๐ Alternate Program using Loop:
If you want to calculate the sum without a formula, here’s another approach:
import java.util.Scanner;
public class SumUsingLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number (n): ");
int n = sc.nextInt();
int sum = 0;
// Using for loop to add numbers
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println("The sum of first " + n + " natural numbers is: " + sum);
sc.close();
}
}
✅ Conclusion:
You can find the sum of the first n natural numbers easily in Java —
either by using the mathematical formula for efficiency or a loop for clarity.
Comments
Post a Comment