Code: (Objective-C)
- // Chapter 5 Exercise 2
- // A triangular number can also be generated for any integer value
- // of n by this formula:
- // triangularNumber = n (n + 1) / 2
- // For example, the 10th triangular number, 55, can be calculated
- // by substituting 10 as the value for n into the previous formula.
- // Write a program that generates a table of triangular numbers
- // using the previous formula. Have the program generate every fifth
- // triangular number between 5 and 50 (that is, 5, 10, 15, ..., 50).
-
#import <Foundation/Foundation.h>
- int main(int argc, const char * argv[])
- {
- @autoreleasepool {
- int n, triangularNumber;
- NSLog(@"Table of triangular numbers ");
- NSLog(@"--- -----------------------");
- NSLog(@" n triangularNumber ");
- NSLog(@"--- -----------------------");
- for (n = 5; n <=50; n += 5) {
- triangularNumber = n * (n + 1) / 2;
- NSLog(@"%2i %i", n, triangularNumber);
- }
- }
- return 0;
- }
output:
2012-07-23 13:34:51.937 prog5[3235:403] Table of triangular numbers
2012-07-23 13:34:51.939 prog5[3235:403] --- -----------------------
2012-07-23 13:34:51.940 prog5[3235:403] n triangularNumber
2012-07-23 13:34:51.940 prog5[3235:403] --- -----------------------
2012-07-23 13:34:51.941 prog5[3235:403] 5 15
2012-07-23 13:34:51.941 prog5[3235:403] 10 55
2012-07-23 13:34:51.942 prog5[3235:403] 15 120
2012-07-23 13:34:51.942 prog5[3235:403] 20 210
2012-07-23 13:34:51.942 prog5[3235:403] 25 325
2012-07-23 13:34:51.943 prog5[3235:403] 30 465
2012-07-23 13:34:51.943 prog5[3235:403] 35 630
2012-07-23 13:34:51.944 prog5[3235:403] 40 820
2012-07-23 13:34:51.944 prog5[3235:403] 45 1035
2012-07-23 13:34:51.945 prog5[3235:403] 50 1275