Today we shall learn how to find the sum of digits of a given number using classes.Here we get the input a number for the user.Then we shall compute the sum of digits by grabbing each digit of the given number.For eg: if the given number is 143 then sum of digits in computed by 1+4+3=8.We get a doubt,how can we get the digits of given number.By dividing a number by 10 we get the last digit of it as remainder.For eg: 143/10 will give 3 has remainder.In this way we can get each and every digit of the given number.Now we shall write the code for it.
#include<iostream.h> #include<conio.h> class sumofdigits { public: int n,r,result; void sum(); }; void sumofdigits :: sum() { result=0; while(n>0) { r=n%10; n=n/10; result=result+r; } cout<<"Sum of digits of given number is:"<<result; } void main() { clrscr(); sumofdigits ob; cout<<"Enter a number:"; cin>>ob.n; ob.sum(); getch(); }
Output:
You can download the code:download