Calculate the Sum of Numbers in Java
Finding the sum of many numbers is one of the basic programs in Java programming. This is a simple java console program to find the sum of a set of numbers. Using this program, we can find the sum of unlimited numbers.
At first, this program will accept the total number of numbers. After this, program will accept all numbers from user separately.
Example: If number are 1, 2, 3 and 4.
Like: sum is = 1+2+3+4 = 10
You can also find the sum of many numbers without asking total number of items using array. Here we have to declare an array with a limit. Like int nums[] = new int[10]; Here the limit is 10, that is program accept only 10 number to find sum. Then after 10 entering of number, program will calculate the sum.
Here class name is ‘sum’, so you should save your file with name ‘sum.java’.
Lean here how to create, compile and run a java application program here.
Program code:
import java.io.*;
class sum
{
int num;
double sum = 0;
double result;
void findsum() throws IOException
{
BufferedReader Br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\n Mean of how many numbers : ");
num = Integer.parseInt(Br.readLine());
int nums[] = new int[num+1];
for(int i = 1;i<=num;i++)
{
System.out.print("\n Enter " + i + " number : ");
nums[i]= Integer.parseInt(Br.readLine());
sum = sum + nums[i];
}
System.out.print("\n Sum is : "+ sum );
}
public static void main(String s[]) throws IOException
{
sum sm = new sum();
sm.findsum();
}
}

Sample Output:
How many number : 4
Enter 1 st Number : 1
Enter 2 nd Number : 2
Enter 3 rd Number : 3
Enter 4 th Number : 4
Sum is : 10.0
If you have any doubt, then comment here
No comments:
Post a Comment