This C++ Program which gets a number from input and displays the sum of the digits in the given number. The program uses a while loop to go through each and every digit of the given number and adds them up in the loop.
Here is source code of the C++ program which gets a number from input and displays the sum of the digits in the given number. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
* C++ program to Display the Sum of the digits of a given Number
using namespace std;
int val, num, sum = 0;
cout << "Enter the number : ";
cin >> val;
num = val;
while (num != 0)
sum = sum + num % 10;
num = num / 10;
cout << "The sum of the digits of "
<< val << " is " << sum;
$ g++ main.cpp
Enter the number : 12345
The sum of the digits of 12345 is 15
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
If you wish to look at all C++ Programming examples, go to C++ Programs
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1,
- Chapterwise Mock Tests: Chapter 1,
, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry
. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms.
Stay connected with him at LinkedIn
Subscribe to his free Masterclasses at Youtube
& technical discussions at Telegram SanfoundryClasses