Results 1 to 3 of 3
Like Tree1Likes
  • 1 Post By Thiruppathi

Thread: For loop

  1. #1
    mCoder is offline Member
    Join Date
    Sep 2011
    Posts
    2
    Rep Power
    0

    Default 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,

    Java 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.

  2. #2
    Thiruppathi is offline Member
    Join Date
    Sep 2011
    Posts
    5
    Rep Power
    0

    Default 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();
    }

    }
    }
    mCoder likes this.

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default 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?

Similar Threads

  1. JTextField loop 2x for-loop WEIRD!
    By Streetproject in forum AWT / Swing
    Replies: 2
    Last Post: 02-16-2011, 05:46 PM
  2. Replies: 5
    Last Post: 04-30-2010, 05:05 PM
  3. while-loop stopping on first loop
    By davester in forum New To Java
    Replies: 6
    Last Post: 06-26-2009, 08:46 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •