Skip to content

Commit

Permalink
Sum of the first n natural numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
Arijit-SE committed Apr 11, 2023
1 parent 506c660 commit ff42a5c
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions Sum_Upto_n.java
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);
}
}

0 comments on commit ff42a5c

Please sign in to comment.