Program | Comments |
//Arrays - Tutorial 1 #include <iostream> #include <iomanip> |
We need iostream.h since we are using cout and we need iomanip.h (io manipulators header file) since we use the setw() manipulator. |
{ int num[10][10], totals[] = {0,0,0,0,0,0,0,0,0,0}; int row, column; |
The num array is declared as being a two-dimensional 10 X 10 array of integers. The totals array does not have a size declared but initialised to zeroes, the number of zeroes determines the size of totals. The integers row and column are used to count through the 2D array. |
for (row = 0; row < 10; row++) for (column = 0; column < 10; column++) num[row][column] = row * column; |
Array num is initialised to contain the product of the current values of row and column. A nested for loop is used, the program steps through in row order followed by column order. |
for (column = 0; column < 10; column++) for (row = 0; row < 10; row++) totals[column] = totals[column] + num[row][column]; |
Now the totalling of each column is completed. A nested for loop is used: for each row total the current column. |
for (row = 0; row < 10; row++) { cout << "....... "; for (column = 0; column < 10; column++) cout << setw(4) << num[row][column]; cout << endl; } |
The rows and columns are displayed almost as for the original
example. The difference is just the addition of the line:
cout << "....... "; |
cout << "Totals: "; for (row = 0; row < 10; row++) cout << setw(4) << totals[row]; cout << endl; return 0; } |
Last of all the totals are shown, after the last row of the num array. |
First | Next | Previous | Last | Glossary | About |
Copyright © 1999 - 2001
David Beech