Write c++program to to accept five digit number and display the sum of digits of entered no.
Answers
Explanation:
« Prev PageNext Page »
C++ Program to Display the Sum of the Digits of a given Number
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
*/
#include<iostream>
using namespace std;
int main()
{
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
$ ./a.out
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.