Ronald
Ronald

Reputation: 343

'while' Loop in Objective-C

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:

  1. 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?

  2. At what point is the remainder discarded from the value of number? Why is there no number -= remainder statement before n /=10?

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

Upvotes: 1

Views: 4465

Answers (2)

KSletmoe
KSletmoe

Reputation: 1017

  1. It checks to see if number is not equal to zero because remainder very well may never become zero. If we were to input 5 as our input value, the first time through the loop remainder would be set to 5 (because 5 % 10 = 5), and number would go to zero because 5 / 10 = 0.5, and ints do not store floating point values, so the .5 will get truncated and the value of number will equal zero.
  2. The remainder does not get removed from the value of number in this code. I think that you may be confused about what the modulo operator does (see this explanation).

Bonus answer: learning a programming language is difficult at first, but very rewarding in the long run (if you stick with it). Each new language that you learn after your first will most likely be easier to learn too, because you will understand general programming constructs and practices. The best of luck on your endeavor!

Upvotes: 0

Richard J. Ross III
Richard J. Ross III

Reputation: 55543

  1. 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).

  2. 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.

Upvotes: 2

Related Questions