// From the software distribution accompanying the textbook // "A Practical Introduction to Data Structures and Algorithm Analysis, // Third Edition (C++)" by Clifford A. Shaffer. // Source code Copyright (C) 2007-2011 by Clifford A. Shaffer. // This program tests various code fragements from // Chapter 3, mainly for syntactic correctness. #include "book.h" #include "permute.h" // Dummy function for the example of section 3.8 int value(int x) { return x; } // Dummy sort function for c3p13.book and c3p16.book int sort(int *x, int count) { return count; } // Since the array used in this fragment is two dimensional, bury it // in its own function to avoid conflicting with the use in other // fragments. void foo(int n) { int A[n][n]; int i, j, tmp; // Exercise 3.10d for (i=0; i < n-1; i++) for (j=i+1; j < n; j++) { tmp = A[i][j]; A[i][j] = A[j][i]; A[j][i] = tmp; } } int main() { int sum; int i, j, k; int n = 100; int a; int b = 15; int *A; int sum1, sum2; Randomize(); if ((A = (int *)calloc(n, sizeof(int))) == NULL) { cout << "Error: Unable to allocate space for permutation array\n"; exit(-1); } // Example 3.3, a simple double loop sum = 0; for (i=1; i<=n; i++) for (j=1; j<=n; j++) sum++; cout << "Test 1: For n = " << n << ", sum is " << sum << "\n"; cout << "(It should be n^2.)\n"; // Example 3.9, a simple assignment a = b; cout << "Test 2: b is " << b << " and a is " << a << "\n"; // Example 3.10, a single loop making a simple summation sum = 0; for (i=1; i<=n; i++) sum += n; cout << "Test 3: For n = " << n << ", n^2 is " << sum << "\n"; // Example 3.11, two loops, one nested sum = 0; for (i=1; i<=n; i++) // First for loop for (j=1; j<=i; j++) // is a double loop sum++; for (k=0; k