JAVA program to find sum of first n natural numbers
This JAVA program is to find the sum of first n natural numbers. Natural numbers are non-negative integers.
For example if we take 3 natural numbers 1,2,3 then their sum=6
Logic
Take a for loop starting with 0 keep incrementing the value of i and add it to the previous value.
Dry Run of the Program
Take input ‘n’ .Let us take n=3 //So it will give summation of 4 natural numbers
1st iteration for(i=0;i<=n;i++) i.e. for(i=0;i<=3;i++)
sum=sum+i i.e sum = 0 + 0 hence sum=0
2nd iteration for(i=1;i<=n;i++) i.e. for(i=1;i<=3;i++)
sum=sum+i i.e sum = 0 + 1 hence sum=1
3rd iteration for(i=2;i<=n;i++) i.e. for(i=2;i<=3;i++)
sum=sum+i i.e sum = 1 + 2 hence sum=3
4th iteration for(i=3;i<=n;i++) i.e. for(i=3;i<=3;i++)
sum=sum+i i.e sum = 3 + 3 hence sum=6
So output we get as sum = 6 for n=3.
Program
import java.util.*; class sum { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter a no"); int n = sc.nextInt(); int i,sum=0; for(i=0;i<=n;i++) { sum = sum + i; } System.out.println("Sum of first "+n+" natural nos = "+sum); } }