// this program uses functions to read values into a 2D array and // print it out #include <iostream.h> #include <iomanip.h> const int NUMROWS = 10; const int NUMCOLS = 8; void fillArray(int [][NUMCOLS],int&,int&); void printArray(int [][NUMCOLS],int,int); int main() { int matrix[NUMROWS][NUMCOLS]; int nrows; int ncols; fillArray(matrix,nrows,ncols); printArray(matrix,nrows,ncols); return 0; } // this function asks the user how many rows and columns will be // used and then reads the values. the parameters rows and cols // return the number of rows and columns used void fillArray(int matrix[][NUMCOLS], int& rows, int& cols) { // ask the user how many rows and columns he or she would like to use cout << "How many rows would you like to fill (max " << NUMROWS << ")? "; cin >> rows; cout << "How many columns would you like to fill (max " << NUMCOLS << ")? "; cin >> cols; for (int i = 0 ; i < rows ; i++) { cout << "Enter the values for the " << (i+1) << "th row: " << endl; for (int j = 0 ; j < cols ; j++) cin >> matrix[i][j]; } } // this function prints out the values that were read into the array // values are printed in row order void printArray(int matrix[][NUMCOLS], int rows, int cols) { cout << endl << endl << "The matrix:\n"; for (int i = 0 ; i < rows ; i++) { for (int j = 0 ; j < cols ; j++) cout << setw(5) << matrix[i][j]; cout << endl; } }
How many rows would you like to fill (max 10)? 4 How many columns would you like to fill (max 8)? 6 Enter the values for the 1th row: 1 2 3 4 5 6 Enter the values for the 2th row: 222 3 444 55 6 777 Enter the values for the 3th row: 987 6 54 32 111 20 Enter the values for the 4th row: 6 44 7 88 3 2 The matrix: 1 2 3 4 5 6 222 3 444 55 6 777 987 6 54 32 111 20 6 44 7 88 3 2
Email Me |
Office Hours |
My Home Page |
Department Home |
MCC Home Page
© Copyright Emmi Schatz 2002