Discuss Please. I need some help with a function. in the C/C++ Help forum on Dev Articles. Please. I need some help with a function. C/C++ Help forum discussing building and maintaining applications in C/C++. Find out why these languages are the foundation on which other languages are built.
Posts: 3
Time spent in forums: 16 m 16 sec
Reputation Power: 0
Please. I need some help with a function.
I have asked my C++ instructor about it and he confused me throughly.
I have a int value. For example 35. I need a function that can add the digits of the number together. So another value will be 3+5 or 8. I have thought of converting it to String and reading each digit as a character but it became very messy and did not work properly. I would appreciate some direction.
Posts: 997
Time spent in forums: 6 Days 14 h 26 m 27 sec
Reputation Power: 5
Something like this?
You'll only need the add_digits() function, the rest is just a demonstration.
C Code:
Original
- C Code
#include <stdio.h>
#include <stdlib.h>
int add_digits(int input)
{
if(input < 10)
return input;
else
return(input % 10 + add_digits(input / 10));
}
int main(int argc, char **argv)
{
/* Declarations */
int number, i;
/* See if command line parameter set */
if(argc > 1)
{
for(i = 1; i < argc; ++i)
{
number = atoi(argv[i]);
printf("digits for %d add up to %d\n", number, add_digits(number));
}
}
else
{
number = 35; /* Your example */
printf("digits for %d add up to %d\n", number, add_digits(number));
}
/* Exit Succes */
return0;
}
If you compile this and run it from the command line, you can add any number of (integer) parameters, and it'll perform the function on them.
__________________ This is my code. Is it not nifty?
"The biggest problem encountered while trying to design a system that was completely foolproof, was, that people tended to underestimate the ingenuity of complete fools."
---Douglas Adams