การคูณ a × b คือการบวก a จำนวน b ครั้ง
ตัวอย่าง: 5×4=20, 7×8=56, 9×9=81
วิธี 1: ใช้ตัวดำเนินการ *
#include <iostream>
using namespace std;
int main() {
int a = 6, b = 8;
cout << "Product of " << a << " and " << b << " is " << a*b << endl;
return 0;
}
ผลลัพธ์
Product of 6 and 8 is 48
อธิบาย
cout<<"Product of "<<a<<" and "<<b<<" is "<<a*b<<endl;
วิธี 2: ไม่ใช้ * (ใช้ loop บวกซ้ำ)
#include <iostream>
using namespace std;
int main() {
int a = 7, b = 8, product = 0;
for(int i=1; i<=b; i++)
product = product + a;
cout << "The product of " << a << " and " << b << " is " << product << endl;
return 0;
}
ผลลัพธ์
The product of 7 and 8 is 56
อธิบาย
for(int i=1; i<=b; i++)
product = product + a;
for loop บวก a จำนวน b ครั้ง = a×b แสดงผล