Sum of the powers from 1 to n

3739 views c#
0

How to create 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 1^1 + 2^2 + 3^3 + 4^4 1 + 4 + 27 + 256 = 288

Using for loop..

I try answer but I didn't get it..

answered question

If you show us what you tried we can help you better

What's giving you a hard time? The input? The computation? The output? Setting up Visual Studio?

1 Answer

13

If you are willing to use LINQ, then one option is:

var sum = Enumerable.Range(1, 4) // replace `4` with n or whatever you want
    .Sum(z => Math.Pow(z, z));

Enumerable.Range will get the first four numbers, and Math.Pow will do the 1^1 and 2^2 etc. Sum will add all of them up.

If you must use a loop:

double sum = 0;

for (int i = 1; i <= 4; i++) // replace `4` with n or whatever you want
{
    sum += Math.Pow(i, i);
}

which does the exact same thing, in a more verbose way.

posted this

Have an answer?

JD

Please login first before posting an answer.