w3resource logo


C# Sharp Programming Exercises

C# Sharp Exercises: Calculate power of any number

Secondary Nav

C# Sharp Recursion : Exercise-15 with Solution

Write a program in C# Sharp to calculate the power of any number using recursion.
Test Data :
Input the base value : 5
Input the exponent : 3
Expected Output
:
The value of 5 to the power of 3 is : 125

C# Sharp Code:

using System;
public class RecExercise15
{
 
 public static void Main()
	{
    int bNum,pwr;
    int result;
    Console.Write("\n\n Recursion : Calculate power of any number :\n");
	Console.Write("------------------------------------------------\n");	
     
    Console.Write(" Input the base  value : ");
    bNum = Convert.ToInt32(Console.ReadLine());
     
    Console.Write(" Input the exponent : ");
    pwr = Convert.ToInt32(Console.ReadLine());
     
    result=CalcuOfPower(bNum,pwr);//called the function CalcuOfPower
     
    Console.Write(" The value of {0} to the power of {1} is : {2} \n\n",bNum,pwr,result);
	}

public static int CalcuOfPower( int x,int y)
 {
  if (y == 0)
   return 1;
  else
   return x * CalcuOfPower( x, y - 1 );
 }
}

C# Sharp Practice online:


using System;
public class RecExercise15
{
 
 public static void Main()
	{
    int bNum,pwr;
    int result;
    Console.Write("\n\n Recursion : Calculate power of any number :\n");
	Console.Write("------------------------------------------------\n");	
     
    Console.Write(" Input the base  value : ");
    bNum = Convert.ToInt32(Console.ReadLine());
     
    Console.Write(" Input the exponent : ");
    pwr = Convert.ToInt32(Console.ReadLine());
     
    result=CalcuOfPower(bNum,pwr);//called the function CalcuOfPower
     
    Console.Write(" The value of {0} to the power of {1} is : {2} \n\n",bNum,pwr,result);
	}

public static int CalcuOfPower( int x,int y)
 {
  if (y == 0)
   return 1;
  else
   return x * CalcuOfPower( x, y - 1 );
 }
}

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program