Monday, April 22, 2019

Recursion 3 : Compute a^n

  • Problem Description

    Write a program to compute a^n (a power n) using recursion.

    Input and Output Format:


    Input consists of 2 integers.

    Refer sample input and output for formatting specifications.

    All text in bold corresponds to input and the rest corresponds to output.
  • Test Case 1

    Input (stdin)
    2

    8

    Expected Output
    The value of 2 power 8 is 256
  • Test Case 2

    Input (stdin)
    1

    2

    Expected Output
    The value of 1 power 2 is 1
Solution

#include <stdio.h>

int power(int n1, int n2);

int main()
{
    int base, powerRaised, result;
    scanf("%d",&base);
    scanf("%d",&powerRaised);

    result = power(base, powerRaised);

    printf("The value of %d power %d is %d", base, powerRaised, result);
    return 0;
}

int power(int base, int powerRaised)
{
    if (powerRaised != 0)
        return (base*power(base, powerRaised-1));
    else
        return 1;
}

No comments:

Post a Comment

Parity

Problem Description Ram and Sita playing the parity game. Two types of parity are there. One is odd parity and next is even parity. Ram will...