Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

TwoDarray or loop

Hi ,
any one could help me on this ,i want it start from one until 30 thanks

import java.util.Scanner;
public class inte
{

public static void main(String[] args)
{
final int MAX_ROWW = 5;
final int MAX_STARR = 20;

int i,k;

for(i=1; i <= 30 ;i++)
{

for(k=1; k <= MAX_ROWW; k++)
{


System.out.print(String.format ("%5d",i++));
}

System.out.println();

}

}

}



the out come is as follow my question where is 6 ,10 ,
why ?
any help please
1 2 3 4 5
7 8 9 10 11
13 14 15 16 17
19 20 21 22 23
25 26 27 28 29
[853 byte] By [bikar] at [2007-11-11 8:04:18]
# 1 Re: TwoDarray or loop
System.out.print(String.format ("%5d",i++));
You're incrementing the loop variable within the (nested) loop. Not a good thing to do as it can make the logic very hard to follow. Even worse in your case, it has led to an unwanted side effect. Every time the inner loop completes you are going to increment the outer loop variable twice - once in the code I have posted, and again in the outer loop control logic.

I think you're going to have to rethink your algorithm for doing this. There's no need to have more than one loop, you can do it with one loop and have a variable that counts and determines when a new line is needed.
mikeBarr81 at 2007-11-11 22:36:32 >
# 2 Re: TwoDarray or loop
Hi, I did as i you give me some hints but still i have some problem , the out come start from 0 even i want to start from 1.
any help now please ?
thanks

import java.util.Scanner;
public class NestedPanels
{

public static void main(String[] args)
{
int[][] table = new int[20][5];
// Load the table with values
for (int row=0; row < table.length; row++)
for (int col=0; col < table[row].length; col++)

table[row][col] = row * 5 + col;

// Print the table
for (int row=0; row < table.length; row++)
{

for (int col=0; col < table[row].length; col++)
System.out.print (table[row][col] + "\t");
System.out.println();
}

}

}


out come
0 1 2 3 4
5 6 7 8 9
...
bikar at 2007-11-11 22:37:32 >