Click here to Skip to main content
15,890,579 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In the following program I want to use instead of While loop.
This program returns the sum of individual numbers of positive integer number.

Objective-C
#include<stdio.h>
#include<conio.h>
void main()
{
int num,k,sum=0;
clrscr();
printf("Enter the numbers whose digits are to be added :- ");
scanf("%d",&num);
while(num!=0)
{
k=num%10;
sum=sum+k;
num=num/10;
}
printf("\nSum of the Digits :- %d",sum);
getch();
}


Output
Enter the numbers whose digits are to be added :- 456
Sum of the Digits :- 15
Posted
Updated 25-Mar-15 21:27pm
v2

Why? While is the natural loop for this. The alternative is basically a while that is harder to read:
C++
for( ; num != 0 ; )
   {
   ...
   }
 
Share this answer
 
Comments
Stefan_Lang 26-Mar-15 5:25am    
Very true, the code doesn't lend itself to a for loop. Therefore I suggested an alternate implementation that, IMHO, is more appropriate to the task, and offers a reasonable application of the for loop.
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:
C++
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:
C++
#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)
   {
      // get character at position, convert to digit, and add to sum
   }
   ...
   return 0; // 0 indicates success; return something else if an error occurs above
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900