C++ program to find sum of digits for a given number

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: sumofdigits
You can download the code:download

Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in C++ and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s