-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSumOfNaturalNumbers.java
More file actions
33 lines (24 loc) · 715 Bytes
/
Copy pathSumOfNaturalNumbers.java
File metadata and controls
33 lines (24 loc) · 715 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/*Write a Java program to input a number n and calculate the sum of the first n natural numbers:
Sum=1+2+3+...+n
*/
import java.util.Scanner;
public class SumOfNaturalNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input
System.out.print("Enter a number: ");
int n = sc.nextInt();
int sum = 0;
// Using for loop
for (int i = 1; i <= n; i++) {
sum += i; // sum = sum + i
}
// Output
System.out.println("Sum of first " + n + " natural numbers = " + sum);
sc.close();
}
}
/* Example Run:
Enter a number: 5
Sum of first 5 natural numbers = 15
*/