Thread: Nested loops - asterisk diamond

  1. #1
    Registered User
    Join Date
    Jul 2013
    Posts
    5

    Cool Nested loops - asterisk diamond

    Getting close but I think I am stuck on the second loop. The input you put in will be doubled (and it's not supposed to). Any help much appreciated!!

    Code:
    int main()
    {
        int n, i, j, k;
    
        printf("What would you like the height to be? (Positive odd integer)\n");
        scanf("%d", &n);
    
        for(i=1; i <= n; i++)
        {
            for(j=1; j <= n-i; j++)
            printf("%c", ' ');
            for (k=1; k <= 2*i-1; k++)
            printf("%c", '*');
            printf("\n");
        }
    
    
        k = 1;
        for(i=1; i <= n - 1; i++)
        {
            for(j=1; j <= k; j++)
            printf(" ");
            k++;
            for (j=1; j <= 2*(n-i)-1; j++)
            printf("*");
            printf("\n");
        }
    
    return 0;
    }

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,887
    Quote Originally Posted by charl33t View Post
    Getting close but I think I am stuck on the second loop. The input you put in will be doubled (and it's not supposed to). Any help much appreciated!!
    So divide n by 2, and use that value for the loops.

  3. #3
    Registered User
    Join Date
    Jul 2013
    Posts
    5
    Thank you!! I got it figured out.

  4. #4
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,794
    Code:
    for(i=1; i <= n; i++)
    well, it has no impact on your code, but more generally used in C form will be:
    Code:
    for(i=0; i < n; i++)
    Since when you start working with arrays your variant will get you out of bound of array of n element.
    So I would suggest to start using the second form already now to be regular with it when time comes.
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Nested loops..
    By her091 in forum C Programming
    Replies: 12
    Last Post: 06-17-2012, 02:22 PM
  2. Nested loops
    By zeondik in forum C# Programming
    Replies: 2
    Last Post: 10-26-2008, 06:58 AM
  3. Diamond asterisk
    By P_of_Y in forum C++ Programming
    Replies: 33
    Last Post: 07-22-2006, 09:32 PM
  4. nested For loops
    By Chaplin27 in forum C++ Programming
    Replies: 1
    Last Post: 03-09-2005, 10:12 AM
  5. nested loops PLEASE HELP!!
    By scuba22 in forum C++ Programming
    Replies: 6
    Last Post: 10-08-2002, 09:31 AM