473,407 Members | 2,320 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

Sun of digits in a number

Hello, I would like to know how to do this:
Basically when I input a number, such as 123, it should display 6
(1+2+3), and for 666 would be 18. I'm a bit stuck here...

I know it would involve a while loop along that can do this condition:

nd1=num/100%10;
nd2=num/10%10;
nd3=num%10;, etc

And some how add it up. Can anyone help me? Thanks.

Oct 4 '05 #1
25 1706
sn***********@gmail.com wrote:
Hello, I would like to know how to do this:
Basically when I input a number, such as 123, it should display 6
(1+2+3), and for 666 would be 18. I'm a bit stuck here...

I know it would involve a while loop along that can do this condition:

nd1=num/100%10;
nd2=num/10%10;
nd3=num%10;, etc

And some how add it up. Can anyone help me? Thanks.


Well, if you do it only once:

nd = num % 10;
nn = num / 10;

what do you get? What if you take one of those results and keep doing
the same operation with it (instead of 'num')? How many times will you
get to do it? What numbers will you need to add and where?

V
Oct 4 '05 #2
sn***********@gmail.com wrote:
Hello, I would like to know how to do this:
Basically when I input a number, such as 123, it should display 6
(1+2+3), and for 666 would be 18. I'm a bit stuck here...

I know it would involve a while loop along that can do this condition:

nd1=num/100%10;
nd2=num/10%10;
nd3=num%10;, etc

And some how add it up. Can anyone help me? Thanks.

Do it the other way around: take the modulo to get a digit,
then divide by ten, if not zero do it all again.

More than that, I will not offer. Your teacher wants you to do
your own homework.
Oct 4 '05 #3
Who said it was homework? I'm doing this on my spare time because I
want to learn C++. I've already said what I remember, but just
forgetting how to do it. I know I can use a while loop, but I'm not
sure how to set it up after that. Please don't assume things.

Oct 4 '05 #4
sn***********@gmail.com wrote:
Who said it was homework? I'm doing this on my spare time because I
want to learn C++. I've already said what I remember, but just
forgetting how to do it. I know I can use a while loop, but I'm not
sure how to set it up after that. Please don't assume things.


However, this is more something that involves basic math principles
rather than learning C++. If you were learning C++ you could always
move onto a non-math based item to learn while loops and the come back
to it after you had the math concepts down.

Easiest way:
Do it on paper. Find the patterns. Turn the patterns into programming.

You are on the first step, once you finish the second step you can
proceed to the third.

Oct 4 '05 #5
sn***********@gmail.com wrote:
Who said it was homework? I'm doing this on my spare time because I
want to learn C++.
So, are you doing it for a project at work? No? Then it *is* home work.
I've already said what I remember, but just
forgetting how to do it. I know I can use a while loop, but I'm not
sure how to set it up after that.
Set up what? After what?

while (somecondition) {
bodyoftheloop
}

You need to figure out what condition to write and what to put in the body
of the loop (what operation you need repeated).
Please don't assume things.


OK, but just for our information, why not?

V
Oct 4 '05 #6
I'm just your average joe. I know math (I'm taking calculus currently).
There's no reason to flame me, you all think I'm the typical guy who
demands the code. I even stated what I've got so far. I'm just getting
ahead of a later class trying to learn. I never specifically asked for
the code -- but I'm not the guy who quickly just c/ps it in. I'm
learning to, just like all of you have learned from the start. I've
told you how much I know anyways...

I'm pretty sure all of you asked questions just like this when you
began learning. And no, it's not homework -- it's a hobby.

Dictionary defines homework as:
"Work, such as schoolwork or piecework, that is done at home. "

So if I'm at the library doing this, I guess it counts as homework?
Please have some logic towards your answer. I admire you for helping me
at the start though.

Oct 4 '05 #7
sn***********@gmail.com wrote:
I'm pretty sure all of you asked questions just like this when you
began learning. And no, it's not homework -- it's a hobby.


Actually, the question I would have asked would have been the
following:

What's the operator to find the remainder of the a number divided by
another?
What's the operator to add a number to itself?

Asking how defeats the purpose of learning. You may have questions
about the name of a function to do "foo", but asking how to do a
general algorithm is the same as asking for the algorithm itself.

If you have a number, 12353, and you want to add the digits, how do you
do that?

Well, you add 1 + 2 + 3 + 5 + 3.

How do you get the 3? Well, 12353 % 10 gives you 3. How do you get the
5? Well, 1235 % 10 gives you the 5.

How do you turn that into code? Patterns and repeatitions.

Oct 4 '05 #8
^
I know the logic behind it. I'm stuck implementing how to add the
1+2+3+4+5. I know you use the mod to get the digits, but how can you
add them while looping? And adding the variables while they are at it?
I got how to get the number of digits:

while(dig > 0){
count++;
dig = dig/10; }

Kinda stuck there.

Oct 4 '05 #9
Victor Bazarov wrote:
sn***********@gmail.com wrote:
Who said it was homework? I'm doing this on my spare time because I
want to learn C++.


So, are you doing it for a project at work? No? Then it *is* home work.


You are using a definition of home work that (a) you won't find in
dictionaries and that (b) was clearly not the intended meaning of the posts
above starting with "Your teacher wants you to do your own homework."

[snip]
> Please don't assume things.


OK, but just for our information, why not?


Well, you are running an increased risk of patronizing people who do not
strictly deserve it.

On the other hand, you have a point: a news group post usually is very
little to go on, and you just have to make decisions on how to respond.
Best

Kai-Uwe Bux
Oct 4 '05 #10
sn***********@gmail.com wrote:
Who said it was homework? I'm doing this on my spare time because I
want to learn C++.


Then is self-assigned homework, not very different.

--
Salu2
Oct 4 '05 #11
sn***********@gmail.com wrote:
^
I know the logic behind it. I'm stuck implementing how to add the
1+2+3+4+5. I know you use the mod to get the digits, but how can you
add them while looping? And adding the variables while they are at it?
I got how to get the number of digits:

while(dig > 0){
count++;
dig = dig/10; }

Kinda stuck there.


You get the rightmost digit with

dig%10

You add things up with +=

so

total += dig%10;

Put that in the right place in your loop. And drop count++, what does
that do?

john
Oct 4 '05 #12
On Tue, 04 Oct 2005 14:48:22 -0700, snow.carriers wrote:
^
I know the logic behind it. I'm stuck implementing how to add the
1+2+3+4+5. I know you use the mod to get the digits, but how can you
add them while looping? And adding the variables while they are at it?
I got how to get the number of digits:

while(dig > 0){
count++;
dig = dig/10; }

Kinda stuck there.


So how do you add numbers in your head? You don't instantly grok the
entire sum. First you start out with nothing (0). Then you see the 1. Aha!
0 + 1 is 1. Then you see the 2. 1 + 2 is 3. Then you see three. 3 + 3 = 6.
Then you see the four -> 6 + 4 = 10. You *accumulate* the answer...

- Jay
Oct 4 '05 #13
Kai-Uwe Bux wrote:
dictionaries and that (b) was clearly not the intended meaning of the
posts above starting with "Your teacher wants you to do your own
homework."


Many people use the expression: "I teached myself". In that case, maybe the
teacher does not know what he wants.

--
Salu2
Oct 4 '05 #14
Thanks for the obvious.
Anyways this is what I got so far, however for some reason only the
last digit displays.
while (dig > 0) {
dig = dig%10;
total += dig%10;
dig = dig/10;
}

Oct 4 '05 #15

sn***********@gmail.com wrote:
^
I know the logic behind it. I'm stuck implementing how to add the
1+2+3+4+5. I know you use the mod to get the digits, but how can you
add them while looping? And adding the variables while they are at it?
I got how to get the number of digits:

while(dig > 0){
count++;
dig = dig/10; }

Kinda stuck there.


Well, loop one you have sum = 1, loop two you have sum = 1+2. Break it
down you have sum as a moving total with the new mod number as the new
value.

Oct 4 '05 #16
sn***********@gmail.com wrote:
Thanks for the obvious.
Anyways this is what I got so far, however for some reason only the
last digit displays.
while (dig > 0) {
dig = dig%10;
total += dig%10;
dig = dig/10;
}


Lets trace that out, starting with dig = 123, total = 0

dig = dig%10, so now dig = 3
total = dig%10, so now total = 3
dig = dig/10, so now dig = 0
so now the loop exits.

Do you see why it doesn't work? Do you see the mistake? It's hard to
advise because it's hard to know why you thought what you wrote would
work in the first place.

john
Oct 4 '05 #17

snow.carri...@gmail.com wrote:
Thanks for the obvious.
Anyways this is what I got so far, however for some reason only the
last digit displays.
while (dig > 0) {
dig = dig%10;
total += dig%10;
dig = dig/10;
}


What is up with the first line?

Say Digit = 1345

Digit = 1345 % 10 means digit now equals 5.
Total = += 5 % 10, which means total equals 5.
Dig = 5 / 10 which is 0, means Dig = 0 and loop breaks.

Oct 4 '05 #18
How would I do it so that
dig = dig/10
Would be equal to 12?

Oct 4 '05 #19
On Tue, 04 Oct 2005 15:27:44 -0700, snow.carriers wrote:
Thanks for the obvious.
Anyways this is what I got so far, however for some reason only the
last digit displays.
while (dig > 0) {
dig = dig%10; // (1)
total += dig%10; // (2)
dig = dig/10; // (3)
}


Just about. Just don't do the initial mod in the loop (1). You want to add
the mod to the total (2), and then divide by 10 to get the next digit into
low position (3).

- Jay
Oct 4 '05 #20
sn***********@gmail.com wrote:
How would I do it so that
dig = dig/10
Would be equal to 12?


If dig = 123 before then you do

dig = dig/10

dig = 12 afterwards.

The problem with your loop is that dig does not equal 123 by the time
that you reach 'dig = dig/10'. Lets trace it again

start with dig = 123

while (dig > 0) - great this is true

dig = dig % 10 - before dig = 123, afterwards dig = 3 ***WRONG***

total += dig%10 - doesn't change dig

dig = dig / 10 - before dig = 3 (see ***WRONG***), so afterwards dig = 0

There's something very wrong here, do you understand assignment? Do you
understand that a program is a sequence of commands executed one after
another. At the moment you are just not getting it and it's hard to
explain such fundamental concepts.

If you are going to be a programmer you really need to be able to trace
out a four statement loop and be able to understand what it's behaviour is.

john
Oct 4 '05 #21

<sn***********@gmail.com> wrote in message
news:11*********************@g49g2000cwa.googlegro ups.com...
Hello, I would like to know how to do this:
Basically when I input a number, such as 123, it should display 6
(1+2+3), and for 666 would be 18. I'm a bit stuck here...

I know it would involve a while loop along that can do this condition:

nd1=num/100%10;
nd2=num/10%10;
nd3=num%10;, etc

And some how add it up. Can anyone help me? Thanks.


#include <iostream>
#include <numeric>
#include <sstream>
#include <string>

unsigned int sum_digits(int num)
{
std::ostringstream oss;
oss << num;
const std::string s(oss.str());
return std::accumulate(s.begin(), s.end(), 0) - '0' * s.size();
}

int main()
{
std::cout << sum_digits(123) << '\n';
return 0;
}

:-) :-) :-)

-Mike
Oct 5 '05 #22
C'mon, why would you want such a convoluted solution.

It's surely far simpler:

#include <numeric>

struct digit_iterator
{
digit_iterator(int num = 0) : _num(num) { }
int operator* () { return _num % 10; }
digit_iterator& operator++() { _num /= 10; return *this; }
bool operator!=(const digit_iterator& i) { return _num != i._num; }
private: int _num;
};

int sum_digits(int num)
{
return std::accumulate(digit_iterator(num), digit_iterator(), 0);
}

(and yes I'm sure someone will point that digit_iterator isn't a fully
valid input iterator).

Oct 5 '05 #23

wi******@hotmail.com wrote:
C'mon, why would you want such a convoluted solution.

It's surely far simpler:

#include <numeric>

struct digit_iterator
{
digit_iterator(int num = 0) : _num(num) { }
int operator* () { return _num % 10; }
digit_iterator& operator++() { _num /= 10; return *this; }
bool operator!=(const digit_iterator& i) { return _num != i._num; }
private: int _num;
};

int sum_digits(int num)
{
return std::accumulate(digit_iterator(num), digit_iterator(), 0);
}

(and yes I'm sure someone will point that digit_iterator isn't a fully
valid input iterator).


A template metaprogram is the way to go here:

#include <iostream>

template <unsigned int I>
int PrintDigits()
{
PrintDigits<I/10>();
std::cout << I%10;
}

template <>
int PrintDigits<0>() {}

int main()
{
PrintDigits<12345>();
std::cout << std::endl;
}

Greg

Oct 5 '05 #24

wi******@hotmail.com wrote:
C'mon, why would you want such a convoluted solution.

It's surely far simpler:

#include <numeric>

struct digit_iterator
{
digit_iterator(int num = 0) : _num(num) { }
int operator* () { return _num % 10; }
digit_iterator& operator++() { _num /= 10; return *this; }
bool operator!=(const digit_iterator& i) { return _num != i._num; }
private: int _num;
};

int sum_digits(int num)
{
return std::accumulate(digit_iterator(num), digit_iterator(), 0);
}

(and yes I'm sure someone will point that digit_iterator isn't a fully
valid input iterator).


A template metaprogram is the way to go here:

#include <iostream>

template <unsigned int I>
int PrintDigits()
{
PrintDigits<I/10>();
std::cout << I%10;
}

template <>
int PrintDigits<0>() {}

int main()
{
PrintDigits<12345>();
std::cout << std::endl;
}

Greg

Oct 5 '05 #25
Greg wrote:

A template metaprogram is the way to go here:

#include <iostream>

template <unsigned int I>
int PrintDigits()
{
PrintDigits<I/10>();
std::cout << I%10;
}

template <>
int PrintDigits<0>() {}

int main()
{
PrintDigits<12345>();
std::cout << std::endl;
}

Um...I assume you actually meant...

template <unsigned int I>
int SumDigits()
{
return I % 10 + SumDigits<I/10>();
}

template <>
int SumDigits<0>() { return 0; }
The slight inconvenience that the program needs to be recompiled for
every different number is surely offset by the blindingly fast run-time
efficiency.

Oct 5 '05 #26

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Shreyas Kulkarni | last post by:
hi there, recently i have got a problem regarding calculation of sum of digits in a floating point or precision number. the weird behaviour of compiler/language is preventing me from calculating...
10
by: guidosh | last post by:
Hello, I'm trying to write a printf statement that sets the field width when printing a number. I'm using this: printf("%*", fieldwidth, num_to_print); However, I can't figure out how to...
13
by: Kosio | last post by:
Hello, I know of a way to extract digits from a number using the %10 and divide by 10. But I am wondering if there is an algorithm out there that does not use a divide by 10 feature. The...
27
by: Luke Wu | last post by:
Is there a C function that returns the number of digits in an input int/long? example: numdigits(123) returns 3 numdigits(1232132) returns 7
18
by: Kuljit | last post by:
I am doing Engineering(B.Tech) in Computer Science. I have a question for which i am struggling to write a C code(program). It struck me when we were being taught about a program which counts the...
109
by: jmcgill | last post by:
Hello. Is there a method for computing the number of digits, in a given numeric base, of N factorial, without actually computing the factorial? For example, 8! has 5 digits in base 10; 10! has...
7
by: Michael Howes | last post by:
MSDN documentation for format strings seems ambiguous. It's says things like "significant digits or number of decimal places" all over the place. Well those two things are different. How do I...
2
by: Mukesh_Singh_Nick | last post by:
What is meant by the "most significant digits" in the following statement? <BLOCKQUOTE> With %g and %G, the precision modifier determines the maximum number of significant digits...
4
by: =?Utf-8?B?Vmlua2k=?= | last post by:
Hello Everyone, I am trying to convert the digits to even number so for example if I have 3 digit number, I want it to be 4 digit and If I have 5 digit number, I want it to be 6 digit. How can i...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.