简体   繁体   中英

Infinite loop when printing an N x N table

Consider the following Java program:

public class RelativelyPrime {
    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]); // Dimensions of grid
        int i, j;
        int r; // Remainder when i is divided by j

        for (i = 1; i <= N; i++) {
            for (j = 1; j <= N; j++) {
                do { // Using Euclidean algorithm
                   r = i % j;
                   i = j;
                   j = r;
                } while (r > 0);
                if (i == 1) System.out.print("*");
                else System.out.print(" ");
            }
            System.out.println();
        }
    }
}

This program prints an N x N table (or matrix, if you like) where N is a command-line argument.
The (i, j)-entry is a * if i and j are relatively prime, or a single whitespace if they are not relatively prime. When I run the program by entering, for instance, java RelativelyPrime 3 it endlessly prints * . Why is this happening?

You changed i and j in the while loop.

    for (i = 1; i <= N; i++) {
        for (j = 1; j <= N; j++) {
            int ii = i, jj = j;
            do { // Using Euclidean algorithm
               r = ii % jj;
               ii = jj;
               jj = r;
            } while (r > 0);
            if (ii == 1) System.out.print("*");
            else System.out.print(" ");
        }
        System.out.println();
    }

This is where using the debugger would have helped you solve the problem.

Inside your loops, you alter both i and j which means they never reach N and thus you have an infinite loop.

I suggest you not alter these variables but instead use two new variables, ideally with meaningful names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM