A beginner's technique to solve the problem as simply as possible, so we've this program that uses only a single while loop to calculate power of a function, the arguments base and power of which are entered by the user on prompt. The code for this approach looks like as below
#include<stdio.h> int main(){ unsigned int x,y,i=1,power=1; printf("Enter Value of Variable x (base): "); scanf("%u",&x); printf("Enter Value of Variable y (power): "); scanf("%u",&y); while (i<=y){ power *= x; i++; } printf("Result (x^y=) : %d",power); }
This program when built on Windows 8, runs like as below
To play safe we verify our obtained result with one we've calculated from a standard calculator.
Advanced Method : Using Recursion
Recursion is a powerful phenomenon that can be used to intelligently solve the most complex problems using simplest lines of code. Translating above program in the language of recursion, we define a function named unsigned int calculatePower(int base, int power) that receives base and power as arguments and returns the calculated power. We only define the function definition here
unsigned int calculatePower(int base, int power){ if (power == 0) return 1; else{ return base * calculate(base, power-1); } }
Our recursive function has a base case defined at power=1 and uses this to evaluate greater powers to their simpler and smaller parts, until it has reached the simplest level (the base case). One common error found in recursions is invalid base case, that doesn't produce a syntax error, but does result in an inaccurate result (logical error). It is important to note that the base case returns 1. Had it been return base; in place of return 1; in above program, we'd end up getting result power one greater than desired value. One way to prevent such errors is to first develop the program for simplest problem and then expanding it to accomodate more complex problems once you reach a good enough solution.
No comments:
Post a Comment