Lab 07, Esc101, 2004-05 Semester-II

Solve the following problems


Problem 1

    Write a program to sort an array of strings. For this write a function sort() which will take the array of Strings as argument and sort the array. It should not return any thing i.e. return value of sort() is 'void'. In the main() function print the sorted array of strings.   

Hint :

Use compareTo() method of the String class to compare two strings.

public int compareTo(String anotherString)
  The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal;


Problem 2

    Remove all duplicates from an array. For example, if the array has the values

        4  7  11  4  9  5  11  7  3  5

then the array should be changed to

            4  7  11  9  5  3.

Write a function which removes the duplicates and return a new array with the duplicates removed. While removing duplicates DO NOT sort the array. Print the values of the returned array in the main( ) function.
       



Problem 3

Magic Squares    An n X n matrix that is filled with numbers 1,2,3 , ... , n2  is a magic square if the sum of the elements in each row, in each row, in each column, and in the two diagonals is the same value.  For example

 
11
18
25
2
9
10
12
19
21
3
4
6
13
20
22
23
5
7
14
16
17
24
1
8
15

   Write a program to construct a magic n-by-n squares for a given n (n is odd). Here DO NOT use two-dimensional arrays.

Hint :
 
  It works only if n is odd. Place a 1 in the middle of the bottom row. After k has been placed in the (i, j) square, place k + 1 into the square to the right and down, wrapping around the borders. However, if the square to the right and down has already been filled, or if you are in the lower right corner, then you must move to the square straight up instead.

For these first write the following routines and use them in solving the problem:

   int right(int i), which will give the index to the right of a given index, with wrap around
   int down(int i) (similar to "right")
   int up(int i) (similar to "right" and "down")