The Program in C# Program to Find Sum of Squares of Elements of Given array is given below:
using System;
namespace SumOfSquares
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Codeauri Family,enter the number of elements in the array here to find the sume of squares of elements in array");
int n = int.Parse(Console.ReadLine());
int[] numbers = new int[n];
Console.WriteLine("Well,enter the elements of the array: ");
for (int i = 0; i < n; i++)
{
numbers[i] = int.Parse(Console.ReadLine());
}
int sum = 0;
foreach (int num in numbers)
{
sum += num * num;
}
Console.WriteLine("Okay,the sum of squares of the elements in the array is: " + sum);
}
}
}
Output:
Hello Codeauri Family,enter the number of elements in the array here to find the sume of squares of elements in array
2
Well,enter the elements of the array:
199
200
Okay,the sum of squares of the elements in the array is: 79601
Pro-Tips💡
Here are the step by step execution of above program:
- The first line of code
using System;
specifies the namespace that contains the classes needed for the program. - Next, the program is defined as belonging to the
SumOfSquares
namespace. - Within the namespace, a class called
Program
is defined. TheMain
method of this class is the starting point of the program. - The
Main
method first prints a message asking the user to enter the number of elements in the array, and stores the user’s input in the integer variablen
. - An array
numbers
is declared withn
elements, usingint[] numbers = new int[n];
. - A
for
loop is used to read the elements of the array from the user, usingint.Parse(Console.ReadLine())
to parse the input string as an integer. The elements are stored in thenumbers
array. - A
foreach
loop is used to iterate through the elements in thenumbers
array, computing the square of each element usingnum * num
and adding it to thesum
variable. - Finally, the result of the computation is printed to the console using
Console.WriteLine("Okay,the sum of squares of the elements in the array is: " + sum);
. Thesum
variable is converted to a string using string concatenation with an empty string.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.