Search code examples
javaloopstriangle

Why is my program printing the next line at a location i didnt ask for?


Basically i have to print 2 traingles, top up upside down, buttom one upside up. They are both the same legnth, my program works fine yet for some reason my second triangle gets slighty tilted to the right. Can anyone please explain to me how to fix and why this bug happens?

public static void main(String[] args) {
        Scanner s = new Scanner(System.in);

        System.out.println("Enter number");
        int num = s.nextInt();
        
        for (int i = 0; i < num; i++) {
            for (int j = num; j > i; j--) {
                System.out.print("*");
                System.out.print(" ");
            }
            
            System.out.println();


            for (int k = 0; k <= i; k++) {
                System.out.print(" ");
            }
        }

        // second part
        
        
        for (int i = 0; i < num; i++) {
            for (int j = 0; j <= i; j++) {
                System.out.print("*");
                System.out.print(" ");
            }
            
            System.out.println();
            
            for (int k=num; k>i; k-=2) {
                System.out.print(" ");
            }
        }
    }
}

* * * 
 * * 
  * 
   * 
  * * 
 * * * 

Solution

  • A couple of small tweaks:

    • in the end of the first outer for loop
    • in the second outer for-loop at the end

    See code comments below

            for (int i = 0; i < num; i++) {
                for (int j = num; j > i; j--) {
                    System.out.print("*");
                    System.out.print(" ");
                }
                
                System.out.println();
    
    
                for (int k = 0; k < i; k++) { // stop condition changed
                    System.out.print(" ");
                }
                if (i < num -1) { // this was added
                    System.out.print(" ");
                }
            }
    
            // second part
            
            for (int i = 0; i < num; i++) {
                for (int j = 0; j <= i; j++) {
                    System.out.print("*");
                    System.out.print(" ");
                }
                
                System.out.println();
                
                for (int k=num-1; k>i+1; k-=1) { // stop condition change
                    System.out.print(" ");
                }
            }