Java program to find sum of natural numbers

To find the sum of natural numbers, we first need to know what are natural numbers?

java program to find sum of natural numbers


Natural numbers are the part of the number system which includes

all positive integers from 1 to infinity. We do not count zero in the

natural numbers. Therefore, they start from 1.


We will see the example through :

  • while loop with users choice
  • for loop with users choice
1) Using while loop with users choice


    
      import java.util.*;
class SumNaturalq {

    public static void main(String[] args) {
        Scanner in= new Scanner(System.in);
        int n, i=1, sum=0;
        System.out.println("Enter a number till which you want the sum");       
        n = in.nextInt();

        while(i <= n)
        {
            sum =sum+ i;
            i++;
        }

        System.out.println("Sum = " + sum);
    }
}
Output: 
Enter a number till which you want the sum 5 (users choice) 
 Sum = 15 
 2) Using for loop with users choice
    
      import java.util.*;
class SumNatural
{
    public static void main(String args[])
    {
    Scanner in = new Scanner(System.in);
    int n,i, sum=0;
    n=in.nextInt();
    for(i=1;i<=n;i++)
    {
        sum=i+sum;
    }
    System.out.println("The sum of natural numbers from 1 to n is "+ sum);
}
}
    
  
Output: 
5(users choice) 

 The sum of natural numbers from 1 to n is 15

Hope you understand the program. You may also visit this site for programs related to Java.

Comments

  1. I'm sure you had great knowledge about this. You gave us much information. This information is really good and commentable. Thanks for sharing your things with us. Gate Computer Science

    ReplyDelete

Post a Comment

Popular Posts