Answer to Question #190613 in C# for angelo r reyes

Question #190613

Write a program to scan a number n and then output the sum of the 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-05-07T23:41:55-0400
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;


namespace C_SHARP
{
    class Program
    {
        static void Main(string[] args)
        {
            int n;
            double sum = 0;
            Console.Write("Enter n= ");
            n = int.Parse(Console.ReadLine());
            //1st Solution – using for loop/ 
            for (int i = 1; i <= n; i++)
            {   
                sum += Math.Pow(i,i);
            }
            //show result
            Console.WriteLine("Using for loop");
            Console.WriteLine("The sum of the powers from 1 to {0} = {1}\n",n, sum);
            //2nd Solution – using while loop 
            int j=1;
            sum = 0;
            while (j <= n)
            {
                sum += Math.Pow(j, j);
                j++;
            }
            //show result
            Console.WriteLine("Using while loop");
            Console.WriteLine("The sum of the powers from 1 to {0} = {1}\n", n, sum);
            //3rd Solution- using do while loop 
            j = 1;
            sum = 0;
            do
            {
                sum += Math.Pow(j, j);
                j++;
            } while (j <= n);
            //show result
            Console.WriteLine("Using do while loop");
            Console.WriteLine("The sum of the powers from 1 to {0} = {1}\n", n, sum);


            Console.ReadKey();
        }
    }
}



Example:



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