Thursday, September 13, 2012

Homework 3

Do homework 1 over, but with recursion instead of a loop. First write the function
static void printrow(int i,int j)
This function prints the characters of the i-th row, starting at column j. If j is 8, we have printed all the characters already. Just print a newline and quit. If j < 8, print one characters. Use the numbers i and j to decide between 0 and X, just as before. Then the function calls itself. The first argument stays the same, but the second argument goes up by one -- because we are moving to the next column. Now write the function
static void printall(int i)
This function prints the rows from row i to the end. If i=8 we are done -- do nothing. If i < 8, use the function printrow to print the i-th row (start at column 0). Then call printall again, with the row number increased by one. Your main function just calls printall(0).

Possible Solution:

public class board
{

    public static void main(String[] args)
    {
        printall(0);
    }
  
    static void printrow(int i,int j)
     {
        if (j == 8)
            System.out.println();
       else
       {
            if(i % 2 == 1 || j % 2 == 1)
                System.out.print('X');
            else
                System.out.print('O');  
                       
            printrow(i, ++j);
          }
    }

    static void printall(int i)
    {
        if (i == 8)
            System.out.println("Done");
       else
       {
           printrow(i, 0);        
           printall(++i);
       }
    }  
  
}