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
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.");
}
}
}
}
Comments
Leave a comment