นี่คือตัวอย่างการคำนวณผลรวมของตัวเลขในภาษา C++
ตัวอย่าง
#include<iostream>
using namespace std;
int main() {
int x, s = 0;
cout << "Enter the number : ";
cin >> x;
while (x != 0) {
s = s + x % 10;
x = x / 10;
}
cout << "\nThe sum of the digits : "<< s;
} ผลลัพธ์
Enter the number : 236214828 The sum of the digits : 36
ในโปรแกรมข้างต้น ตัวแปร x และ s สองตัวถูกประกาศและ s เริ่มต้นด้วยศูนย์ ผู้ใช้ป้อนหมายเลขและเมื่อตัวเลขไม่เท่ากับศูนย์จะสรุปตัวเลขของตัวเลข
while (x != 0) {
s = s + x % 10;
x = x / 10;
}