Reputation: 73
So for an assignment I was tasked with creating a pattern using loops that out puts something like this
a
B A
c b a
D C B A
e d c b a
F E D C B A
g f e d c b a
where the the input n is = to the number of rows printed.
so far I know I have to print the spaces first and then print the values
I have the code for the spaces so far the asterisks are just so I can see if I had the right amount of spaces.
import java.util.Scanner;
public class HW0407 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
//int x = 7;
System.out.println("Pattern C");
int a = 0;
int b = x - 2;
String s1 = "zyxwvutsrqponmlkjihgfedcba";
String s2 = "ZYXWVUTSRQPONMLKJIHGFEDCBA";
for (int row = 0; row < x; row++) {
for (int col = 0; col <= b; col++) {
System.out.print(" " + "*");
if (col == b) {
System.out.println();
}
}
b = b - 1;
}
The string values are there because I had an Idea to make it so where I had an if statement like so
if(row % 2 == 0){
string str = s2.substring(25 - row, 25);
}
else{
string str = s1.substring(25 - row, 25);
}
I want to figure out where to start, should I make a new loop, a nested loop within the first for loop or place it in the already created nested loop.
I'm sorry if I make some weird mistakes, I'm still fairly confused on loops since I was just introduced to it. I had suggestions to use arrays and multiple methods but I am not allowed to use those since they were not covered subjects yet.
Upvotes: 2
Views: 409
Reputation: 1077
This is my solution:
int x = 6;
String letters = "abcdefghijklmnopqrstuvwxyz";
char output = 0;
for (int i = 0; i < x; i++) {
for(int j = x; j > 0; j--) {
if(j > i + 1) {
output = ' ';
} else {
output = letters.charAt((j - 1) % letters.length());
}
if (i % 2 == 1) output = Character.toUpperCase(output);
System.out.print(" " + output + " ");
}
System.out.println();
and output:
a
B A
c b a
D C B A
e d c b a
F E D C B A
Upvotes: 0
Reputation: 885
You only need 2 loops that iterate through the rows and columns (which you have).
As you iterate through the columns, use the following logic:
You seem to have figured out how to tell whether you should be printing capital or lowercase letters, so you should have all you need to write up the full solution.
Upvotes: 2