Amazon.com Widgets Answer to Exercise 8 extended.
Welcome, Guest. Please login or register.
Did you miss your activation email?
May 23, 2013, 01:22:33 PM
Home Help Search chat Login Register   
News: Read this please.The Great Kangaroo Escape Looking for reviews of the 4th ed on Amazon!   Twitter:  @skochan
                     

+  Official Forum for Programming in Objective-C (the iPhone Programming Language) - Stephen Kochan
|-+  Old Stuff
| |-+  Answers to Exercises
| | |-+  Chapter 5
| | | |-+  Answer to Exercise 8 extended.
Pages: [1]   Go Down
Print
Author Topic: Answer to Exercise 8 extended.  (Read 444 times)
OC2000
Newbie
*
Posts: 5


Email




« on: June 22, 2011, 09:20:58 PM »

I decided to add a little extra programming to reproduce the exact result as requested in the exercise i.e. The sum of 1234 is 1 + 2 +3 + 4 or 10

There maybe a simpler way to do this, but I've basically used what we've been taught up until now.

-(void) createAdditionNumber
{
 long int number, right_digit, startNumber, x,y,z,a;
   
    NSString * result = @"";
   
    NSLog(@"Enter your number.");
    scanf("%li",&number);
    startNumber = number; // stores the initial number
    z = 0;
    a=0;
   
   // main loop
   
    while (number !=0)
    {
        right_digit = number % 10;                                           
        x = right_digit;
        if (a == 0)
            a=x;
        else
            a = (a * 10) + x; // creates the reverse numer i.e. 1 x10 = 10 + 2 = 12, 12 x 10 = 120 + 3 = 123
        z+=x;
        number /= 10;
    }
   
    // loop to create string 1 + 2 + 3 + 4
    while (a !=0)
    {
        right_digit = a % 10;
        y = right_digit;
       
        if (a < 10 )
            result = [NSString stringWithFormat:@"%@ %li", result,y];
        else
            result = [NSString stringWithFormat:@"%@ %li +", result,y];
        a /= 10;
    }
    NSLog (@" The Sum of %li is %@ or %li", startNumber,result, z);
}
Logged
Pages: [1]   Go Up
Print
Jump to:  



Login with username, password and session length

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!
Entire forum contents (c) 2009 classroomM.com. All rights reserved.