Problem:
Design an algorithm to compute the sum of the squares of n numbers.
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 square of the number read to the most recent sum.
4. Write out sum of squares of n numbers.
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class SumOfSquaresOfNNumbers {
List<Integer> numbers = new ArrayList<Integer>();
public static void main(String[] args) {
SumOfSquaresOfNNumbers sumOfSquaresOfNNumbers = new SumOfSquaresOfNNumbers();
sumOfSquaresOfNNumbers.getTheNumbers();
sumOfSquaresOfNNumbers.findTheSumOfSquares();
}
private void getTheNumbers(){
System.out.println("how many numbers you want to find out the squares sum");
Scanner s = new Scanner(System.in);
int n = s.nextInt();
for(int i = 0; i< n;i++){
System.out.println("enter the number");
numbers.add(s.nextInt());
}
}
private void findTheSumOfSquares(){
int sum = 0;
for(Integer i: numbers){
sum = sum + (i * i);
}
System.out.println("the sum is: " + sum);
}
}
Output:
how many numbers you want to find out the squares sum
3
enter the number
1
enter the number
3
enter the number
5
the sum is: 35
Design an algorithm to compute the sum of the squares of n numbers.
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 square of the number read to the most recent sum.
4. Write out sum of squares of n numbers.
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class SumOfSquaresOfNNumbers {
List<Integer> numbers = new ArrayList<Integer>();
public static void main(String[] args) {
SumOfSquaresOfNNumbers sumOfSquaresOfNNumbers = new SumOfSquaresOfNNumbers();
sumOfSquaresOfNNumbers.getTheNumbers();
sumOfSquaresOfNNumbers.findTheSumOfSquares();
}
private void getTheNumbers(){
System.out.println("how many numbers you want to find out the squares sum");
Scanner s = new Scanner(System.in);
int n = s.nextInt();
for(int i = 0; i< n;i++){
System.out.println("enter the number");
numbers.add(s.nextInt());
}
}
private void findTheSumOfSquares(){
int sum = 0;
for(Integer i: numbers){
sum = sum + (i * i);
}
System.out.println("the sum is: " + sum);
}
}
Output:
how many numbers you want to find out the squares sum
3
enter the number
1
enter the number
3
enter the number
5
the sum is: 35
No comments:
Post a Comment