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();
}
}
}
CodePudding user response:
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
##
# #
# #
# #
# #
# #
CodePudding user response:
In each line, Instead of printing c # characters, you print one # character, then c-2 space characters, then another # character.
CodePudding user response:
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:
##
# #
# #
# #
# #
# #
CodePudding user response:
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)
##
# #
# #
# #
# #
# #
# #
# #
# #
