Question #272282

Write a program to scan a number n and then output the sum of the squares from1 to n. Thus, if the input is 4, the output should be 30 because:12 + 22 + 32 + 42 1 + 4 + 9 + 16 =30

1st Solution – using for loop

2nd Solution – using while loop

3rd Solution-‐ using do while loop

Expert's answer

```
using System;
namespace ConsoleAppSumOfTheSquare
{
class Program
{
static void Main(string[] args)
{
int number, result;
Console.WriteLine("Please enter the positive number");
if(int.TryParse(Console.ReadLine(), out number))
{
if (number < 0)
{
Console.WriteLine("The entered number must be positive.");
}
else
{
result = SumOfTheSquareUsingForLoop(number);
Console.WriteLine($"The result of a calculation using a 'for' loop is {result}.");
result = SumOfTheSquareUsingWhileLoop(number);
Console.WriteLine($"The result of a calculation using a 'while' loop is {result}.");
result = SumOfTheSquareUsingDoWhileLoop(number);
Console.WriteLine($"The result of a calculation using a 'do while' loop is {result}.");
}
}
else
{
Console.WriteLine("The entered value cannot be converted to a number.");
}
Console.ReadKey();
}
static int SumOfTheSquareUsingForLoop(int n)
{
int result = 0;
for (int i = 1; i<=n; i++)
{
result = result + i * i;
}
return result;
}
static int SumOfTheSquareUsingWhileLoop(int n)
{
int result = 0;
int i = 1;
while (i <= n)
{
result = result + i * i;
i++;
}
return result;
}
static int SumOfTheSquareUsingDoWhileLoop(int n)
{
int result = 0;
int i = 1;
if (n > 0)
{
do
{
result = result + i * i;
i++;
}
while (i <= n);
}
return result;
}
}
}
```

Learn more about our help with Assignments: C#

## Comments

## Leave a comment