473,651 Members | 2,644 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

I need help calculating the sum of the numbers of an integer

Like I said in the title, I have to calculate the sum of the numbers of
an interger with a recursive fonction.

Exemple: n=1255, sum= 1 + 2 + 5 + 5= 13

Do I have to use a string on can I use a simple cin ??

Thanks for your help !!

And sorry for my english :)

Nov 2 '05 #1
6 4074
lpw
> Like I said in the title, I have to calculate the sum of the numbers of
an interger with a recursive fonction.

Exemple: n=1255, sum= 1 + 2 + 5 + 5= 13

Do I have to use a string on can I use a simple cin ??

Thanks for your help !!

And sorry for my english :)


Funny... this arrived right after Shiva's post, which, among other things,
states:

"As a rule, posters in comp.lang.c++ will not do homework, but will give
helpful hints if you have shown some willingness to try a solution."
Nov 2 '05 #2
un[real] wrote:
Like I said in the title, I have to calculate the sum of the numbers of
an interger with a recursive fonction.

Exemple: n=1255, sum= 1 + 2 + 5 + 5= 13

Do I have to use a string on can I use a simple cin ??


You can use 'simple cin'.

The key is understanding how % and / work on integers.

john
Nov 2 '05 #3
I would said that you really have to understand what n%10 and n/10 does
IF n is an integer. Experiment a bit (you can even combine them so also
try n/10%10 )

Now go do your homework!

Nov 2 '05 #4
Ok thanks... i'll work on that

Nov 2 '05 #5
I know it's my first time posting here, and I'm not asking for a
solution at all, I'm just looking for some hint about how to do it...

I can calculate the sum of the numbers but not in a recursive way, that
is why I posted here

Nov 2 '05 #6
This is completely off topic from this groups, but now that we are it:

OK, now that you are trying let me give you my idea, you can compare
and learn from it:

When you are doing recursion you find where the recursion is at, and
what's your base case.

So think that sum of all digits of a given number is the sum of the
last digit plus the sum of all the others digits, but the some of all
the others digits is the sum of the last digit plus... ¡You have
recursion!

Ok, so let's translate into code what exactly means that precious
sentences:

The last digit of a given integer number is calculated with %10, it's
not God-sent either, the a%b returns the reminder of a/b, and a little
bit of math would give you that the reminder of a/10 is always the last
digit of it.

Now the funny thing is n/10. If n is an integer, n/10 drops the decimal
part of it because an integer doesn't hold decimal numbers.

So if you have a function sumDigits() the sentence "the sum of all
other digits (of a given number n)" means sumDigits(n/10)

And of course your base case, the thing that stops the recursion going
forever, is when you have a number that is single-digit. If that's the
case well the sum is the number itself:

Now HOCUS-POCUS:

int sumDigits(int n){

if(n<10)
return n;
else
return n%10 + sumDigits(n/10);

}

I thinks it's also worth to look at a non-recursive function to do
that:

int sumDigits(int n){

int sum;
for(sum=0; n>0; sum+=n%10, n/=10);

return sum;

}

Nov 3 '05 #7

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

Similar topics

2
1876
by: Oliver Burnett-Hall | last post by:
I'm trying to move to using tableless page layouts, but I've come across what appears to be a bug in IE5's rendering that I can't find a way to overcome. The page has a sidebar to the left of the main content area. The main content are has several subsections, each of which starts with a mini-menu of four links. I want to have these laid out across the full width of the column. Here's an ASCII attempt to show the desired page layout:
4
5576
by: bonehead | last post by:
Greetings, A friend tells me that he has not been able to work out an expression that calculates elapsed minutes from TimeA to TimeB. For example: TIMEA TIMEB ELAPASED ----- ----- -------- 11:30AM 12:35PM 65
4
6482
by: Nikhil Patel | last post by:
Hi all, I am a VB6 programmer and learning C#. I am currently reading a chapter on types. I have question regarding enums. Why do we need to convert enum members to the value that they represent? Thanks in advance... -Nikhil
13
1509
by: Supra | last post by:
how do i get 2 different number in same row? using random example: 4 2 5 6 7 4 1 7 9 8 3 3 <===== i want different number but not same as opposite 8 5
4
28736
by: Mahesh S | last post by:
Hi I am writing a sql query (added below) to calulate percentage. Its returning an integer value whereas I would like to get a float value (with 2 decimal precision). The query is: (SELECT (COUNT(*) * 100) / (SELECT COUNT(*) FROM HEALTHCAREDB.PATIENT_DIABETIC_TYPE)
8
2324
by: sajid | last post by:
The CSS 2.1 Specification describes how to sort a list of selectors in order of specificity, but it doesn't provide a method to calculate the specificity of a single selector in isolation. I've devised a method to do this, which I describe in the following article: http://calculating-css-selector-specificity.blogspot.com/ Comments and/or criticisms welcome.
17
4613
by: Ron | last post by:
I want to write a program that will accept a number in a textbox for example 23578 and then in a label will display the sum of the odd and even number like this... the textbox containsthe number 23578 the label would say: Sumof odd number is: 15 Sum of even number is: 10 any ideas?
4
2158
by: sigkill9 | last post by:
I'm trying to create a script that will accept a user entered integer and find only one set of prime numbers that add up to that integer but need some help. The script is supposed to only accept even numbers, and if it encounters an odd number it needs to exit with a "please enter only even numbers" message. I've made some progress on the script, but it still isnt quite rite. I already tried to code an error message for uneven input...
1
3546
by: cmb3587 | last post by:
My code runs fine for the most part...the only time it fails is when I type in a negative to end the array. I don't want the negative number to be included in the array and I thought that is what the while loop in the getNums method does. However, it is including this negative number when calculating the avg and it is doing something weird to the median. When the array end itself because the max size has been reached everything works fine. ...
0
8349
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8795
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8695
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8460
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8576
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7296
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6157
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4281
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1585
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.