CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Sep 2010
    Posts
    1

    Nested for loops

    My code is this
    public class temp
    {
    public static void main(String[] args)
    {

    for (int i = 1; i <= 4; i++)
    {
    for (int j = 1; j <= 6; j++)
    {
    System.out.print((i*j)*4-3 + " ");
    }
    System.out.println();
    }
    }
    }
    I'm getting:
    1 5 9 13 17 21
    5 13 21 29 37 45
    9 21 33 45 57 69
    13 29 45 61 77 93

    The output should be:
    1 5 9 13 17 21
    2 6 10 14 18 22
    3 7 11 15 19 23
    4 8 13 16 20 24

    Can't figure out what I'm doing wrong.
    Please help
    Thanks,
    Jeff

  2. #2
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: Nested for loops

    When posting code please use code tags.

    Can't figure out what I'm doing wrong
    Try debugging your program. Step through the code by hand writing down the values for i & j as you go and then do the calculation and see what the answer is. Repeat this until you get to the part where it all goes wrong.

    Once you have done that and realised your calculation is wrong you need to look at what you are trying to achieve and work out how to achieve it. Start with how to calculate the values in the first column only (hint it might be easier if j started from 0).
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  3. #3
    Join Date
    Jun 1999
    Location
    Eastern Florida
    Posts
    3,877

    Re: Nested for loops

    Norm

  4. #4
    Join Date
    Sep 2010
    Posts
    21

    Re: Nested for loops

    This how I did and get it right:

    public static void main(String[] args)
    {

    for (int i = 1; i <= 4; i++)
    {
    System.out.print(i + " " );
    for (int j = 1; j <= 5; j++)
    {
    System.out.print(i+j+j+j+j + " " );
    }
    System.out.println();
    }
    }
    }


    output:
    1 5 9 13 17 21
    2 6 10 14 18 22
    3 7 11 15 19 23
    4 8 12 16 20 24

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured