Q: Inverted right triangle using while loop I need to print this triangle using while loop :

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

My code is :
int a=0;
StringBuilder str=new StringBuilder();
str.append("*");
while(a<=5){
    System.out.println(str);
    str.append("*");
    a=a+1;
}

And its output is :

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


A: You are doing this backwards. You should start your string builder like '*****' and then replace (not append) the start with a space character. Here is an alternative using the method setCharAt:
public class TrianglePrinter {
    public static void main(String[] args) {
        printDescendingTriangle(5);
    }

    private static void printDescendingTriangle(final int a) {
        StringBuilder str = initialStringBuilder(a);
        int i = 0;

        while(i < a){
            System.out.println(str);
            str.setCharAt(i,' ');  // here I'm replacing the '*' with a space ' ' character
            i++;
        }
    }

    // To initialize the StringBuilder with the ***** characters with the specified length
    private static StringBuilder initialStringBuilder(int a) {
        StringBuilder sb = new StringBuilder(a);

        for (int i = 1; i <= a; i++){
            sb.append("*");
        }
        return sb;
    }
}

Output:
*****
 ****
  ***
   **
    *

