Java program to find sum of natural numbers
To find the sum of natural numbers, we first need to know what are 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
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);
}
}
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.
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