Answer to Question #272282 in C# for chi

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


1
Expert's answer
2021-11-29T00:00:41-0500
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;
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS