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