390 likes | 612 Views
CS1010: Programming Methodology http://www.comp.nus.edu.sg/~cs1010/. Week 8: Multidimensional Arrays & Testing and Debugging. Objectives: Understand the concept and application of multidimensional arrays Understand how to test and debug your program. References: Chapter 6 Numeric Arrays.
E N D
CS1010: Programming Methodologyhttp://www.comp.nus.edu.sg/~cs1010/
Week 8: Multidimensional Arrays & Testing and Debugging Objectives: • Understand the concept and application of multidimensional arrays • Understand how to test and debug your program • References: • Chapter 6 Numeric Arrays CS1010 (AY2011/2 Semester 1)
Week 8: Outline (1/2) • Week 7 Exercise #2: Set Containment • Multidimensional Arrays • Initializers • Examples • Matrices • Demo #1: Matrix addition • Exercise #1: Matrix multiplication • Maze Problem • Exercise #2 (take-home): Valid path CS1010 (AY2011/2 Semester 1)
Week 8: Outline (2/2) • Testing and Debugging 5.1 Demo #2: Using printf() 5.2 Debugging with assert(): Demo #3: using assert() 5.3 Exercise #3: Using assert() 5.4 Testing thoroughly 5.5 Using a debugger – gdb (Demo #4) 5.6 Find the bug 5.7 Famous programming errors CS1010 (AY2011/2 Semester 1)
1. Week 7 Exercise #2: Set Containment • Consider two arrays, arrAand arrB, of int values, where their sizes are sizeA and sizeB respectively. • Write a functionintisSubset(intarrA[], intsizeA, intarrB[], intsizeB) to determine if the set of numbers in arrA is a subset of the set of numbers in arrB. • The function returns 1 if arrA is a subset of arrB, or 0 otherwise. You may assume there are no duplicate numbers in each set. • Example: If arrA[ ] = {14, 5, 1, 9} and arrB[ ] = {2, 9, 3, 14, 5, 6, 1} • isSubset(arrA, 4, arrB, 7) returns 1 • isSubset(arrA, 4, arrB, 6) returns 0 • An incomplete program Week7_SetContainment.c is given. Complete the program. This is your take-home exercise. CS1010 (AY2011/2 Semester 1)
2. Multidimensional Arrays (1/2) • In general, an array can have any number of dimensions • Example of a 2-dimensional (2D) array: // array with 3 rows, 5 columns inta[3][5]; a[0][0] = 2; a[2][4] = 9; a[1][0] = a[2][4] + 7; 0 1 2 3 4 0 2 1 16 2 9 • Arrays are stored in row-major order a[0][0] … a[0][4] a[1][0] … a[1][4] a[2][0] … a[2][4] row 0 row 1 row 2 CS1010 (AY2011/2 Semester 1)
2. Multidimensional Arrays (2/2) 1 2 3 30 31 • Examples of applications Jan 32.1 31.8 31.9 32.3 32.4 Feb 32.6 32.6 33.0 0 0 : matrix[3][3] 31.8 32.3 30.9 31.6 32.2 Dec Daily temperatures: temperatures[12][31] Suise Jerna Zass Emily Ex1 Ex1 Ex1 Ex1 Ex2 Ex2 Ex2 Ex2 Ex3 Ex3 Ex3 Ex3 Lab1 Lab1 Lab1 Lab1 59 76 79 52 75 80 50 68 60 45 66 62 Lab2 Lab2 Lab2 Lab2 60 90 57 0 72 0 60 83 0 63 48 77 Lab3 Lab3 Lab3 Lab3 76 52 81 67 80 73 59 71 66 62 75 79 Lab4 Lab4 Lab4 Lab4 38 33 60 58 52 42 72 64 37 35 52 48 Lab5 Lab5 Lab5 Lab5 93 68 58 78 68 86 80 79 72 82 85 73 Students’ lab marks: marks[4][5][3] CS1010 (AY2011/2 Semester 1)
2. Multidimensional Array Initializers // nesting one-dimensional initializers inta[3][5] = { {4, 2, 1, 0, 0}, {8, 3, 3, 1, 6}, {0, 0 ,0, 0, 0} }; // the first dimension can be unspecified int b[][5] = { {4, 2, 1, 0, 0}, {8, 3, 3, 1, 6}, {0, 0, 0, 0, 0} }; // initializer with implicit zero values int d[3][5] = { {4, 2, 1}, {8, 3, 3, 1, 6} }; What happens to the uninitialized elements? CS1010 (AY2011/2 Semester 1)
2. Multidimensional Array: Example Week8_2DArray.c #include <stdio.h> #define N 5// number of columns in array intsumArray(int[][N], int); // function prototype int main(void) { int foo[][N] = { {3,7,1}, {2,1}, {4,6,2} }; printf("sum is %d\n", sumArray(foo, 3)); printf("sum is %d\n", sumArray(foo, 2)); return 0; } // To sum all elements in arr intsumArray(intarr[][N], int rows) { inti, j, total = 0; for (i = 0; i < rows; i++) { for (j = 0; j < N; j++) { total += arr[i][j]; } } return total; } Second dimension must be specified; first dimension is not required. CS1010 (AY2011/2 Semester 1)
3. Matrices • A two-dimensional array where all rows have the same length is sometimes known as a matrix because it resembles that mathematical concept. • A matrix A with m rows and n columns is represented mathematically in the following manner. • Note that in implementing the matrix as an array in C, the row number and column number start at 0 instead of 1. CS1010 (AY2011/2 Semester 1)
3. Demo #1: Matrix Addition (1/2) • To add two matrices, both must have the same number of rows, and the same number of columns. • To compute C = A + B, where A, B, C are matrices • ci,j = ai,j + bi,j • Example on 33 matrices: CS1010 (AY2011/2 Semester 1)
3. Demo #1: Matrix Addition (2/2) For complete program see Week8_matrixOps.c // To sum mtxA and mtxB to obtain mtxC voidsumMatrix(floatmtxA[][MAX_COL], floatmtxB[][MAX_COL], floatmtxC[][MAX_COL], introw_size, intcol_size) { int row, col; for (row=0; row<row_size; row++) for (col=0; col<col_size; col++) mtxC[row][col] = mtxA[row][col] + mtxB[row][col]; } CS1010 (AY2011/2 Semester 1)
3. Exercise #1: Matrix Multiplication (1/2) • To multiply two matrices A and B, the number of columns in A must be the same as the number of rows in B. • The resulting matrix has same number of rows as A and number of columns as B. • For example, multiplying a 45 matrix with a 53 matrix gives a 43 matrix. CS1010 (AY2011/2 Semester 1)
3. Exercise #1: Matrix Multiplication (2/2) • To compute C = A B, where A, B, C are matrices • ci,j = (ai,1 b1,j ) + (ai,2 b2,j ) + . . . + (ai,nbn,j) • ci,j is sum of terms produced by multiplying the elements of A’s row i with B’s column j. • Example on 33 matrices: • Complete the prodMatrix() function in Week8_matrixOps.c CS1010 (AY2011/2 Semester 1)
4. Maze Problem (1/2) • Let’s consider a maze that is represented by a two-dimensional N N integer array. • The value of each array element is either 0 (representing a wall) or 1 (representing a cell). • The starting and exit points in the maze are specified by the cells maze[0][0]and maze[N-1][N-1] respectively. • A path is represented by a single-dimensional character array with four possible element values representing the move directions: ‘N’ (for north), ‘S’ (for south), ‘E’ (for east), and ‘W’ (for west). Each path is defined with respect to the starting cell maze[0][0]. CS1010 (AY2011/2 Semester 1)
4. Maze Problem (2/2) 0 1 2 3 4 5 • Example (N = 6) 0 1 2 3 4 5 CS1010 (AY2011/2 Semester 1)
4. Exercise #2 (take-home): Valid Path 0 1 2 3 4 5 • A path in a maze is defined to be valid if the path is within the maze and does not visit any wall. • Examples: • Valid path: ‘E’, ‘E’, ‘S’, ‘N’ • Invalid path: ‘S’, ‘W’ • Invalid path: ‘E’, ‘E’, ‘E’, ‘S’ • Write a functionintisValid (int maze[][N], char path[], intpathlen)that takes as inputs a N Nmaze and a path of length pathlen, and returns 1 if path is valid in maze; else returns 0. • This is a take-home exercise. Try it out before you refer to the given incomplete program Week8_IsValid.c. 0 1 2 3 4 5 CS1010 (AY2011/2 Semester 1)
5. Testing and Debugging (1/7) Moveable armature Electro-magnet Notebook with moth fromMark II computer: Space (Bugs may get stuck here!) CS1010 (AY2011/2 Semester 1) • Where does the term “debugging” come from? • Very early computers used mechanical relays for switching currents. However, most likely the termbug existed beforethe “moth-in-a-relay”story. • Why does a program “core dump”? • Early computers usedtiny magneticcores (rings) asmemory cells to hold0 and 1 values.
Testing Debug Error? Yes 5. Testing and Debugging (2/7) • Testing • To determine if a code contains errors. • Debugging • To locate the error(s) and fix it (them). • Documentation • To improve maintainability of the code. • Include sensible comments, good coding style and clear logic. CS1010 (AY2011/2 Semester 1)
5. Testing and Debugging (3/7) CS1010 (AY2011/2 Semester 1) • Philosophical notes on program design, debugging and testing • A good design is importantA good design results in a high quality program. A low quality design cannot be “debugged into” high quality. • Don’t optimize for speed too earlyIt is possible to make a correct program run faster.It is much more difficult to make a fast (but wrong) program run correctly.
5. Testing and Debugging (4/7) CS1010 (AY2011/2 Semester 1) • A program should be tested with various input values to make sure that it performs correctly across all inputs. • A program should make as few assumptions about the input as possible. • E.g.: Your program assumes that the user will type a number. But she types a string crash! • However, in CS1010 we assume that input follows the specification. We do this to focus on the basics first. Writing robust programs is not trivial. • Many of today’s methods to hack into computers work by feeding programs with unexpected inputs. This results in crashes, buffer overflows, etc.
5. Testing and Debugging (5/7) How to test? CS1010 (AY2011/2 Semester 1) • By user/programmer: • Run program by hand multiple times. • By test program: • Write a little test program that runs the program to be tested with different inputs. • By test environments: • Large-scale test suites that generate test cases, run them, compare the expected output and provide a pass/fail assessment. • E.g.: Mozilla’s Tinderbox
5. Testing and Debugging (6/7) • Manual walkthroughs • Tracing with pencil-and-paper. • Verbal walkthroughs. • printf() statements • Easy to add • Provide information: • Which functions have been called • The value of parameters • The order in which functions have been called • The values of local variables and fields at strategic points • Disadvantages • Not practical to add print statements in every function • Too many print statements lead to information overload • Removal of printf statements tedious CS1010 (AY2011/2 Semester 1)
5. Testing and Debugging (7/7) • Tips and Techniques • Start off with a working algorithm • Incremental coding/test early/fix bugs as you find them • Simplify the problem • Explain the bug to someone else • Recognize common errors (such as using ‘=’ instead of ‘==’, wrong addition of semi-colon, infinite loop, etc.) • Recompile everything (referring to a suite of programs) • Test boundaries • Eg: For primality test, did you test it with 1? 2? • Test exceptional conditions • Take a break! CS1010 (AY2011/2 Semester 1)
5.1 Demo #2: using printf( ) • Example on writing printf() statements Week8_WasherWeight_Printf.c . . . // compute weight of a single washer rim_area = circle_area(d2) - circle_area(d1); printf("Rim area = %lf\n", rim_area); // for checking unit_weight = rim_area * thickness * density; printf("Unit weight = %lf\n", unit_weight); // for checking // compute weight of a batch of washers total_weight = unit_weight * qty; // output printf("\nThe total weight of the batch of %d washers is %.2f grams\n", qty, total_weight); . . . CS1010 (AY2011/2 Semester 1)
5.2 Debugging with assert( ) #include <assert.h> intmy_function(int a, double b) { ... assert(a <= 5 && b >= 17.1); ... } CS1010 (AY2011/2 Semester 1) • When writing large programs, it is often useful to know that a condition or set of conditions is true. • Such a statement is known as an assertion. • The C language provides an <assert.h> header file and corresponding assert macro that the programmer can use to make assertions. • If an assertion fails, the assert macro prints a diagnostic message describing the condition that should have been true but was not, and then it kills the program.
5.2 Demo #3: Using assert( ) #include <stdio.h> #include <assert.h> int main (void) { inta; double b; a = 6; b = 18.0; assert(a <= 5 && b >= 17.1); printf("The value of a is %d and the value of b is %lf\n", a, b); return 0; } Week8_AssertDemo.c $ a.out Assertion failed: a <= 5 && b >= 17.1, file Week8_AssertDemo.c, line 11 Abort (core dumped) $ CS1010 (AY2011/2 Semester 1)
5.3 Exercise #3: Using assert( ) CS1010 (AY2011/2 Semester 1) Caution: Do NOT use assignment statement inside assert(). Take our familiar Week3_WashersWeight.cprogram and add an assertion to make sure that the outer diameter is larger than the inner diameter. Call it Week8_WashersWeight_Assert.c
5.4 Testing Thoroughly (1/3) • Test your programs with your own data • Do not rely on CodeCrunchto test your programs! • We discussed this in week 4. There is an error in this code: // To find the maximum among 3 integer// values in variables num1, num2, num3.int max = 0;if (num1 > num2 && num1 > num3) max = num1;if (num2 > num1 && num2 > num3) max = num2;if (num3 > num1 && num3 > num2) max = num3; • It works fine if it is tested on some sets of data: <3,5,9>, <12,1,6>, <2,7,4>, etc. and the program works for all these. • What is missing in his testing? CS1010 (AY2011/2 Semester 1)
5.4 Testing Thoroughly (2/3) • In testing your programs thoroughly, do not forget about boundary or special cases! • These are the cases where the program may give the wrong answer – a common error • In the Primality Test problem (checking if an integer is a prime), what are the boundary cases? CS1010 (AY2011/2 Semester 1)
if (x != 3) y = 5 z = z - x A E if (z > 1) B F C G z = z / x z = 0 D H 5.4 Testing Thoroughly (3/3) • It is also important to test all the paths that your program control flow can take • Design test data to check all paths • Example if (x != 3) { y = 5; } else { z = z - x; } if (z > 1) { z = z / x; } else { z = 0; } Test data: <x=0, z=1> to test path A, B, G, H; <x=3, z=3> to test path E, F, C, D; etc. CS1010 (AY2011/2 Semester 1)
5.5 Using a Debugger • Debugger usually provides the following • Stepping • Breakpoint • Watches (inspecting variables) • We will illustrate these with Gnu debugger gdb. • See video http://www.youtube.com/watch?v=Z6zMxp6r4mc CS1010 (AY2011/2 Semester 1)
5.5 Using the gdb Debugger (Demo #4) Explore other gdb commands on your own! CS1010 (AY2011/2 Semester 1) • Step 1: add the –g option when compiling and linking: • gcc –g Week8_WashersWeight_Printf.c • Step 2: start the gdb with your program: • gdba.out • Step 3: use the different gdb commands to step through your program: • Break at a specific function: break function_name • Start with: break main • Run program: run (or r) • Step to the next line of code: step (or s) • List source code: list (or l) • Examine the value of a variable: print variable_name • Quit the debugger: quit
5.6 Find the Bug doublehalf(doublein_val) { return (in_val/2.0); } Week8_Half.c Week8_HalfMain.c #include <stdio.h> intmain(void) { intval = 10; double result = 0.0; result = half(val); printf("Half of %dis%lf\n", val, result); return 0; } Compile it with –Wall option. $ gccWeek8_HalfMain.c Week8_Half.c $ a.out $ Half of 10 is 10.000000 CS1010 (AY2011/2 Semester 1) • Why does this program produce the wrong result?
5.7 Famous Programming Errors (1/2) CS1010 (AY2011/2 Semester 1) • Mariner Bugs Out (1962) • Cost: $18.5 million • Disaster: The Mariner 1 rocket with a space probe headed for Venus diverted from its intended flight path shortly after launch. Mission Control destroyed the rocket 293 seconds after liftoff. • Cause: A programmer incorrectly transcribed a handwritten formula into computer code, missing a single superscript bar. Without the smoothing function indicated by the bar, the software treated normal variations of velocity as if they were serious, causing faulty corrections that sent the rocket off course.
5.7 Famous Programming Errors (1/2) CS1010 (AY2011/2 Semester 1) • Mars Climate Crasher (1998) • Cost: $125 million • Disaster: After a 286-day journey from Earth, the Mars Climate Orbiter fired its engines to push into orbit around Mars. The engines fired, but the spacecraft fell too far into the planet’s atmosphere, likely causing it to crash on Mars. • Cause: The software that controlled the Orbiter thrusters used imperial units (pounds of force), rather than metric units (Newtons) as specified by NASA.
Summary for Today • Today’s most important lessons • Multidimensional arrays • Testing and Debugging • Using printf() to trace your program • Using assert() • Using gdb debugger CS1010 (AY2011/2 Semester 1)
Announcements/Things-to-do • Revise Chapter 6 Numeric Arrays • Term Test this Saturday • 8 October 2011, Saturday • See module website for details • Next week’s lecture • Recursion: Lesson 8.10 CS1010 (AY2011/2 Semester 1)
End of File CS1010 (AY2011/2 Semester 1)