Advertisements
Advertisements
Question
Write a program to display the pattern:
- A B C D E
B C D E
C D E
D E
E - A
B C
D E F
G H I J
K L M N O - A B C D E
A B C D A
A B C A B
A B A B C
A A B C D
Code Writing
Solution
// Except Pattern2, All other patterns can be reused
//to accommodate other strings by changing the value of the String variable
class SQ21{
public static void main(String hg[])
{int i, j, len;
String s = "ABCDE";
s = s.trim(); // remove leading and trailing spaces
len = s.length();
System.out.println("\n***Pattern1***");
for (i = 0; i < len; i++) [rows
{ for (j = i; j < len; j++) // columns
System.out.print(" " + s.charAt(j));
System.out.println();
}
System.out.println("\n***Pattern2***");
int p = 65; // capital A
for (i = 0; i < 5; i++) // rows
{ for (j = 0; j <= i; j++) // columns
{System.out.print(" " + (char)p);
p++; // increment the ascii value
}
System.out.println();
}
System.out.println("\n***Pattern3***"); // before diagonal
for (i = len; i > 0; i--)
{ for (j = 0; j < i; j++)
System.out.print(" " + s.charAt(j));
for (int m = 0; m < len-i; m++) // after diagonal
System.out.print(" " + s.charAt(m));
System.out.println();
}}}
shaalaa.com
Is there an error in this question or solution?