MVC ASP.NET C# SQL Server WCF Written Test HR Round Subscribe C# Videos C# Programs Buy DVD

Power function in C#

Write a Power() function. The function should take 2 parameters - Base and Exponent. The function should return back the result of "Base raised to the power of exponent". Let me give an example.

When the Power() method is called using parameters 3 and 4 as shown below. The value of 3 to the power of 4 should be returned back, i.e 81.

So in short Power(3,4) should return 81. So in this example 3 is the base and 4 is the exponent.


using System;


namespace SamplePrograms
{
    class PowerFunction
    {
        public static void Main()
        {
            // Prompt the user to enter base
            Console.WriteLine("Enter your base");
            int Base = Convert.ToInt32(Console.ReadLine());


            // Prompt the user to enter exponent
            Console.WriteLine("Enter your exponent");
            int Exponent = Convert.ToInt32(Console.ReadLine());


            // Call the power method passing it Base and Exponent
            int Result = Power(Base, Exponent);


            // In System.Math class there is Pow() static method which is
            // very similar to the static Power() method we implemented
            // double Result = System.Math.Pow(Base, Exponent);
            
            // Print the result
            Console.WriteLine("Result = {0}", Result);
        }


        public static int Power(int Base, int Exponent)
        {
            // Declare a variable to hold the result
            int Result = 1;


            // Multiply the Base number with itself, for 
            // exponent number of times
            for (int i = 1; i <= Exponent; i++)
            {
                Result = Result * Base;
            }


            //return the Result
            return Result;
        }
    }
}

1 comment:

  1. //To Get the Power of a number
    int Base = 1;
    Console.WriteLine("Please enter the Base:");
    Base = Convert.ToInt32(Console.ReadLine());

    int Exponent = 1;
    Console.WriteLine("Please enter the Exponent:");
    Exponent = Convert.ToInt32(Console.ReadLine());
    int Result = 1;
    for (int i = 1; i <= Exponent; i++)
    {
    Result = Result * Base;
    }
    Console.WriteLine(Base + " raised to the power of " + Exponent + " = " + Result);
    Console.ReadKey();

    ReplyDelete