Answer to Question #346283 in C for Hima

Question #346283

The function Power, which raises the integer number x to the power n, can be defined recursively as follows: Power(x, n) = 1 for n = 0 Power(x, n) = x * Power(x, n-1) for n > 0 (i) Using the above definition write the recursive function Power(x, n) in C. (ii) Rewrite the recursive function Power(x, n) in an iterative form. (iii) Write the main function and test the above written functions. Note: You can write one program and test the functions or you may write two separate programs for each part (i) and (ii).


1
Expert's answer
2022-05-30T08:17:31-0400
#include <stdio.h>
#include <stdlib.h>
int Power(int x, int n)
{
	if (n == 0)
		return 1;
	else if (n > 0)
		return x * Power1(x, n - 1);
	else
		return 1;
}
int main()
{
	int x;
	int n;
	printf("Please enter a number: ");
	scanf_s("%d", &x);
	printf("Please enter a power: ");
	scanf_s("%d", &n);
	printf("recursive function Power(x, n) %ld \n", Power(x, n));
	return 0;
}


#include <stdio.h>
#include <stdlib.h>
int Power(int x, int n)
{
	long int result = x;
	int i;
	if (n == 0)
		return 1;
	else if (n > 0)
	{
		for (i = 0; i < n - 1; i++)
			result = result * x;
		return result;
	}
	else
		return 1;
}
int main()
{
	int x;
	int n;
	printf("Please enter a number: ");
	scanf_s("%d", &x);
	printf("Please enter a power: ");
	scanf_s("%d", &n);
	printf("iterative function Power(x, n) %ld \n", Power(x, n));
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS