StrugglingCSmajor
StrugglingCSmajor

Reputation: 5

How to manipulate nested for loops

String[][] board = [a,b,c,d]
                   [e,f,g,h];   

for(int i=0; i<board.length; i++){
    String temp = "";
    for(int j=0; j<board[i].length; j++){
        temp = temp+board[i][j];
        System.out.println(temp);
    }
}

Current output

a
ab
abc
abcd
e
ef
efg
efgh

I want the output to look like

a
ab
abc
abcd
b
bc
bcd
c
cd
d
e
ef
efg
efgh
f
fg
fgh
g
gh
h 

How would I do this?

Upvotes: 0

Views: 366

Answers (1)

nio
nio

Reputation: 5289

You need a third nested for loop to do that:

String[][] board = [a,b,c,d]
                   [e,f,g,h];   

// i - for each row
for(int i=0; i<board.length; i++){

    // j - start from this column in a row
    for(int j=0; j<board[i].length; j++){
        String temp = "";        
        // put all columns right to the j and including together
        for(int k=j;k<board[i].length; k++) {
            temp = temp+board[i][k];
            System.out.println(temp);
        }
    }
}

Upvotes: 1

Related Questions