Answer to Question #271792 in C# for chi

Question #271792

Write a program to scan a number n and then output the sum of he powers from 1 to n.

Thus, if the input is 4, the output should be 288 because:

11 + 22 + 33 + 44 1 + 4 + 27 + 256 = 288


1st Solution – using for loop

2nd Solution – using while loop

3rd Solution-­‐ using do while loop


1
Expert's answer
2021-11-26T07:09:18-0500
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.Write("Enter number n: ");
                string str = Console.ReadLine();
                int n = int.Parse(str);
                int i, sum;

                Console.WriteLine("1st Solution – using for loop");
                sum = 0;
                for (i = 1; i <= n; i++)
                {
                    sum += (int)Math.Pow(i, i);
                }
                Console.WriteLine("the sum of the powers from 1 to n: {0}", sum);

                Console.WriteLine("2nd Solution – using while loop");
                sum = 0;
                i = 0;
                while (++i <= n)
                {
                    sum += (int)Math.Pow(i, i);
                }
                Console.WriteLine("the sum of the powers from 1 to n: {0}", sum);

                Console.WriteLine("3rd Solution - using do while loop");
                sum = 0;
                i = 1;
                do
                {
                    sum += (int)Math.Pow(i, i);
                }
                while (++i <= n);
                Console.WriteLine("the sum of the powers from 1 to n: {0}", sum);
            }
            catch
            {
                Console.WriteLine("Bad number.");
            }
        }
    }
}

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