In: Computer Science
in java
Write a program that will print the following output
1 1 2 1 1 2 4 2 1 1 2 4 8 4 2 1 1 2 4 8 16 8 4 2 1 1 2 4 8 16 32 18 8 4 2 1
class numberSeries
{ /***The given series is in format 1 121 12421 1248421 etc
* Let n be the highest value in loop then the outer loop will execute n th root of 2 plus 1 times
* Here n=32 nth root of 2=5 so outer loop will execute 5+1=6 times
* There are 2 inner loops one for printing numbers in ascending order
* and one for printing numbers in descending order***/
public static void main(String[] args)
{
//Declaring loop variables i and j and initialize i as 1
int i=1,j;
//Loop to print n terms of pattern
while(i<=32)
{
//Inner loop to print numbers in increasing order
//After execution of each time j changes to j*2
for(j=1;j<=i;j=j*2)
//Display value of j
System.out.print(j+" ");
//Inner loop to print numbers in decreasing order
//After execution of each time j changes to j/2
// starting value of j is i/2
for(j=i/2;j>=1;j=j/2)
System.out.print(j+" ");
i=i*2;
}
}
}
OUTPUT
1 1 2 1 1 2 4 2 1 1 2 4 8 4 2 1 1 2 4 8 16 8 4 2 1 1 2 4 8 16 32 16 8 4 2 1