add numbers apart from last

hello there. I'm new here I may trying to write a c++ code that will add all of the numbers together apart from the last one. I can get all of the numbers to add together but I cant seam to find a way to exclude the last number, for example if I enter in 5556 I want to add 5+5+5 but leave out the 6. any help would be greatly appreciated

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 #include <iostream>
using namespace std;
int main()
{
int num;
int sum = 0;
cout << " Enter a number above 0 : ";
cin >> num;
while ( num > 0 ) {
sum += num % 10;
num /= 10;
}
cout << "Sum = " << sum;
return 0;
}
nu123,

You are so close!

Do you understand how your current code works?

num%10 will give the current number, modulo 10; i.e. the current last digit. You add this to sum.
Then num /= 10 will do integer division by 10, which effectively removes the last digit.

So, all you need to do is remove the last digit WITHOUT adding it to the sum. The easiest way is probably just to add ANOTHER single line
num /= 10;
before line 9.
add
num=num/10;
after cin and above while
that's brilliant thanks. i was trying to figure it out for ages. i have a basic under standing of the code but I'm still new to c++ so I cant fully understand what is happening yet
Topic archived. No new replies allowed.