ฟังก์ชันกำลังคำนวณโดยใช้คูณหาร เช่น 5n คือ 5*5*5… n ครั้ง สำหรับฟังก์ชันนี้ ในการทำงานอย่างถูกต้องโดยไม่ต้องใช้ตัวดำเนินการ multiplication(*) และ division(/) เราจะใช้การวนซ้ำซ้อนที่เพิ่มตัวเลข n จำนวนครั้ง
ตัวอย่าง
#include <iostream>
using namespace std;
int main() {
int a= 4 , b = 2;
if (b == 0)
cout<<"The answer is"<<1;
int answer = a;
int increment = a;
int i, j;
for(i = 1; i < b; i++) {
for(j = 1; j < a; j++) {
answer += increment;
}
increment = answer;
}
cout<<"The answer is "<<answer;
return 0;
} ผลลัพธ์
The answer is 16