Create a free account on Computer Sir Ki Class and unlock access to valuable learning resources.
Exam Paper Downloads: After registering and logging in, you can download exam question papers in PDF format to practice and prepare for your exams.
Student Support: Get assistance with your doubts, queries, and questions related to your studies. Our support is here to help you understand topics and resolve your learning difficulties.
Register today and make your exam preparation easier and more effective!
Write two separate programs to generate the following patterns using iteration(loop) statements:
(a)
1 *
2 * #
3 * # *
4 * # * #
5 * # * # *
(b)
[/code]
5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
[/code]
Answer:
(a)
import java.util.Scanner;
public class Pattern1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter n: ");
int n = scanner.nextInt();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
if (j % n == 1) {
System.out.print("* ");
} else {
System.out.print("# ");
}
}
System.out.println();
}
}
}
(b)
import java.util.Scanner;
public class Pattern2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter n: ");
int n = scanner.nextInt();
for (int i = n; i >= 1; i--) {
int num = n;
for (int j = 1; j <= i; j++) {
System.out.print(num + " ");
num--;
}
System.out.println();
}
}
}
C. Sir| Created: 16-Apr-2019 | Updated: 16-Apr-2019|ICSE2015