For a homework assignment, I need help with generalizing the code for printing the following pattern.
A
B C
D E F
G H I J
The problem was coding the spaces between the alphabets.
This is what i came up with, but it is just for the first 4 lines of the pattern.
(Sorry i have poor formatting skills >.>)
int r = 65;
char m ;
int count=0;
for(int i = 4;i>0;i--)
{
for( int j = i;j>0;j--)
{System.out.print(" ");}
for(int j = 4-i;j>=0;j--)
{
count++;
m=(char)r;
if(count == 3||count == 6||count == 8 || count == 11|| count == 13|| count ==15)
{
System.out.print(" ");r--;
}
else
System.out.print(m);r++;
}
for(int j = 4-i;j>0;j--)
{
count++;m=(char)r;
if(count == 3||count == 6||count == 8 || count == 11|| count == 13|| count ==15)
{
System.out.print(" ");r--;
}
else
System.out.print(m);r++;
}
System.out.println("");
}
thanks to Gene for the explanation, i did some editing and this is what i came up with.
int r = 65;
char m ;
for(int i = 4;i>0;i--)
{
for( int j = i;j>0;j--)
{System.out.print(" ");}
for(int j = 4-i;j>=0;j--)
{
m=(char)r;
System.out.print(m+" ");
r++;
}
System.out.println("");
}
Writing loops is all about using math (usually simple math) to describe one iteration in terms of loop indicies.
Let
Nbe the number of rows soi=0,1,...N-1are their indices.First, your example shows that row
ihasN-i-1leading spaces. Let’s check this. For rowi=N-1we get zero and fori=0we getN-1. In your example thei=0case is 3. This agrees with the drawing, so we’re looking good.The second part is that there are
i+1characters per row. All but the last has a following space. The last has a following newline.Finally, we can get the correct letter by just starting at A and incrementing each time we print a new one.
So now we’re ready to write code:
This is untested but ought to work.