Thread: for loop

  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    8

    for loop

    Hi,

    Have a look at the code
    Code:
    /* prorgram to print output
    ********
    ***   ***
    **      **   
    *         *
    
    --------------------------------------------------------
    */
    
    #include<stdio.h>
    int main()
    {
        int x,rows,columns;
        
        printf("Enter the number of columns :");
        scanf("%d",&x);
        
          
           for (rows=0;rows<=x;rows++)
           
           {
               for (columns=1;columns<=x;columns++)
              
               if (columns<=x-rows)
               /*printf("*");*/
               printf("%d",columns);
               else
               printf(" ");
               printf("\n");
           
                  }   
                   
           getchar();
           }

    I know it is similar to printing out 12344321 ,123 321,12 21 and so on.

    As you can see the first part of printing out 1234 followed by the other lines is something I cud figure out but the way to figure out printing the reverse is something I am unable to wrap my head around.I am pretty sure it can be solved by the use of a % or / operator(dont know which one for sure).

    All I am looking for is for some one to guide me as to how to achieve the answer.

    Thanks in advance

  2. #2
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Code:
    1. Your code isn't indented properly, which makes it hard for people to read.
    2. You appear to be missing some '{' and '}' braces.

  3. #3
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    The missing braces are not really necessary here as there is only one command executed within the inner for loop, however with indentation like that it is hard to tell.

    With your problem you need the columns for loop to run to double the value of 'x'.

    When checking whether or not to print a star you then also need to check if the current column is greater than the number x + the number of rows. That will print the right hand triangle for you.

    [edit]I just realized that its not symmetrical, but I'll leave the last bit for you to figure out [/edit]
    Last edited by mike_g; 08-19-2007 at 04:00 PM.

Popular pages Recent additions subscribe to a feed