Hi. How do i make this program count the sum of the numbers that make up the enered number? e.g. '14' will be '5'. What should i put in the brackets? Idont know how to make this program know of how many numbers inputed number is made
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<iostream>
usingnamespace std;
int main(){
int n, sum=0;
cin>>n;
while(n/){
}
return 0;
}
thank, but how do i make it using while loop? im asking this because tomorrow ill have a test with while loop so im now "trainng" for it. im a total beginner knowing only for and while loops, havent worked with strings or any other fancy stuff yet
This isn't any kind of "training in how to use the while loop". The while loop is simple.
1 2 3 4 5 6 7
while ( some_condition )
{
//code
// code that might set some_condition to false
}
That's everything there is to know about a while loop.
This is about algorithms. It requires the knowledge that an int divided by an int gives an int (e.g 123 / 10 = 12)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
int main()
{
int value = 0;
cin >> value;
int sum = 0;
if (value < 0) value*=-1;
while(value > 9)
{
sum += value - ((value/10) * 10);
value =value/10;
}
sum += value;
cout << '\n' << sum << '\n';
}