Q: Input an integer number. Find and show the sum of digits of given number.
For example, if given number is 123 then answer will be Sum of digits = 6
because 1+2+3 = 6.
Input Number Add its digits C++ Program |
The Actual C++ Code of Add Digits of a given number Program
/*
Program to input a number, then display sum of its digits.
(c) Www.EasyCppProgramming.Blogspot.Com
*/
#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
int num, temp, sum=0, r, q;
clrscr();
cout<<"Enter a number to add its Digits=";
cin>>num;
temp = num;
while ( temp>0 )
{
q = temp/10;
r = temp % 10;
sum = sum + r;
temp = q;
}
cout<<"\n The sum of digits of given number "<<num<<" = "<<sum;
getch();
}
Write C++ Program to find sum of digits of given number |
The Working of C++ Code of Add Digits of a given number Program
This program is of reverse number logic.1. We will divide 123 by 10 and get quotient=12, r = 3
2. add r=3 into sum, so sum=3
3. Now put q =12 into dividend number
4. so divide 12 by 10, quotient=1 and remainder r=2.
5. Add r=2 into sum, so sum will become 5.
6. now put q=1 into dividend number
7. Now divide 1 by 10, quotient=0 and r=1.
8. so add r=1 into sum, and sum becomes 6
9. now put quotient=0 into dividend number called temp variable
10. so that while loop test condition while (temp>0) becomes false and loop terminates.
11. Therefore display the answer sum of digits of number 123 = 6
/*
Program to input a number, then display sum of its digits.
(c) Www.EasyCppProgramming.Blogspot.Com
*/
#include<iostream.h> // include header files
#include<conio.h>
void main()
{
int num, temp, sum=0, r, q;
clrscr();
cout<<"Enter a number to add its Digits=";
cin>>num; // input number
temp = num; // copy number into temp variable
while ( temp>0 ) // loop while temp is greater than zero
{
q = temp/10; // calculate quotient = temp number / 10, if num is 123 then q=12
r = temp % 10; // calculate remainder r = 123 % 10, r = 3
sum = sum + r; // sum = 0 + 3; so last digit 3 of 123 is added in sum variable
temp = q; // set next time dividend temp=12
}
cout<<"\n The sum of digits of given number "<<num<<" = "<<sum; //sum=6
getch();
}
0 comments:
Post a Comment
We Love To Hear From You!