Printing program state

PGSS Computer Science Core

In debugging a program, it frequently helps to be able to print aspects of the program's current state. You can do this in Java using the System.out.println function.

To print the state, you give to System.out.println information you want to print. For example, if you wanted to print i and n % i for each iteration of the loop of PrimeTestAll, you would insert a call to System.out.println as follows.

    public static int PrimeTestAll(int n) {
        int i;
        
        // small numbers are never prime.
        if(n < 2) {
            return 0;
        }
        
        // try all i between 2 and sqrt(n)
        for(i = 2; i * i <= n; i = i + 1) {
            System.out.println("i: " + i + "; n % i: " + (n % i));
            if(n % i == 0) {
                // then i divides n
                return 0;
            }
        }
        return 1;
    }

(The double-quotes surround a string of characters to be printed; you can append decimal representations of numbers to a string using the '+' operator. System.out.println will also accept characters, integers, and doubles as parameters.)

If you insert lines to print information about the current state, be sure to remove them before submitting your program for evaluation.