Write a program in Java to generate the following pattern using nested loops.
1
3 1
5 3 1
7 5 3 1
9 7 5 3 1
Answers
Note:
I have attached the program and it's compilation, with the output as an attachment. Have a look at it. I have compiled the code on java editor, and the code is perfect!
Program:
import java.util.Arrays;
import java.util.Scanner;
public class HelloWorld
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.println("No of rows :");
int n = sc.nextInt();
//n refers the no.of rows
int [] oddarray = new int[n];
int num=1;
int ins=0;
// Loop : Inserting n odd numbers into the array as we need n numbers to form the pattern
while(ins!=n)
{
if(num % 2 != 0)
{
oddarray[ins] = num;
ins++;
}
num++;
}
// Nested loops : Outer loop deals with the rows whilethe inner one deals with the elements to be printed in the row.
for(int i=0; i<5; i++)
{
for(int j=i;j>=0;j--)
{
System.out.print(oddarray[j]+" ");
}
System.out.println();
}
}
}
Input:
No of rows : 5
Output:
1
3 1
5 3 1
7 5 3 1
9 7 5 3 1
Explanation:
Here, I have made the program in such a way that the user needs to give the input, based on the no.of rows he needs to create the pattern. Dynamic! Once, the user inputs the size of the array, which says the no.of elements that are gonna include in the pattern, we need to create an array with that size.
Once an array is created, we insert the odd elements into the array based on the size mentioned, using a loop. Once the needed odd numbers are inserted into the array, the loop terminates.
Now, to print the pattern using the elements in the array, we create an outer loop that deals with the rows and an inner loop that deals with the elements to be printed in the loop. That's it! You can see the pattern you wish for, getting printed.
Hope it helps! If yes, Leave a smile over here :)