How remove or skip spaces in nested loop patterns

I have this little code that is to create the output below:

##
# #
#  #
#   #
#    #
#     # <- Wanted output


   ##
   ###
   ####
   #####
   ######
   ####### <- Current output

How do I add spaces and remove "#"? The pattern is six long (straight down) increasing by one each line but only having two "#" per line all the way down.

Code:

import java.util.Scanner;

public class Pattern {
    public static void main(String[] args) {
        final int BASE_SIZE = 6;

        for (int r = 0; r < BASE_SIZE; r++){

            for (int c = 0; c < (r+2); c++){
            System.out.print("#");
            }
            System.out.println();
        }
    }
}

3 answers

  • answered 2022-01-23 02:41 Gurkirat Singh Guliani

    You just have to update your inner for loop where you print empty spaces if the column value is not first(c=0) and last ( c=r+1) for each row.

    public class Pattern {
        public static void main(String[] args) {
            final int BASE_SIZE = 6;
    
            for (int r = 0; r < BASE_SIZE; r++){
    
                for (int c = 0; c < (r+2); c++){
                    if ( c == 0 || c == r+1)
                System.out.print("#");
                    else 
                        System.out.print(" ");
                }
                System.out.println();
            }
    
        }
    }
    

    and the output is like this:

    ##
    # #
    #  #
    #   #
    #    #
    #     #
    

  • answered 2022-01-23 02:41 WJS

    You need to print one hash mark, print spaces up to current r value, then print final hash mark.

    final int BASE_SIZE = 6;
    
    for (int r = 0; r < BASE_SIZE; r++){
        System.out.print("#");
        for (int i = 0; i < r; i++) {
            System.out.print(" ");
        }
        System.out.println("#");
    }
    

    prints

    ##
    # #
    #  #
    #   #
    #    #
    #     #
    

  • answered 2022-01-23 02:45 William

    This works perfectly and you can specify the side size.

    public static void wantedPatern (int side) {
        for (int i = 0; i < side; i++){
            System.out.print("#");
            for(int k = -i; k < 0; k++){
                System.out.print(" ");
            }
            System.out.println("#");
        }
    }
    
    

    Output with side 9 wantedPatern(9)

    ##
    # #
    #  #
    #   #
    #    #
    #     #
    #      #
    #       #
    #        #
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum