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
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:
Comments
Leave a comment