Amazon.com Widgets Chapter 5 Exercise 8
Welcome, Guest. Please login or register.
Did you miss your activation email?
May 24, 2013, 02:11:03 AM
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
| | | |-+  Chapter 5 Exercise 8
Pages: [1]   Go Down
Print
Author Topic: Chapter 5 Exercise 8  (Read 571 times)
WANGOOROO
Newbie
*
Posts: 11

wangooroo@hotmail.com WANGOOROO WANGOOROO
WWW Email




« on: November 09, 2009, 03:09:33 PM »

Here is my version of Chapter 5 Exercise 8.

I get the result I want, but using the method with % I am adding the digits of the supplied integer in reverse order.  Not sure it really matters as the end value is the same. 

--------------

Code: (Objective-C)
/*	Chapter 5 Exercise 8
Write a program that calculates the sum of the digits of an integer

For example: the sum of the digits of the number 2155 is:
2 + 1 + 5 + 5 = 13
 
The program should accept any arbitrary integer entered.   */


#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

int number, right_digit, sum;

sum = 0;

NSLog(@"Enter your number.");
scanf("%i", &number);

while ( number != 0 )
{
right_digit = number % 10;
sum += right_digit;
NSLog(@"%i", right_digit);
number /= 10;
}

NSLog(@"The sum of these digits is: %i", sum);

[pool drain];
    return 0;
}

Logged

I am striving to be the kind of person such that when my feet hit the floor each morning the devil says, "Oh crap, He's awake!"
skochan
Administrator
Hero Member
*****
Posts: 3104







« Reply #1 on: November 09, 2009, 06:48:10 PM »

Your approach is fine.

Cheers,

Steve Kochan
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.