If you have any query feel free to chat us!
Happy Coding! Happy Learning!
The sum of the first N natural numbers is a common mathematical problem that can be solved using a formula or a loop in programming. The formula for finding the sum of the first N natural numbers is:
Sum = (N * (N + 1)) / 2
Here's an example Java program that calculates the sum of the first N natural numbers using a loop:
javaCopy code
import java.util.Scanner;
public class SumOfNaturalNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of N: ");
int N = scanner.nextInt();
// Calculate the sum using a loop
int sum = 0;
for (int i = 1; i <= N; i++) {
sum += i;
}
System.out.println("Sum of the first " + N + " natural numbers is: " + sum);
scanner.close();
}
}
Example output:
mathematicaCopy code
Enter the value of N: 5
Sum of the first 5 natural numbers is: 15
In the program above, we use a for loop to iterate from 1 to N and keep adding each number to the sum
variable. After the loop, we print the final sum.
However, it's worth noting that for large values of N, using the formula (N * (N + 1)) / 2 is more efficient than using a loop to add individual numbers. The formula has a time complexity of O(1), while the loop-based approach has a time complexity of O(N).
Comments: 0