dear Slagerman and melmacianalf, thanks for your suggestions. They are really useful. But I prefered the solution I got from physics forum. As I have very little changes to make.
For the completness of the thread, the below code shows the solution I used
Integer:: i, j, k, ii, jj, kk, num...