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.
Here total number of items: 4 items. So first of all, we will give the total number of items to the program. According to this number, programming will ask you to enter 4 numbers. Then program will calculate sum of given 4 number and display the sum on screen.
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
Advertisements
Responses
0 Respones to "Java Code to Calculate the Sum of Many Numbers"
Post a Comment