Wednesday 14 June 2017

Java Implementation of Computing the Summation of a set of numbers

Problem:

Given a set of n numbers design an algorithm that adds these numbers and returns the resultant sum. Assume n is greater than or equal to zero.


Algorithm:

1. Prompt and read in the number of numbers to be summed.
2. Initialize sum for zero numbers
3. While less than n numbers have been summed repeatedly do
      a. read in next number
      b. compute current sum by adding the number read to the most recent sum.
4. Write out sum of n numbers.


Solution:

package com.myprograms;

import java.util.Scanner;

public class SummationOfNNumbers {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter how many numbers you want to sum");
int n = s.nextInt();
int sum = 0;
for(int i = 0; i <n; i++){
System.out.println("enter the number");
sum = sum + s.nextInt();
}
System.out.println("the sum is" + sum);
s.close();
}

}

Output:

enter how many numbers you want to sum
5
enter the number
100
enter the number
200
enter the number
300
enter the number
400
enter the number
500
the sum is 1500

No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...