// countOrderedPairsBeginningWith(i,n) returns a count of // the ordered pairs of the form (i,j) where 1 <= j <= n and i > j. int countOrderedPairsBeginningWith(const int i, const int n) { int j, count = 0; j = 1; while(j <= n) { if(i > j) { count++; } j++; } return count; } // countOrderedPairs(n) returns a count of the number of // ordered pairs (i,j) where 1 <= i,j <= n and i > j. // For example, the ordered pairs containing integers from // 1 to 3 are: (1,1), (1,2), (1,3), (2,1), (2,2), (2,3), // (3,1), (3,2), (3,3). In 3 of those ordered pairs, the first // number is larger than the second number. So countOrderedPairs(3) // returns 3. int countOrderedPairs(const int n) { int i, count = 0; i = 1; while(i <= n) { count += countOrderedPairsBeginningWith(i,n); i++; } return count; }
Note. The definition of countOrderedPairsBeginningWith is strange because the loop keeps going until j > n. But values of j that are where j ≥ i are ignored. Changing the condition in the while-loop heading makes the inner if-statement unnecessary and makes the loop waste less time.
int countOrderedPairsBeginningWith(const int i, const int n) { int j, count = 0; j = 1; while(j < i) { count++; j++; } return count; }
Note. Both of these functions can be simplified using for-loops.
int countOrderedPairsBeginningWith(const int i, const int n) { int count = 0; for(int j = 1; j < i; j++) { count++; } return count; } int countOrderedPairs(const int n) { int count = 0; for(int i = 1; i <= n; i++) { count += countOrderedPairsBeginningWith(i,n); } return count; }