Write a program in java to print this pattern:
A
2 B
C C C
4 D 4 D
E E E E E
no spam
Answers
SOLUTION:
The given problem is solved using language - Java.
public class Pattern {
public static void main(String args[]) {
int rows=5,i,j;
for(i=1;i<=rows;i++) {
for(j=1;j<=i;j++) {
if(i%2==1)
System.out.print((char)(64+i)+" ");
else {
if(j%2==0)
System.out.print((char)(64+i)+" ");
else
System.out.print(i+" ");
}
}
System.out.println();
}
}
}
LOGIC:
Logic is very simple. When the value of the variable 'i' is odd, only characters are printed. When the value of 'i' is even, the row number and the respective character is displayed.
See attachment for output.
Answer:
Program:-
public class Program
{
public static void main(String args[])
{
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
if(i%2!=0)
System.out.print((char)(i+64)+" ");
else if(i%2==0)
{
if (j%2==0)
System.out.print((char)(i+64)+" ");
else
System.out.print(i+" ");
}
}
System.out.println();
}
}
}