You are on page 1of 39

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
CS1010 (AY2011/2 Semester 1)
References:
Chapter 6 Numeric Arrays
Week8 - 2
Week 8: Outline (1/2)
1. Week 7 Exercise #2: Set Containment
2. 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
Week 8: Outline (2/2)
5. 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) Week8 - 4
1. Week 7 Exercise #2: Set Containment
Consider two arrays, arrA and arrB, of int values, where their
sizes are sizeA and sizeB respectively.
Write a function
int 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 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) Week8 - 5
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
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 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) Week8 - 6
0 1 2 3 4
0
1
2
2
9
16
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
Zass
Jerna
Ex1 Ex2 Ex3
Lab1
Lab2
Lab3
Lab4
76 80 62
60 72 48
76 80 62
60 72 48
Lab5 58 79 73
2. Multidimensional Array Initializers
// nesting one-dimensional initializers
int 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 values
int d[3][5] = { {4, 2, 1},
{8, 3, 3, 1, 6} };
CS1010 (AY2011/2 Semester 1) Week8 - 8
What happens to
the uninitialized
elements?
2. Multidimensional Array: Example
#include <stdio.h>
#define N 5 // number of columns in array
int sumArray(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
int sumArray(int arr[][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 be
specified; first dimension is
not required.
CS1010 (AY2011/2 Semester 1) Week8 - 9
3. Matrices
CS1010 (AY2011/2 Semester 1) Week8 - 10
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.
a
1 1 ,
a
1 2 ,
.
a
1 n ,
a
2 1 ,
a
2 2 ,
.
a
2 n ,
.

.
a
m 1 ,
a
m 2 ,
.
a
m n ,
Note that in implementing the matrix as an array in C,
the row number and column number start at 0 instead
of 1.
3. Demo #1: Matrix Addition (1/2)
CS1010 (AY2011/2 Semester 1) Week8 - 11
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
c
i,j
= a
i,j
+ b
i,j

Example on 33 matrices:
|
|
|
.
|

\
|
=
|
|
|
.
|

\
|

+
|
|
|
.
|

\
|
0 2 1
1 2 2
0 2 0
1 2 0
0 1 2
0 0 1
1 0 1
1 1 0
0 2 1
3. Demo #1: Matrix Addition (2/2)
CS1010 (AY2011/2 Semester 1) Week8 - 12
// To sum mtxA and mtxB to obtain mtxC
void sumMatrix(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<row_size; row++)
for (col=0; col<col_size; col++)
mtxC[row][col] = mtxA[row][col] + mtxB[row][col];
}
For complete program see
Week8_matrixOps.c
3. Exercise #1: Matrix Multiplication (1/2)
CS1010 (AY2011/2 Semester 1) Week8 - 13
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.
3. Exercise #1: Matrix Multiplication (2/2)
CS1010 (AY2011/2 Semester 1) Week8 - 14
To compute C = A B, where A, B, C are matrices
c
i,j
= (a
i,1
b
1,j
) + (a
i,2
b
2,j
) + . . . + (a
i,n
b
n,j

)

c
i,j
is sum of terms produced by multiplying the elements of As
row i with Bs column j.
Example on 33 matrices:
|
|
|
.
|

\
|

=
|
|
|
.
|

\
|

|
|
|
.
|

\
|
1 2 1
1 3 2
0 2 3
1 2 0
0 1 2
0 0 1
1 0 1
1 1 0
0 2 1
Complete the prodMatrix() function in Week8_matrixOps.c
4. Maze Problem (1/2)
Lets 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) Week8 - 15
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
4. Exercise #2 (take-home): Valid Path
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 function
int isValid (int maze[][N], char path[], int pathlen)
that takes as inputs a N N maze 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
0
1
2
3
4
5
CS1010 (AY2011/2 Semester 1) Week8 - 17
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 term
bug existed before
the moth-in-a-relay
story.



Why does a program core dump?
Early computers used
tiny magnetic
cores (rings) as
memory cells to hold
0 and 1 values.
Electro-magnet
Moveable armature
Space
(Bugs may get
stuck here!)
Notebook with moth from
Mark II computer:
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)
5. Testing and Debugging (3/7)
CS1010 (AY2011/2 Semester 1) Week8 - 20
Philosophical notes on program design, debugging and
testing
A good design is important
A good design results in a high quality program. A low quality
design cannot be debugged into high quality.
Dont optimize for speed too early
It 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) Week8 - 21
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 todays 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)
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.: Mozillas Tinderbox
CS1010 (AY2011/2 Semester 1) Week8 - 22
How to test?
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)
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)
Example on writing printf() statements
CS1010 (AY2011/2 Semester 1) Week8 - 25
5.1 Demo #2: using printf( )
. . .

// 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);

. . .
Week8_WasherWeight_Printf.c
5.2 Debugging with assert( )
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.
CS1010 (AY2011/2 Semester 1) Week8 - 26
#include <assert.h>

int my_function(int a, double b)
{
...
assert(a <= 5 && b >= 17.1);
...
}
5.2 Demo #3: Using assert( )
CS1010 (AY2011/2 Semester 1) Week8 - 27
$ a.out
Assertion failed: a <= 5 && b >= 17.1, file Week8_AssertDemo.c, line 11
Abort (core dumped)
$
#include <stdio.h>
#include <assert.h>

int main (void)
{
int a;
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
5.3 Exercise #3: Using assert( )
CS1010 (AY2011/2 Semester 1) Week8 - 28
Caution: Do NOT use assignment statement inside
assert().
Take our familiar Week3_WashersWeight.c program and
add an assertion to make sure that the outer diameter is
larger than the inner diameter.
Call it Week8_WashersWeight_Assert.c
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 this
code:
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: <3,5,9>,
<12,1,6>, <2,7,4>, etc. and the program works for all these.
What is missing in his testing?
5.4 Testing Thoroughly (1/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) Week8 - 30
5.4 Testing Thoroughly (2/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
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:
<x=0, z=1> to test path
A, B, G, H;
<x=3, z=3> to test path
E, F, C, D;
etc.
5.4 Testing Thoroughly (3/3)
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) Week8 - 32
5.5 Using a Debugger
5.5 Using the gdb Debugger (Demo #4)
Step 1: add the g 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 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
CS1010 (AY2011/2 Semester 1) Week8 - 33
Explore other gdb commands on your own!
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 <stdio.h>

int main(void)
{
int val = 10;
double result = 0.0;

result = half(val);
printf("Half of %d is %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.
5.7 Famous Programming Errors (1/2)
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.

CS1010 (AY2011/2 Semester 1) Week8 - 35
5.7 Famous Programming Errors (1/2)
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 planets 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.
CS1010 (AY2011/2 Semester 1) Week8 - 36
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
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
End of File
CS1010 (AY2011/2 Semester 1) Week8 - 39

You might also like