To display the sum of the first n natural numbers in Java, you can use a loop to iterate through the numbers and keep a running total.
Here's an example of how to do this using a for
loop:
int n = 10; int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } System.out.println("Sum of first " + n + " natural numbers: " + sum);
This will output the following:
Sum of first 10 natural numbers: 55
You can also use a while
loop to achieve the same result:
int n = 10; int sum = 0; int i = 1; while (i <= n) { sum += i; i++; } System.out.println("Sum of first " + n + " natural numbers: " + sum);
This will also output the sum of the first 10 natural numbers.
You can use a similar approach to calculate the sum of the first n natural numbers for any value of n. Simply change the loop condition to the desired upper limit.