Thursday, 16 June 2016

Program to find the sum of first n Natural numbers.

Explanation :
If number = 5 then the output will be 1+2+3+4+5 i.e, equal to 15.

Code:

import java.util.Scanner;
public class Sum
{
       public static void main(String[] args)
       {
            int n,i=1,sum=0;
           Scanner sc=new Scanner(System.in);
           System.out.print("Enter Number :");
           n=sc.nextInt();
          do
         {
            sum=sum+i;
            i +=1;
          } while(i<=n);
            System.out.print("Sum of First " + n + " Numbers = "+sum);
         }
  }

No comments:

Post a Comment