total beginner with while

Hey, can you help me with this? I know I should add more variables but I still dont know where. You are given a number and you have to find the sum of the numbers that consist of that number, for ex. if you are given 177, the answer should be 15. I know it's pretty easy but I still can't crack this. I dont know how to complete the division part.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  #include <iostream>
using namespace std;
int main (){
float n=1, sum=0; // n-number(that will be given)

while(n>0){
cin>>n;
  n=n%100;
  n=n/ ;   //???
  sum=sum+n; 
    
}

cout<<sum;
return 0;
This is how I would have done it -

1. Input the number as an std::string

http://www.cprogramming.com/tutorial/string.html

2. Then you can use std::stoi to convert each character in the string to an integer (put them in an vector of ints) -

http://en.cppreference.com/w/cpp/string/basic_string/stol
http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4027/C-Tutorial-A-Beginners-Guide-to-stdvector-Part-1.htm

3. Then just sum the contents of the vector.
Last edited on
Thanks but I have to use while loop only since I'm still not an independent student
If your goal is just to use a while loop, then you can do that even if you do it the way I described.
It's not that complicated actually.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include <iostream>
using namespace std;
int main (){
int n=1, sum=0; // n-number(that will be given)

while( n != 0){
cout << "enter: ";
cin>>n;
  sum+=n%100;
n -=100 * n;
  sum+=n%10;
n-= 10*n;
 sum+=n%1;
n-= 1*n;
  
}

cout<<sum;
return 0;
}


Code may not be generic, but you can probably fix that.
Btw, sum must be an integer, because your numbers won't divide completely.
So 177%100 = 1.77 or 1
77%10 = 7.7 or 7
7%1 = 7 or 7.
Now I give you the task to incorporate loops to make the program more generic, and allow any number work. This program works for numbers 999 and below. Make it work for any.
Last edited on
Topic archived. No new replies allowed.