COMP 102 Programming Fundamentals I Presented by : Timture Choi COMP102 Lab 09 1 2-D Array E.g. // declare a 2-D array of 30 uninitialized integers int table[3][10]; 3 rows 10 columns 0 1 2 0 1 2 ---- COMP102 Lab 09 ---- ---- 3 4 5 6 7 8 9 ---- ---- ---- ---- ---- ---- ---2 2-D Array Accessing 2-D array Syntax array[row][column] E.g. table[1][2] = 5; x = table[1][2]; table COMP102 Lab 09 0 1 2 0 1 2 3 4 5 ---- ---- -5 -- ---- ---- ---3 2-D Array Initialization Two methods to initialize a 2-D array int table[3][6] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16, 17,18}; int table[3][6] = {{1,2,3,4,5,6}, {7,8,9,10,11,12}, {13,14,15,16,17,18}}; table COMP102 Lab 09 0 1 2 0 1 2 3 4 5 1 7 13 2 8 14 3 9 15 4 10 16 5 11 17 6 12 18 4 2-D Array Inputting Values Use two for loops to access/process all the elements of a 2-D array E.g. int total_row = 3, total_col = 6; for (int row=0; row<total_row; row++) for (int col = 0; col<total_col; col++) { // assign value to an element of array table[row][col] = row*col; … // assign value of an element to a variable temp = table[row][col]; } COMP102 Lab 09 5 Mathematical Functions #include <math> double log(double x) Natural logarithm double log10(double x) Base 10 logarithm double exp(double x) e to the power x double pow(double x, double y) x to the power y double sqrt(double x) Square root of x double sin(double x) double cos(double x) double tan(double x) In radian argument COMP102 Lab 09 6 Mathematical Functions double ceil(double x) Smallest integer not less than x E.g. ceil(1.1) => 2 ceil(-1.9) => -1 double floor(double x) Largest integer not greater than x E.g. floor(1.9) => 1 floor(-1.1) => -2 <math.h> will not provide the round-off function COMP102 Lab 09 double d; int i; … int i = (int) (d>0 ? d+0.5 : d-0.5); 7 Passing Arrays as Parameters 1-D int func(int array[size], int size); int func(const int array[size], int size); 2-D int func(int array[row][col], int row, int col); int func(const int array[row][col], int row, int col); The “[ ]” in the formal parameter specification Indicates that the variable is an array It is a good practice to pass the dimension of the array as another parameter Arrays are always passed by reference If the function must not change any element of the array const should be used COMP102 Lab 09 8 SUMMARY By the end of this lab, you should be able to: Declare and manipulate 2-D arrays Use mathematical functions provide by <math> Pass an array to a function Normally With const keyword COMP102 Lab 09 9