Advertisement
skb50bd

[pow] Calculating Exponent Result (Iterative and Recursive)

Mar 29th, 2016
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.66 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int recursivePower(int a, int n) {
  5.     return n ? a * recursivePower(a, n - 1) : 1 ; //If n = 0, returns 1; otherwise calls itself with one less power
  6. }
  7.  
  8. int iterativePower(int a, int n) {
  9.     int result = 1;
  10.     for (int i = 0; i < n; i++) //multiplies 'a' n times. thus, a * a * a = a^3
  11.         result *= a;
  12.     return result;
  13. }
  14.  
  15. int main() {
  16.     int A, N;
  17.  
  18.     cout << "Enter an Integer: ";
  19.     cin >> A;
  20.     cout << "Enter the exponent: ";
  21.     cin >> N;
  22.  
  23.     cout << "Recursive Power: " << recursivePower(A, N) << endl;
  24.     cout << "Iterative Power: " << iterativePower(A, N) << endl;
  25.  
  26.     return 0;
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement