# For loop

• 09-27-2011, 01:02 PM
mCoder
For loop
Hello,

I'm just start programming with Java. I'm trying to solve the following problem (display pattern):

1
2 4
3 6 12
4 8 16 32
5 10 20 40 80
============

So far I did,

Code:

public class DisplayPattern1
{
public static void main(String[] args)
{
int i, j;

for( i = 1; i <= 5; i++ )
{
for ( j = 1; j <= i; j++ )

{
System.out.print( i + " " );
}

System.out.println();
}

}
}

But it shows

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

How could I multiply by 2 with first column to show that pattern. Or any better idea would be appreciable.
• 09-27-2011, 01:09 PM
Thiruppathi
Re: For loop
public class DisplayPattern1
{
public static void main(String[] args)
{
int i, j,pow;

for( i = 1; i <= 5; i++ )
{
pow=1;

for ( j = 1; j <= i; j++ )

{
System.out.print( (i*pow) + " " );
pow=pow*2;
}

System.out.println();
}

}
}
• 09-27-2011, 02:51 PM
Norm
Re: For loop
Copy and paste is usually a faster way to get some code.
Did you learn how to organize your problem, see what the patterns were and create the code to generate that pattern?