write your own pow function in c. The C library function double pow(double m, double n) returns m raised to the power of n i.e. mn. Without using pow function we have to write code to find m to the power n.This is a common interview question.

write your own pow function in c

pow function recursive implementation without using * operator

#include<stdio.h>

void mnpow (int k, int m, int n);
int count = 0;

int main ()
{
   int m = 2;
   int n = 3;
   printf ("power of %d to %d is ", m, n);
  
   mnpow (0, m, n);
  
   // print ans
   printf ("%d\n", count);

  return 0;
}

void mnpow (int k, int m, int n)
{
  int i = 0;
  if (k == n)
  {
      count++;
      return;
  }
  for (i = 0; i < m; i++)
  {
      mnpow (k + 1, m, n);
  }
}

How it works

Execution flow of the program.

write your own pow function in c



Related Contents to follow