Typically,
for
is used when you have a counter controlling the number of times your loop is executed. You don't have such a counter here, although you could construct one.
OriginalGriff did just that in solution 1, using the same variable that your
while
uses to control the loop. I'd go one step further, since you modify your control variable in each iteration: that is a step typically placed in the last section of the
for
statement, like this:
for( ; num != 0 ; num = num/10 )
{
...
}
Personally, however, I'd do something entirely different: the input is natively entered as a string, so why not read it as a string and simply iterate over the digits that are already present in that string? This would lend itself to a much more natural use of
for
!
Also, you tagged this question as C++/Objective C, but you are using C functions instead of C++ io streams!?
Additionally, never define
main()
with a return type of
void
! the main function should always return
int
, even though the compiler may accept
void
. That is a convention expected from every executable program.
Try something like this:
#include <iostream>
#include <string>
int main() {
string line;
std::cout << "please enter number: " << std::endl;
std::getline(std::cin, line);
int sum = 0;
for (auto position = line.begin(); position != line.end(); ++position)
{
}
...
return 0; }