Tracking algorithms with pencil and paper

From Applied Science
Revision as of 18:42, 16 April 2022 by Wikiadmin (talk | contribs)

In the introduction to computing course the teacher might write a lot on the blackboard and, the students, a lot on paper. The computer is left for homework, some of which, called program exercises, are graded and counted for the grade at the end of the semester. Some universities include practical classes in laboratories, some does not. The tests are not computer based, but in a old-fashioned way with paper and pencil. The teacher should not ask students to write a full program to solve a complex problem with around 200 lines of code in a test, but rather smaller problems such as reading a matrix, printing numbers, basic arithmetic, etc.

In essence, reading and fixing algorithms on paper is making your brain function as a debugger.


  • What good does an algorithm on paper have if there is no compiler?

Before a movie director shoots a film, an artist should have sketched the scene. Before an architect builds a 3D model of a house, a drawing on paper should have been done. Algorithm on paper is meant for you to focus on logic and not be "spoiled" by compiler warnings and errors. The compiler identifies syntax errors, but is unable to detect wrong logic. If you were expecting your program to print "Hello World" ten times, but the program printed nine, the compiler cannot detect what is wrong.

To execute algorithm on paper is the same as tracking the algorithm line by line. One way for us to do that is to use a table, where we place variables on columns and the values of each var on rows, each new row counts as a new iteration. That is a good technique for learning how algorithms made by other people function. If the algorithm is well-documented and well-written it's easy to catch how it does something. Else, to track it on paper is the only way of understanding what and how it does something.

A manual and coarse way of debugging a program is to place a printf() call before and after each variable, then you'll be able to track every variable in the program.


What comes below assumes that you know how to declare variables, know how to use loops, know C's syntax and how to compile a code
  • A typical "track this algorithm" problem. Write down what is going to be printed by program below:
  1. include <stdio.h>int main() {

/* USN = University Student Number */
int USN, i = 1, digit, reverse = 0, count;

printf("Type your USN: ");

scanf("%d", &USN);
count = USN;

while (count != 1) {

count = count / 10;

i = i * 10;

}

while (i != 0) {

digit = USN % 10;
reverse = reverse + digit * i;
printf("%d * ", reverse);
if (digit % 2 == 0) printf("even\n");

else printf("odd\n");
USN = USN / 10;

i = i / 10;

}

return 0;
}

Let's track it. Suppose the input is USN = 1234567.

first while	 
count	 i	loop's iterations
1234567	 1	 0 (before going in)
123456	 10	 1
12345	 100	 2
...	 ...	 ...
1	 1000000	 6