answersLogoWhite

0


Best Answer

The following function will sum the digits in any positive number.

unsigned int sum_digits(unsigned int num, unsigned int base=10)

{

sum=0;

if(base>1) // base must be 2 or higher

{

while(num)

{

sum+=num%base; // add least significant digit to sum

num/=base; // shift right by base

}

}

return(sum);

}

User Avatar

Wiki User

10y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

9y ago

There is a far easier way to implement the required functionality than using inheritance. However, to answer the question, here's one possible solution that makes use of inheritance:

#include<iostream>

#include<iomanip>

#include<random>

#include<time.h>

// In order to make use of inheritance we need a common base class.

// Although the underlying datatype is an integral, we cannot inherit from an integral,

// therefore we need to embed the integral in the base class, and provide operators

// that allow the class to function as if it were an integral. Only the bare minimum

// implementation required to achieve the goal is provided.

class integral_t

{

friend std::ostream& operator<< (std::ostream&, const integral_t&);

protected:

unsigned m_number;

public: integral_t (const unsigned number) : m_number (number) {} integral_t (const integral_t& object) : m_number (object.m_number) {}

integral_t& operator/= (const unsigned number) { m_number /= number; return *this; }

integral_t& operator%= (const unsigned number) { m_number %= number; return *this; }

// Virtual conversion operator required to provide specialised functionality

// for the output stream insertion operator (overloaded friend function).

virtual operator unsigned () const { return m_number; }

};

// overloaded friend function to allow insertion into an output stream

std::ostream& operator<< (std::ostream& os, const integral_t& obj)

{

// call virtual conversion operator to ensure most-specialised behaviour.

os << (unsigned) obj;

return os;

}

// The reverse class inherits from the integral base class, overloading the virtual

// unsigned conversion operator to reverse the digits of the underlying integral.

class reverse_t : public integral_t

{

public:

reverse_t (const unsigned number) : integral_t (number) {}

reverse_t (const integral_t& object) : integral_t (object) {}

virtual operator unsigned () const {

unsigned result = 0;

unsigned number = m_number;

do {

result *= 10;

result += number % 10;

} while (number /= 10);

return result;

}

};

// The sum class inherits from the integral base class, overloading the virtual

// unsigned conversion operator to sum the digits of the underlying integral.

class sum_t : public integral_t

{

public:

sum_t (const unsigned number) : integral_t (number) {}

sum_t (const integral_t& object) : integral_t (object) {}

virtual operator unsigned () const {

unsigned result = 0;

unsigned number = m_number;

do {

result += number % 10;

} while (number /= 10);

return result;

}

};

// The main function exercises all three classes.

int main()

{

using std::cout;

using std::endl;

using std::setw;

// pseudo-random number generator

std::default_random_engine generator;

generator.seed ((unsigned) time (NULL));

std::uniform_int_distribution<unsigned> distribution (1000, 9999);

// generate ten 4-digit numbers at random

for (unsigned count = 0; count < 10; ++count)

{

// Instantiate an integral object.

integral_t num = distribution (generator);

// Instantiate a sum object from the integral.

sum_t sum = num;

// Instantiate a reverse object from the integral.

reverse_t rev = num;

// Print all three objects.

cout << "Number:" << setw(5) << num <<

"\tSum of digits: " << setw(3) << sum <<

"\tReversed digits: " << setw(5) << rev << endl;

}

}

Example output:

Number: 5746 Sum of digits: 22 Reversed digits: 6475

Number: 8356 Sum of digits: 22 Reversed digits: 6538

Number: 4307 Sum of digits: 14 Reversed digits: 7034

Number: 8062 Sum of digits: 16 Reversed digits: 2608

Number: 6162 Sum of digits: 15 Reversed digits: 2616

Number: 1167 Sum of digits: 15 Reversed digits: 7611

Number: 5025 Sum of digits: 12 Reversed digits: 5205

Number: 4646 Sum of digits: 20 Reversed digits: 6464

Number: 2962 Sum of digits: 19 Reversed digits: 2692

Number: 1703 Sum of digits: 11 Reversed digits: 3071

A far better solution would be to use two simple functions:

unsigned sum_digits (unsigned number) {

unsigned result = 0;

do {

result += number % 10;

} while (number /= 10);

return result;

}

unsigned reverse_digits (unsigned number) {

unsigned result = 0;

do {

result *= 10;

result += number % 10;

} while (number /= 10);

return result;

}

As you can see, the only difference between these two functions is that the reverse_digits function includes one additional statement, result *= 10;. Although inheritance is intended to avoid code duplication, if you examine the code carefully you will see that they are not in fact duplicates. They are entirely different algorithms because the difference is within an iterative loop, and it's just not possible to optimise away the difference without introducing unnecessary complexity and inefficiency.

If you examine the classes again, you will find that both derivatives contain almost identical implementations to those shown above within each of their virtual conversion overloads, so inheritance offers no practical advantage over the functions. However, we've actually done far worse because we've introduced duplicate code that is already built-in to C++ itself! That is, the integral_t type is not providing any functionality that isn't already built-in (everything it does we can already achieve with a primitive unsigned int). The sole reason for having it was simply to enable an inheritance system that was never required in the first place.

When writing programs, regardless of the language, we must always strive for the simplest solutions to every problem we encounter, using the most efficient algorithms available, or redesigning existing algorithms to make them more efficient. Adding layers of complexity unnecessarily is simply an exercise in futility -- and a complete waste of time (and money!). Just because it can be done, doesn't mean it should be done, not when there's a better, simpler, more efficient method already available.

This answer is:
User Avatar

User Avatar

Wiki User

10y ago

There are basically two methods to do that. One is to convert the number to a string (text), extract the individual digits, convert them back to numeric, and add them. The other method, which does not involve string manipulations, is to repeatedly divide by 10 - the remainder is the digit you want. For example, if your number is 123, then if you divide by 10 you get a remainder of 3 (this is the digit you need), and the division itself gives you a 12 (copy this back to your number, to repeat the loop).

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: Write a program to print sum of the digits in the given number?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Related questions

How to write A Java program to print number of digits in a given number?

One way to do this is to convert the number to a String, then use the corresponding String method to find out the length of the String.


How can you generate a palindrome from a given number?

You write the number and then follow it with the digits in reverse order.


Write a pseudo code to find the sum of digits of a given number reducing them to a single digit?

5


Write a c program to add the digits of a given no?

THIS IS ONLY FOR UPTO A FIVE DIGIT NO. BY ROHAN ARORA#include#includevoid main(){int a,n,s,sum=0;clrscr();printf("Enter the number between 1 to 5 digits\n");scanf("%d",&a);while(a!=0){n=a%10;sum=sum+n;a=a/10;}printf("The sum of digits of the given numberis %d",sum);getch();}


Write a c program to find given number is prime or not?

Yes, do write, or if you're too lazy to your homework, use google.


How many significant digits are in for this number 3.008?

All four of the digits given are significant digits.


Could you write a assembly language program in tasm To check whether a given number present in a sequence of given memory location containing the string to be checked in 8086?

8086 assembly language program to check wether given number is perfect or not


Include zeros in 2.25 million?

Million is the name given to a number with 7 digits in front of the decimal place. In order to write out any number take the number you are given and and move the decimal place to the right until you have 7 digits in front of the decimal. add zeros to the end until it has 7 digits in front of the decimal place. So 2.25 million would be 2,250,000.


If a number with two digits is equal to four times the sum of its digits the number formed by reversing the order of the digits is 27 greater than the given number what is the number?

36


What is the smallest 5 digits odd number that can be formed with given digits 45083?

03458


Is a number with two digits is equal to four times the sum of its digits the number formed by reversing the order ofthe digits is 27 greater than the given number what is the number?

The number is 36.


Write a C program to extract a given word from a file?

program to extract a given word from a file