Sum of n natural numbers
Problem to sum the natural numbers from 1 to n.
Example-1:
Input : n = 5 Output : 15 Explain : 1+2+3+4+5 = 15.
Example-2:
Input : n = 4 Output : 10 Explain : 1+2+3+4 = 10
Solution
public class Main { public static void main(String [] args) { int n = 5; int sum = 0; for(int i=1;i<=n;i++) { sum = sum+i; } System.out.print(sum); } }
n = 5 k = 0 for i in range(1,n+1): k += i print(k)
Output
15