// ------------------------------------------------------------ // array.cpp 13 Sept 2000 // ------------------------------------------------------------ #include "w.h" // ---------------------------------------------------- // io for arrays void pl(int vi[], int k) { for (int j = 0; j < k; j++) cout << vi[j] << " "; nl(); } void pl(double xi[], int k) { for (int j = 0; j < k; j++) cout << xi[j] << " "; nl(); } // ---------------------------------------------------- void main () { nl(0); banner("array.cpp"); int v[10]; // 10 integers v[0] --> v[9] for (int j = 0; j < 10; j++) v[j] = j*j; for (j = 0; j < 10; j++) cout << v[j] << " "; nl(); pl(v,10); int u[] = {1,2,3,4,5,6,7,8,9,10,11,12}; pl(u,11); double x[8]; for (j = 0; j < 8; j++) x[j] = 1.0/(j+1); p("The array x = ");pl(x,8); nl(); double mean = 0; for (j = 0; j < 8; j++) mean = mean + x[j]; mean = mean/8.0; p("The mean of x is mean = "); pl(mean); nl(); char name[] = {'B','e','e','t','h','o','v','e','n','\0'}; pl(name); // name[] can be used 'as' a string nl(); cout << 66 << " = " << char(66)<< " = " << 1*char(66); // multiplying by 1 'casts' char(66) to int(66) nl(2); for (j = 0; j < 9; j++) v[j] = 1*name[j]; pl(v,9); nl(); char name1[] = "Beethoven"; // initialize as a string pl(name1); // = has been 'taught' to assign "Beethoven" to the array for (j = 0; j < 9; j++) v[j] = 1*name1[j]; // coerce char -> int pl(v,9); nl(); int v1[] = {1,2,3,4,5}; int v2[5]; // v2 = v1; WRONG because = is not defined for arrays for (j = 0; j < 5; j++) v2[j] = v1[j]; // elements are int pl(v1,5); pl(v2,5); } /* output --------------------------------------------------- ----------- array.cpp ----------- 0 1 4 9 16 25 36 49 64 81 0 1 4 9 16 25 36 49 64 81 1 2 3 4 5 6 7 8 9 10 11 The array x = 1 0.5 0.333333 0.25 0.2 0.166667 0.142857 0.125 The mean of x is mean = 0.339732 Beethoven 66 = B = 66 66 101 101 116 104 111 118 101 110 Beethoven 66 101 101 116 104 111 118 101 110 1 2 3 4 5 1 2 3 4 5 */