การบวกเป็นดำเนินการเลขคณิตพื้นฐาน โปรแกรมนี้บวกเลข 2 จำนวนและแสดงผลรวม
วิธีที่ 1: ใช้ตัวแปรธรรมดา
#include <iostream>
using namespace std;
int main() {
int num1 = 15, num2 = 10, sum;
sum = num1 + num2;
cout << "Sum of " << num1 << " and " << num2 << " is " << sum;
return 0;
}
ผลลัพธ์
Sum of 15 and 10 is 25
วิธีที่ 2: ใช้ Array
#include <iostream>
using namespace std;
int main() {
int a[3];
a[0] = 7;
a[1] = 5;
a[2] = a[0] + a[1];
cout << "Sum of " << a[0] << " and " << a[1] << " is " << a[2];
return 0;
}
ผลลัพธ์
Sum of 7 and 5 is 12
วิธีที่ 2 เก็บตัวเลขและผลรวมในอาร์เรย์: index 0, 1 สำหรับตัวเลข index 2 สำหรับผลรวม