Trying to get an "if" statement to work in a "for loop".

• April 1st, 2013, 09:25 PM
JAKATAK
Trying to get an "if" statement to work in a "for loop".
This isn't homework, it's a question in a textbook practice example that I can't seem to get right.
I got it to work with 3 for loops, but I don't know how to get it to work with 2 for loops and a if statement.
Can someone show me how to get the following :

Code Java:

```  /* *Write a nested for loop to display the following matrix: *1 2 3 4 * 1 2 3 * 1 2 * 1 * basically they just increase by 2 spaces every iteration it seems like. */     //this is as much of a layout of my code i can do   for (int i = 1; i <= 4; i++) { for (int j = 1; j <= 5 - i; j++) { //i have a feeling the if statement should go after the 2nd for loop, but i can't get it to work. System.out.print(j + " "); } System.out.println(); }```
• April 1st, 2013, 10:16 PM
Junky
Re: Trying to get an "if" statement to work in a "for loop".
Why do you need an if statement? You only need 2 loops. Outer loop controls the number of rows. For each row print x number of spaces then have the inner loop print the numbers.

--- Update ---

On reflection I assume they want you to use the if statement to decide if a space or a number should be printed.
• April 1st, 2013, 11:24 PM
JAKATAK
Re: Trying to get an "if" statement to work in a "for loop".
I just assumed there needed to be an if statement because I couldn't get each row to increase by " " (2 spaces) each time. How would you increase it by 2 spaces each iteration then? normally this would just print 1 2 3 4 for each row and have 4 columns, but instead its decreasing by 1 number (which i did by j<=5-i) and also shifting to the right every iteration which i can't figure out how to do. Is there a way to do that with just 2 for loops?
• April 1st, 2013, 11:44 PM
Mitch1337
Re: Trying to get an "if" statement to work in a "for loop".
I got this to work using a place holder that would increment each iteration of the outer for-loop.

Code java:

`...`
• April 2nd, 2013, 12:16 AM
copeg
Re: Trying to get an "if" statement to work in a "for loop".
@Mitch, this is a problem solving exercise - please refrain from spoonfeeding (for reasons why, please read http://www.javaprogrammingforums.com...n-feeding.html )

@JAKATAK, try writing this out on paper. If you use nested loops, does one of the loop value account for the number of spaces or space offset?