iLearnSlow
iLearnSlow

Reputation: 103

Using Lambda Expression To Code An Exponent In C++

How can I write an "X to the power of k" procedure in C++? (k is a positive integer)

I did the same thing in python, and it was a breeze, but in C++, I don't even know where to begin.

Upvotes: 0

Views: 708

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

How can I write an "X to the power of k" procedure in C++? (k is a positive integer)

Write a short loop in a function like

int pow(int X, int k) {
    int result = 1;
    for(int i = 0; i < k; ++i) result *= X;
    return result;
}

It's easy to express this in a lambda as well:

auto pow = [] (int X, int k) { 
     int result = 1;
     for(int i = 0; i < k; ++i) result *= X;
     return result; 
};

cout << pow(5,3);

See a working sample please.

Upvotes: 2

Mantas Daškevičius
Mantas Daškevičius

Reputation: 324

Ummm, maby try this:

#include <iostream>
#include<cmath> //adds math functions: power, square root etc.

using namespace std;

int main(){

  int x;
  int k;

  cin >> x;
  cin >> k;

 x = pow(x, k);
 cout << "\nX to the power of k: " << x << endl << endl;

  return 0;
}

Upvotes: 0

Related Questions