Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C# Sharp Exercises: Find sum of squares of elements of a given array of numbers

C# Sharp Basic: Exercise-78 with Solution

Write a C# Sharp program to find sum of squares of elements of a given array of integers.

Sample Solution:

C# Sharp Code:

using System;
using System.Linq;
namespace exercises
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] nums = { 1, 2, 3 };
            Console.WriteLine("Sum of squares of elements of the said array: " + test(nums));
            int[] nums1 = { -2, 0, 3, 4 };
            Console.WriteLine("Sum of squares of elements of the said array: " + test(nums1));
        }
        public static int test(int[] nums)
        {
            return nums.Sum(n => n * n);
        }
    }
}

Sample Output:

Sum of squares of elements of the said array: 14
Sum of squares of elements of the said array: 29

Flowchart:

Flowchart: C# Sharp Exercises - Find sum of squares of elements of a given array of numbers.

Sample Solution-1:

C# Sharp Code:

using System;
using System.Linq;
namespace exercises
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] nums = { 1, 2, 3 };
            Console.WriteLine("Sum of squares of elements of the said array: " + test(nums));
            int[] nums1 = { -2, 0, 3, 4 };
            Console.WriteLine("Sum of squares of elements of the said array: " + test(nums1));
        }
        public static int test(int[] nums)
        {
            int sqares_sum = 0;
            for (int i = 0; i < nums.Length; i++)
            {
                sqares_sum = sqares_sum + (int)Math.Pow(nums[i], 2);
            }
            return (int)sqares_sum;
        }
    }
}

Sample Output:

Sum of squares of elements of the said array: 14
Sum of squares of elements of the said array: 29

Flowchart:

Flowchart: C# Sharp Exercises - Find sum of squares of elements of a given array of numbers.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a C# Sharp program to check whether a given word is plural or not.
Next: Write a C# Sharp program to convert an integer to string and a string to an integer.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.