Exercise 1#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog(@" n | n^2");
NSLog(@"-----|---------");
for (int i = 1; i <= 10; i++)
NSLog(@" %2i | %3i", i, i * i);
[pool drain];
return 0;
}
n | n^2
-----|---------
1 | 1
2 | 4
3 | 9
4 | 16
5 | 25
6 | 36
7 | 49
8 | 64
9 | 81
10 | 100
Exercise 2#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog(@" n | triangle #");
NSLog(@"----|------------");
for (int i = 5; i <= 50; i += 5)
NSLog(@" %2i | %4i", i, i * (i + 1) / 2);
[pool drain];
return 0;
}
n | triangle #
----|------------
5 | 15
10 | 55
15 | 120
20 | 210
25 | 325
30 | 465
35 | 630
40 | 820
45 | 1035
50 | 1275
Exercise 3#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int factorial;
NSLog(@" n | n!");
NSLog(@"----|---------");
for (int i = 1; i <= 10; i++) {
factorial = 1;
for (int j = 1; j <= i; j++)
factorial *= j;
NSLog(@" %2i | %7i", i, factorial);
}
[pool drain];
return 0;
}
n | n!
----|---------
1 | 1
2 | 2
3 | 6
4 | 24
5 | 120
6 | 720
7 | 5040
8 | 40320
9 | 362880
10 | 3628800
Exercise 5#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int n, number, triangulerNumber, counter, numberToCompute;
NSLog(@"Number of triangular numbers to compute?");
scanf("%i", &numberToCompute);
for (counter = 1; counter <= numberToCompute; counter++) {
NSLog(@"What triangular number do you want?");
scanf("%i", &number);
triangulerNumber = 0;
for (n = 1; n <= number; n++ )
triangulerNumber += n;
NSLog(@"Triangular number %i is %i", number, triangulerNumber);
}
[pool drain];
return 0;
}
Number of triangular numbers to compute?
5
What triangular number do you want?
100
Triangular number 100 is 5050
What triangular number do you want?
90
Triangular number 90 is 4095
What triangular number do you want?
80
Triangular number 80 is 3240
What triangular number do you want?
42
Triangular number 42 is 903
What triangular number do you want?
21
Triangular number 21 is 231
Exercise 8#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
long long int number;
int total;
NSLog(@"Enter your number:");
scanf("%lli", &number);
// if user enters negative number, convert to positive
if (number < 0)
number = -number;
total = 0;
while (number != 0) {
total += number % 10;
number /= 10;
}
NSLog(@"Sum of the digits: %i", total);
[pool drain];
return 0;
}
Enter your number:
42783321
Sum of the digits: 30