Home Tutorial Java Core Find sum of the squares of Array elements

 
 

Share on Google+Share on Google+
Find sum of the squares of Array elements
Posted on: August 2, 2010 at 12:00 AM
Advertisement
In this section, you will learn how to compute the sum of the squares of the array elements.

Find sum of the squares of Array elements

In this section, you will learn how to compute the sum of the squares of the array elements. For this, we have allowed the user to enter 5 numbers, to be stored into the array. Then we have initialized another array in order to store the square of these array elements. The elements of this array is then added and stored into the variable 'sum' that will display the sum of the squares of Array elements.

Here is the code:

import java.util.*;

class Compute {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.println("Enter 5 numbers: ");
		int num[] = new int[5];
		int sq[] = new int[5];
		int sum = 0;
		for (int i = 0; i < num.length; i++) {
			num[i] = input.nextInt();
			sq[i] = num[i] * num[i];
			sum += sq[i];
		}
		System.out.println("Sum of the square of numbers: " + sum);
	}
}

Output:

Enter 5 numbers:
1
2
3
4
5
Sum of the square of numbers: 55
Advertisement

Related Tags for Find sum of the squares of Array elements:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 2, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com