Sum of n Natural Numbers in Java Using For Loop

Sum of n Natural Numbers in Java. In a Java program, find the sum of n numbers. It will print the addition of n numbers in the java programming language for beginners, as well as the addition of a user-entered number. The result or answer we get when we add two or more numbers or words is known as sum.

Non Natural Numbers in Java

Imaginary numbers, such as the square root of -1, are numbers that cannot be quantified. The number I can be used in formulae and equations, but it is not a real number that can be utilized in fundamental arithmetic. You can’t multiply or divide imaginary numbers. Infinity is another example of an imaginary number.

nextint() in Java

nextInt() is a method that returns an integer. As an int scans the next token of the input. The invocation of this function with the form nextInt() acts precisely like the call nextInt, where radix is the scanner’s default radix.

Natural Numbers in Java

The counting numbers 1, 2, 3,… are generally referred to as natural numbers; however, some definitions include 0, making the non-negative integers 0 through 1, 2, 3,… natural numbers as well. Whole numbers are natural numbers that include 0 as well.

import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
int i, n, sum=0, num;
Scanner scan = new Scanner(System.in);
System.out.print("How many numbers you want to add");
n = scan.nextInt();
System.out.print("Enter " +n+ " number");
for(i=0; i<n; i++)
{
num = scan.nextInt();
sum = sum + num;
}
System.out.print("Sum of all " +n+ " numbers are " +sum);
}
}

Output
How many numbers you want to add 5
Enter 5 number
45
56
78
34
89
Sum of all 5 numbers are 302