7/27/2019 Week8.pptx
1/39
CS1010: Programming Methodologyhttp://www.comp.nus.edu.sg/~cs1010/
http://www.comp.nus.edu.sg/~cs1101/http://www.comp.nus.edu.sg/~cs1101/7/27/2019 Week8.pptx
2/39
Week 8: Multidimensional Arrays &
Testing and Debugging
Objectives:
Understand the concept and application of
multidimensional arrays Understand how to test and debug your program
CS1010 (AY2011/2 Semester 1)
References: Chapter 6 Numeric Arrays
Week8 - 2
7/27/2019 Week8.pptx
3/39
Week 8: Outline (1/2)
1. Week 7 Exercise #2: Set Containment2. Multidimensional Arrays
Initializers
Examples
3. Matrices Demo #1: Matrix addition
Exercise #1: Matrix multiplication
4. Maze Problem Exercise #2 (take-home): Valid path
CS1010 (AY2011/2 Semester 1) Week8 - 3
7/27/2019 Week8.pptx
4/39
Week 8: Outline (2/2)
5. Testing and Debugging5.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) Week8 - 4
7/27/2019 Week8.pptx
5/39
1. Week 7 Exercise #2: Set Containment
Consider two arrays, arrA and arrB, of int values, where theirsizes are sizeA and sizeB respectively.
Write a functionint isSubset(int arrA[], int sizeA, int arrB[], int sizeB)
to determine if the set of numbers in arrA is a subset of the set of
numbers in arrB. The function returns 1 ifarrA is a subset ofarrB, 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) Week8 - 5
7/27/2019 Week8.pptx
6/39
2. Multidimensional Arrays (1/2)
In general, an array can have any number ofdimensions
Example of a 2-dimensional (2D) array:
// array with 3 rows, 5 columns
int a[3][5];a[0][0] = 2;a[2][4] = 9;a[1][0] = a[2][4] + 7;
Arrays are stored in row-major ordera[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) Week8 - 6
0 1 2 3 4
01
2
2
9
16
7/27/2019 Week8.pptx
7/39
2. Multidimensional Arrays (2/2)
Examples of applications
CS1010 (AY2011/2 Semester 1) Week8 - 7
matrix[3][3]
1 2 3 30 31
Jan
Feb
Dec
:
32.1 31.8 31.9
32.3 32.4
32.6 32.6 33.0 0 0
31.8 32.3 30.9 31.6 32.2
Daily temperatures: temperatures[12][31]
Students lab marks: marks[4][5][3]
Ex1 Ex2 Ex3
Lab1
Lab2
Lab3
Lab4
52 50 45
57 60 63
52 59 66
33 42 37
Lab5 68 68 72
Suise
Ex1 Ex2 Ex3
Lab1
Lab2
Lab3
Lab4
79 75 66
90 83 77
81 73 79
58 64 52
Lab5 93 80 85
Ex1 Ex2 Ex3
Lab1
Lab2
Lab3
Lab4
59 68 60
0 0 0
67 71 75
38 52 35
Lab5 78 86 82
Emily
ZassJerna
Ex1 Ex2 Ex3
Lab1
Lab2
Lab3
Lab4
76 80 62
60 72 48
76 80 62
60 72 48
Lab5 58 79 73
7/27/2019 Week8.pptx
8/39
2. Multidimensional Array Initializers
// nesting one-dimensional initializersint a[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 valuesint d[3][5] = { {4, 2, 1},
{8, 3, 3, 1, 6} };
CS1010 (AY2011/2 Semester 1) Week8 - 8
What happens tothe uninitializedelements?
7/27/2019 Week8.pptx
9/39
2. Multidimensional Array: Example#include
#define N 5 // number of columns in arrayintsumArray(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 arrintsumArray(intarr[][N], int rows) {
int i, j, total = 0;
for (i = 0; i < rows; i++) {for (j = 0; j < N; j++) {
total += arr[i][j];}
}return total;
}
Week8_2DArray.c
Second dimension must bespecified; first dimension isnot required.
CS1010 (AY2011/2 Semester 1) Week8 - 9
7/27/2019 Week8.pptx
10/39
3. Matrices
CS1010 (AY2011/2 Semester 1) Week8 - 10
A two-dimensional array where all rows have the samelength is sometimes known as a matrix because itresembles that mathematical concept.
A matrixA with m rows and n columns is represented
mathematically in the following manner.a1 1 a1 2 a1 n
a2 1 a2 2 a2 n
am 1 am 2
am n
Note that in implementing the matrix as an array in C,the row number and column numberstart at 0 insteadof 1.
7/27/2019 Week8.pptx
11/39
3. Demo #1: Matrix Addition (1/2)
CS1010 (AY2011/2 Semester 1) Week8 - 11
To add two matrices, both must have the same numberof 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:
021
122
020
120
012
001
101
110
021
7/27/2019 Week8.pptx
12/39
3. Demo #1: Matrix Addition (2/2)
CS1010 (AY2011/2 Semester 1) Week8 - 12
// To sum mtxA and mtxB to obtain mtxCvoidsumMatrix(float mtxA[][MAX_COL], float mtxB[][MAX_COL],
float mtxC[][MAX_COL], int row_size, int col_size){
int row, col;
for (row=0; row
7/27/2019 Week8.pptx
13/39
3. Exercise #1: Matrix Multiplication (1/2)
CS1010 (AY2011/2 Semester 1) Week8 - 13
To multiply two matrices A and B, the number ofcolumns in A must be the same as the number of rowsin 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.
7/27/2019 Week8.pptx
14/39
3. Exercise #1: Matrix Multiplication (2/2)
CS1010 (AY2011/2 Semester 1) Week8 - 14
To compute C = A B, where A, B, C are matricesci,j= (ai,1 b1,j) + (ai,2 b2,j) + . . . + (ai,n bn,j)
ci,jis sum of terms produced by multiplying the elements of Asrow iwith Bs columnj.
Example on 33 matrices:
121
132
023
120
012
001
101
110
021
Complete the prodMatrix() function in Week8_matrixOps.c
7/27/2019 Week8.pptx
15/39
4. Maze Problem (1/2)
Lets consider a maze that is represented by a two-dimensional NNinteger array.
The value of each array element is either0(representing a wall) or1 (representing a cell).
The starting and exit points in the maze are specifiedby 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 valuesrepresenting the move directions: N (for north), S(for south), E (for east), and W (for west). Each pathis defined with respect to the starting cellmaze[0][0].
CS1010 (AY2011/2 Semester 1) Week8 - 15
7/27/2019 Week8.pptx
16/39
4. Maze Problem (2/2)
Example (N= 6)
0 1 2 3 4 5
0
1
2
3
4
5
CS1010 (AY2011/2 Semester 1) Week8 - 16
7/27/2019 Week8.pptx
17/39
4. Exercise #2 (take-home): Valid Path
A path in a maze is defined to be valid if the path iswithin 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 functionint isValid (int maze[][N], char path[], int pathlen)
that takes as inputs a NNmaze and a path of lengthpathlen, and returns 1 ifpath is valid in maze; elsereturns 0.
This is a take-home exercise. Try it out before you referto the given incomplete program Week8_IsValid.c.
0 1 2 3 4 5
0
1
2
3
4
5
CS1010 (AY2011/2 Semester 1) Week8 - 17
7/27/2019 Week8.pptx
18/39
5. Testing and Debugging (1/7)
CS1010 (AY2011/2 Semester 1) Week8 - 18
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-relaystory.
Why does a program core dump?
Early computers usedtiny magneticcores (rings) asmemory cells to hold0 and 1 values.
Electro-magnet
Moveable armature
Space(Bugs may getstuck here!)
Notebook with moth fromMark II computer:
7/27/2019 Week8.pptx
19/39
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) Week8 - 19
Testing
Yes
Error?
Debug
5. Testing and Debugging (2/7)
7/27/2019 Week8.pptx
20/39
5. Testing and Debugging (3/7)
CS1010 (AY2011/2 Semester 1) Week8 - 20
Philosophical notes on program design, debugging andtesting
A good design is importantA good design results in a high quality program. A low qualitydesign cannot be debugged into high quality.
Dont 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 runcorrectly.
7/27/2019 Week8.pptx
21/39
5. Testing and Debugging (4/7)
CS1010 (AY2011/2 Semester 1) Week8 - 21
A program should be tested with various input values to makesure that it performs correctly across all inputs.
A program should make as few assumptions about the input aspossible.
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 isnot trivial.
Many of todays methods to hack into computers work by feeding
programs with unexpected inputs. This results in crashes, bufferoverflows, etc.
7/27/2019 Week8.pptx
22/39
5. Testing and Debugging (5/7)
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/failassessment.
E.g.: Mozillas Tinderbox
CS1010 (AY2011/2 Semester 1) Week8 - 22
How to test?
7/27/2019 Week8.pptx
23/39
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) Week8 - 23
5. Testing and Debugging (6/7)
7/27/2019 Week8.pptx
24/39
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) Week8 - 24
5. Testing and Debugging (7/7)
7/27/2019 Week8.pptx
25/39
Example on writing printf() statements
CS1010 (AY2011/2 Semester 1) Week8 - 25
5.1 Demo #2: using printf( )
. . .
// compute weight of a single washerrim_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 washerstotal_weight = unit_weight * qty;
// outputprintf("\nThe total weight of the batch of %dwashers is %.2f grams\n",
qty, total_weight);
. . .
Week8_WasherWeight_Printf.c
7/27/2019 Week8.pptx
26/39
5.2 Debugging with assert( )
When writing large programs, it is often useful to know that acondition or set of conditions is true.
Such a statement is known as an assertion.
The C language provides an header file andcorresponding assert macro that the programmer can use to
make assertions.
If an assertion fails, the assert macro prints a diagnosticmessage describing the condition that should have been true butwas not, and then it kills the program.
CS1010 (AY2011/2 Semester 1) Week8 - 26
#include
int my_function(int a, double b){
...assert(a = 17.1);
...}
7/27/2019 Week8.pptx
27/39
5.2 Demo #3: Using assert( )
CS1010 (AY2011/2 Semester 1) Week8 - 27
$ a.outAssertion failed: a = 17.1, file Week8_AssertDemo.c, line 11Abort (core dumped)$
#include #include
int main (void){
int a;double b;
a = 6;b = 18.0;assert(a = 17.1);
printf("The value of a is %dand the value of b is %lf\n", a, b);return 0;
}
Week8_AssertDemo.c
7/27/2019 Week8.pptx
28/39
5.3 Exercise #3: Using assert( )
CS1010 (AY2011/2 Semester 1) Week8 - 28
Caution: Do NOT use assignment statement insideassert().
Take our familiarWeek3_WashersWeight.c program andadd an assertion to make sure that the outer diameter is
larger than the inner diameter. Call it Week8_WashersWeight_Assert.c
7/27/2019 Week8.pptx
29/39
Test your programs with your own data Do not rely on CodeCrunch to test your programs!
We discussed this in week 4. There is an error in thiscode:
CS1010 (AY2011/2 Semester 1) Week8 - 29
// 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: ,, , etc. and the program works for all these.
What is missing in his testing?
5.4 Testing Thoroughly (1/3)
7/27/2019 Week8.pptx
30/39
In testing your programs thoroughly, do not forgetabout 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 isa prime), what are the boundary cases?
CS1010 (AY2011/2 Semester 1) Week8 - 30
5.4 Testing Thoroughly (2/3)
7/27/2019 Week8.pptx
31/39
It is also important to test all the paths that yourprogram control flow can take Design test data to check all paths
Example
CS1010 (AY2011/2 Semester 1) Week8 - 31
if (x != 3) {
y = 5;}else {z = z - x;
}
if (z > 1) {z = z / x;}else {z = 0;
}
if (x != 3)
y = 5 z = z - x
if (z > 1)
z = z / x z = 0
A
B
C
D
E
F
G
H
Test data:
to test path
A, B, G, H; to test pathE, F, C, D;
etc.
5.4 Testing Thoroughly (3/3)
7/27/2019 Week8.pptx
32/39
Debugger usually provides the following Stepping
Breakpoint
Watches (inspecting variables)
We will illustrate these with Gnu debuggergdb.
See videohttp://www.youtube.com/watch?v=Z6zMxp6r4mc
CS1010 (AY2011/2 Semester 1) Week8 - 32
5.5 Using a Debugger
http://www.youtube.com/watch?v=Z6zMxp6r4mchttp://www.youtube.com/watch?v=Z6zMxp6r4mc7/27/2019 Week8.pptx
33/39
5.5 Using the gdb Debugger (Demo #4)
Step 1: add theg option when compiling and linking: gcc g Week8_WashersWeight_Printf.c
Step 2: start the gdb with your program: gdb a.out
Step 3: use the different gdb commands to step throughyour program:
Break at a specific function: break function_name
Start with: break main
Run program: run (orr)
Step to the next line of code: step (ors)
List source code: list(orl)
Examine the value of a variable:print variable_name
Quit the debugger: quit
CS1010 (AY2011/2 Semester 1) Week8 - 33
Explore other gdb commands on your own!
7/27/2019 Week8.pptx
34/39
5.6 Find the Bug
Why does this program produce the wrong result?
CS1010 (AY2011/2 Semester 1) Week8 - 34
double half(double in_val)
{ return (in_val/2.0);}
#include
int main(void){
int val = 10;double result = 0.0;
result = half(val);printf("Half of %dis%lf\n", val, result);return 0;
}
Week8_Half.c
Week8_HalfMain.c
$ gcc Week8_HalfMain.c Week8_Half.c$ a.out$ Half of 10 is 10.000000
Compile it with
Wall option.
7/27/2019 Week8.pptx
35/39
5.7 Famous Programming Errors (1/2)
Mariner Bugs Out (1962)
Cost: $18.5 million
Disaster: The Mariner 1 rocket with a space probe headedfor Venus diverted from its intended flight path shortly afterlaunch. Mission Control destroyed the rocket 293 secondsafter liftoff.
Cause: A programmer incorrectly transcribed a handwritten
formula into computer code, missing a single superscriptbar. Without the smoothing function indicated by the bar, thesoftware treated normal variations of velocity as if they wereserious, causing faulty corrections that sent the rocket offcourse.
CS1010 (AY2011/2 Semester 1) Week8 - 35
7/27/2019 Week8.pptx
36/39
5.7 Famous Programming Errors (1/2)
Mars Climate Crasher (1998)
Cost: $125 million
Disaster: After a 286-day journey from Earth, the MarsClimate Orbiter fired its engines to push into orbit aroundMars. The engines fired, but the spacecraft fell too far intothe planets atmosphere, likely causing it to crash on Mars.
Cause: The software that controlled the Orbiter thrustersused imperial units (pounds of force), rather than metric units(Newtons) as specified by NASA.
CS1010 (AY2011/2 Semester 1) Week8 - 36
7/27/2019 Week8.pptx
37/39
Summary for Today
Todays most important lessons Multidimensional arrays
Testing and Debugging
Using printf() to trace your program Using assert()
Using gdb debugger
CS1010 (AY2011/2 Semester 1) Week8 - 37
7/27/2019 Week8.pptx
38/39
Announcements/Things-to-do
Revise Chapter 6 Numeric Arrays
Term Test this Saturday
8 October 2011, Saturday
See module website for details
Next weeks lecture
Recursion: Lesson 8.10
CS1010 (AY2011/2 Semester 1) Week8 - 38
7/27/2019 Week8.pptx
39/39
End of File