write a nested loop that prints the following output 1 1 2 1 1 2 4 2 1 1 2 4 8 4
ID: 3623252 • Letter: W
Question
write a nested loop that prints 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 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
here is wat i did
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic herepublic class Pyramid{
//declare variables
int row; // row number
int space; // white space
int column; // column number
int n; // degree of power
int i; // used in for loop
int a; // result obtained by pow
for (row = 0; row <= 7; ++row) {
column = (7 - row) * 4;
n = 0;
for (space = column; space > 0; --space) {
System.out.println(" ");
}
for (i = 0; i <= row; ++i) {
a = pow(2, n);
System.out.printf("%4d", a);
++n;
}
--n;
--n;
for (i = 0; i < row; ++i) {
a = pow(2, n);
System.out.printf("%4d",a);
--n;
}
System.out.println("");
}
}
public static int pow(int s,int m)
{
int wer;
wer = m^(s);
return wer;
}
}
Explanation / Answer
please rate - thanks
hope you don't mind. I changed your pow (^ is not standard)
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic herepublic class Pyramid{
//declare variables
int row; // row number
int space; // white space
int n; // degree of power
int i; // used in for loop
int a; // result obtained by pow
int rows=8;
for (row = 0; row < rows; ++row) {
n = 0;
for (space = 4*(rows-row); space > 0; --space) {
System.out.print(" ");
}
for (i = 0; i <= row; ++i) {
a = pow(2, n);
System.out.printf("%4d", a);
++n;
}
--n;
--n;
for (i = 0; i < row; ++i) {
a = pow(2, n);
System.out.printf("%4d",a);
--n;
}
System.out.println( );
}
}
public static int pow(int s,int m)
{
int wer=1;
int i;
for(i=1;i<=m;i++)
wer*=s;
return wer;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.