Search code examples
javanested-loops

Alter output that relates to nested loops in Java


import static java.lang.System.*; 
import java.util.Scanner;

public class TriangleFour{

 public static void createTriangle(int size, String let){
  String output = "";
  String x = let;
  int y = size;

  for (int z = size; z > 0; z--){
     int p = z;
     output += "\n";

     while (p > 0){
      output = output + " ";
      p--;
     }

     for (int d = size; d >= y; d--){
      output = output + x;
     }

     y--;
  }//End of for loop

  out.println(output);
 }
}

This code yields an output of the following when this statement TriangleFour.createTriangle(3, "R"); is executed in my program:

  R
 RR
RRR

I would like to modify my code to basically flip the output like this:

RRR
 RR
  R

Any help would be appreciated.


Solution

  • Here's my attempt. I slimmed down your code a bit, and renamed some variables to make it clearer.

    public static void createTriangle(int size, String let){
            for(int i=size;i>0;i--){
                int fill = i;
                int space = size-i;
                while(space>0){
                    System.out.print(" ");
                    space--;
                }
                while(fill>0){
                    System.out.print(let);
                    fill--;
                }
                System.out.println();   
            }
        }
    

    Pretty much the first for loop dictates how many rows there will be. If the size is 3, there will be 3 rows. The first while loop controls the amount of blank space per row. space is the number of blank spaces to print, and fill is the number of letters to print. You want space + fill = size every time the loop runs.

    So in the first loop, space is 0. You don't print any spaces. fill is 3, so you print 3 letters, 0 + 3 = 3.

    RRR
    

    2nd loop, space is 1, print 1 space. fill is 2, print 2 letters, 1 + 2 = 3.

    RRR
     RR
    

    3rd loop, space is 2, print 2 spaces. fill is 1, print 1 letter. 2+1=3

    RRR
     RR
      R
    

    Hope that makes sense.