C# Program - Power of a Number


Advertisements

If power (or exponential) of number indicates how many the number is multiplied by itself to get the final number. For example:

$$x$$ raised to the power $$2$$ = $$x^2 = x*x$$

$$x$$ raised to the power $$3$$ = $$x^3 = x*x*x$$

Example: Using conditional statement

In the below example, a method called Power() is created to calculate power of a number. It uses while loop to achieve this. This method can be used to calculate the power of a number where power should be a non-negative integer.

using System;

namespace MyApplication { 
  class MyProgram {
    static void Power(double x, int n) {
      double finalnum = 1;
      int n1 = n;
      while(n1 > 0){
        finalnum = finalnum * x;
        n1--;
      }
      Console.WriteLine(x + " raised to the power " + n + " = " + finalnum);
    }  

    static void Main(string[] args) {
      Power(3, 5);
      Power(5, 0);
      Power(6, 2);
    }
  }
}

Output

3.0 raised to the power 5 = 243.0
5.0 raised to the power 0 = 1.0
6.0 raised to the power 2 = 36.0

Example: Using pow() method of C# Math class

The pow() method of C# Math class can also be used to calculate power of a number. It can be used to calculate $$x^n$$ for any value of n (n can be negative or fraction).

using System;

namespace MyApplication { 
  class MyProgram {
    static void Main(string[] args) {
      double x = 3, y = 5, z = 6;
      double a = 5, b = 0, c = 2;

      Console.WriteLine(x + " raised to the power " + a + " = " + Math.Pow(x, a));
      Console.WriteLine(y + " raised to the power " + b + " = " + Math.Pow(y, b));
      Console.WriteLine(z + " raised to the power " + c + " = " + Math.Pow(z, c));
    }
  }
}

Output

3.0 raised to the power 5.0 = 243.0
5.0 raised to the power 0.0 = 1.0
6.0 raised to the power 2.0 = 36.0

Advertisements