Ronald - 9 months ago 27

Objective-C Question

The following program calculates and removes the remainder of a number, adds the total of the remainders calculated and displays them.

`#import <Foundation/Foundation.h>`

int main (int argc, char * argv[]) {

@autoreleasepool {

int number, remainder, total;

NSLog(@"Enter your number");

scanf("%i", &number);

while (number != 0)

{

remainder = number % 10;

total += remainder;

number /= 10;

}

NSLog(@"%i", total);

}

return 0;

}

My questions are:

- Why is the program set to continue as long as the number is not equal to 0? Shouldn't it continue as the long as the remainder is not equal to 0?
- At what point is the remainder discarded from the value of ? Why is there no
`number`

statement before`number -= remainder`

?`n /=10`

[Bonus question: Does Objective-C get any easier to understand?]

Answer

The reason we continue until

`number != 0`

instead of using remainder is that if our input is divisible by`10`

exactly, then we don't get the proper output (the sum of the base 10 digits).The remainder is dropped off because of integer division. Remember, an integer cannot hold a decimal place, so when we divide 16 by 10, we don't get 1.6, we just get 1.

And yes, Objective-C does get easier over time (but, as a side-note, this uses absolutely 0 features of Objective-C, so it's basically C with a `NSLog`

call).

Note that the output isn't quite what you would expect at all times, however, as in C / ObjC, a (unlike languages like D or JS) a variable is not always initialized to a set value (in this case, you assume 0). This could cause UB down the road.

Source (Stackoverflow)