C program to calculate the Power Using Recursion

@codevarsity
 · 
2.1k views
 · 

A simple C program to calculate the power of a number using recursion.

Related Topics

Structures  Functions 

Code

#include <stdio.h>

int power(int n1, int n2);

int main()
{
    int base, powerRaised, result;

    printf("Enter base number: ");
    scanf("%d",&base);

    printf("Enter power number(positive integer): ");
    scanf("%d",&powerRaised);

    result = power(base, powerRaised);

    printf("%d^%d = %d", base, powerRaised, result);
    return 0;
}

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

Output

Enter base number: 3
Enter power number(positive integer): 4
3^4 = 81

Explanation

C Program to Add Two Complex Numbers by Passing Structure to a Function

In the structure complex, we are using float datatype for variables, real and imag since our concern is to add any two complex numbers with a possible fractional value.

In the main() function, the real part and the imaginary part of the complex numbers are taken separtely using scanf().

The structures n1 and n2 are passed as an argument of function add(). The function computes the sum and returns the structure variable temp to the main() function.

The final result is printed using printf() throught the main() function.

Tags

#struct  #return 

Comments