hello! any type of help will be appreciated!

hi i need help writing a code that has an output like this example:

"the value entered is 5467 it has 4 digits, the sum of all digits is 22.
the second value entered is 123456 it has 6 digits, the sum of all digits is 21."


now, i know basic input/output logic i just don't know how to ask the program to count how many digits the entered value has. thanks in advance!
First take a look at the modulus operator (%) on how you will be adding up the individual digits in the number.

Now if you need to know how many digits are in your input number, you can try narrowing down the digits with comparisons.

i.e.

int numDigits(int val){

if(val < 10)
return 1;
else if (val < 100)
return 2;
...
...
...

}
i do not recall ever using "int numdigits(int val)
{
}

how does that work?
You would have to create a function, I just suggested that code as a jumping off point.

When you get the int value. Take that and pass it when you print out the sentence.

For example.

Let's say the input value was 12345, well I know that the numbers in the code are five. 1.2.3.4.5. But the computer doesn't yet know we want to use that number, we have to tell the computer (through an algorithm we design in C++) to give us the number of individual numbers in the input value.

So you would pass the value as such.

cout << "The value entered is " << val << " it has " << numDigits(val) << "digits, the sum of all the digits is " << sumDigits(val);

By creating two function we can split up the code into bite-size manageable pieces. We use these pieces (functions) to do things with the values (val) we want done to those values. So when we can numDigits(val) we are looking for the total number of digits within val. Take a look at my previous post and continue it on until 10 digits. Just follow that pattern.

Same thing with sumDigits(val) (which I am giving you a big hint here! Take a look at the % modulus operator. This will be your main way of finding the total value of the number.
so i looked at the modulus operator and i found that it outputs a remainder. how can i use that to sum up the individual numbers?

i.e.

12345

so 5%1 ?
12345 & 10 = 5
+
1234 % 10 = 4
+
123 % 10 = 3
+
12 % 10 = 2
+
1 % 10 = 1

5+4+3+2+1 = 15
Like militie said, you can use while loop to do the work. (or recursive function if you know)

you need a variable to store the sum.

int sum = 0;
while(when to stop?){
/*
code here
*/
}
Topic archived. No new replies allowed.