c-sharp
  1. c-sharp-program-to-calculate-the-power-of-a-number

Program to Calculate the Power of a Number - (C# Basic Programs)

Calculating the power of a number is a common programming exercise that involves raising a base number to an exponent. In this tutorial, we will discuss a program to calculate the power of a number using C# programming language.

Syntax

The syntax for calculating the power of a number in C# is as follows:

Math.Pow(base, exponent)

The Math.Pow() method raises the base number to the exponent power.

Example

using System;

class Program {
    static void Main(string[] args) {

        double baseNum, exponent, result;
        Console.Write("Enter the base number: ");
        baseNum = double.Parse(Console.ReadLine());

        Console.Write("Enter the exponent : ");
        exponent = double.Parse(Console.ReadLine());

        result = Math.Pow(baseNum, exponent);
        Console.WriteLine("{0}^{1} = {2}", baseNum, exponent, result);

        Console.ReadKey();
    }
}

Output:

Enter the base number: 2
Enter the exponent : 3
2^3 = 8

Explanation

The program begins by prompting the user to enter a base number and an exponent. The double.Parse() method is used to convert the user input from a string to a numeric value.

The Math.Pow() method is then used to calculate the result. The baseNum is raised to the power of exponent by passing them as arguments to the Math.Pow() method. The result is stored in the result variable.

Finally, the result is displayed using Console.WriteLine(). The {0}, {1}, and {2} are called placeholders that correspond to the baseNum, exponent, and result variables respectively.

Use

Calculating the power of a number is a common operation in many mathematical and scientific applications. Being able to write a program to calculate the power of a number is a fundamental skill for any programmer, and it can be used in a wide range of programming projects.

Summary

In this tutorial, we have discussed a program to calculate the power of a number using C# programming language. We have seen the syntax, example, explanation, and use of calculating the power of a number in C#. By practicing this program, programmers can improve their problem-solving skills and become better equipped to tackle complex coding challenges.

Published on: