-1

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(" ");
            }
        }
    }
}

* * * 
 * * 
  * 
   * 
  * * 
 * * * 
dudex198
  • 25
  • 5

1 Answers1

1

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(" ");
            }
        }
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • Thank you very much, this might be an unrelated question, but is my approach to this question in general okay? or is this very unefficient or unsmart. Thank you very much again! Happy holidays – dudex198 Nov 28 '21 at 15:19
  • @dudex198 there are different approaches and I don't know if one is better than the other. Usually it's a matter of personal preferences. I don't think that efficiency is relevant here. – Nir Alfasi Nov 28 '21 at 15:47