Search code examples
javanested-loops

nested loops in java


I'm trying to make a diagonal line that should look like this:

*
 *
  *
   *
    *
     *
      *
       *
        *

I have to use nested loops and I am using a program called Java ready to program which uses java. Here is my code which is close but I can't seem to figure out how to make it diagonal.

// The "E006" class.
import java.awt.*;
import hsa.Console;

public class E006
{
    static Console c;           // The output console

    public static void main (String[] args)
    {
        c = new Console ();
        int i, j;
        for(i = 1; i <= 1; i++)
            for(j = 1; j < 10; j++)
                c.println("*");

    } // main method
} // E006 class

I'm sure it is something very simple, but I am just starting out so I'm not too sure what to do. I must use nested loops (a loop inside a loop).

It would be a great help if someone could help me with this.


Solution

  • This sounds like a school assignment, so I'm not going to solve it for you. Here are some hints:

    • You need to print spaces, not just asterisks
    • You need to print more spaces on each line
    • Your first for loop only executes once, what good is a loop that happens once
    • Your code would be easier to read with better indentation. Use brackets around your for loops even when they aren't required.

    int i, j;
    for(i = 1; i <= 1; i++){
        for(j = 1; j < 10; j++){
            c.println("*");
        }
     }