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

Thread: Grid of circles

  1. #1
    Join Date
    Mar 2010
    Posts
    3

    Grid of circles

    Hi, I'm trying to make a square grid of circles (ex: 3x3, 5x5) using a for loop.

    for(int i=1; i<=Lines; i++){
    g.setColor (Color.RED);
    g.fillOval(x+(SIZE*i/(Lines+1)),y+(SIZE/(Lines+1)),4,4);
    }

    This loop creates only a single row of circles. I'm at a loss as to how to modify this to create an entire grid of circles.
    Any help is appreciated, thanks

  2. #2
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Grid of circles

    You can use two loops, one inside the other.
    If you still want to use only one:

    For a grid of n x m fields (n rows, m columns), you'll have to draw n*m circles, so
    int count = n*m;

    You would loop from i=0 to i<count.
    If (x1, y1) are the coordinates of each circle, and (x,y) is the starting point, then:

    row = i / n (integer division)

    and

    column = i &#37; m.


    So,

    x1 = x + SIZE * column;
    y1 = y + SIZE * row; // if you are drawing bottoms-up, then y1 = y - SIZE * row.

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

    Re: Grid of circles

    Unless there is a compelling reason to do otherwise go with TheGreatCthulhu's first suggestion of 2 loops. It's easier to write, easier for someone else (or yourself after 'n' years) to read and understand and less prone to errors.
    Code:
    for(int x = 0; x < nCols; x++) {
        for(int y = 0; y < nRows; y++) {
            ... your code here...
        }
    }
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  4. #4
    Join Date
    Mar 2010
    Posts
    3

    Re: Grid of circles

    Thank you both very much!

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