Question
Write two separate programs to generate the following patterns using iteration(loop) statements:
(a)
*
* #
* # *
* # * #
* # * # *
(b)
5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class Program5A
{
public static void main(String[] args)
{
int no=0,i=0,j=0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
no = sc.nextInt();
for (i = 1; i <= no; i++)
{
for (j = 1; j <= i; j++)
{
/* if j is even then print '#' else print '*' */
if (j % 2 == 0)
{
System.out.print("# ");
}
else
{
System.out.print("* ");
}
}
System.out.println();
}
}
}
import java.util.Scanner;
public class Program5b
{
public static void main(String[] args)
{
int no=0,temp=0,i=0,j=0;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number: ");
no = scanner.nextInt();
for (i = no; i >= 1; i--)
{
temp = no;
for (j = 1; j <= i; j++)
{
System.out.print(temp + " ");
temp--;
}
System.out.println();
}
}
}