-
Notifications
You must be signed in to change notification settings - Fork 109
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
/* | ||
Write a Java program that takes a user input integer n and calculates the sum of the first n natural numbers. | ||
The program should use a for loop to calculate the sum. | ||
Sample Input: | ||
--------------------- | ||
5 | ||
Sample Output: | ||
--------------------- | ||
The sum of first 5 natural numbers is 15. | ||
Explanation: | ||
--------------------- | ||
The first 5 natural numbers are: 1, 2, 3, 4, 5 | ||
Their sum is: 1 + 2 + 3 + 4 + 5 = 15 | ||
*/ | ||
import java.util.*; | ||
public class Sum_Upto_n { | ||
public static void main(String[] args) { | ||
Scanner sc = new Scanner(System.in); | ||
int k = sc.nextInt(); | ||
int sum=0; | ||
for (int i = 1; i <= k; i++) { | ||
sum+=i; | ||
} | ||
System.out.println(sum); | ||
} | ||
} |