Help with Nested For Loop

This is a discussion on Help with Nested For Loop within the C Programming forums, part of the General Programming Boards category; Use a loop inside a loop to create the following pattern: ABCDE ABCD ABC AB A This is what I ...

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    3

    Help with Nested For Loop

    Use a loop inside a loop to create the following pattern:

    ABCDE
    ABCD
    ABC
    AB
    A

    This is what I got, I got the answer by trial and error and still don't understand how this works. Can anyone help explain How these nested for loops work, what statements control what (row/column). Or if there's another answer possible.

    Thanks in advance.


    Code:
    #include <stdio.h>
    int main(void)
    
    {
    
        const int ROWS = 5;
        const int CHARS = 5;
        int row;
        char ch;
    
        for (row = 0; row < ROWS; row++)
        {
            for (ch = ('F' - CHARS);  ch < ('F' - row); ch++)
    
                printf("%c", ch);
    
            printf("\n");
    
        }
    
        return 0;
    
    }

  2. #2
    Registered User
    Join Date
    Feb 2009
    Posts
    278
    This might make it easier to understand...

    Code:
    int row;
    int col;
    
    for (row = 1; row <= 5; row++) {
      printf("Row %d : ", row);
      for (col = 1; col <= 6 - row; col++) {
        printf("Col %d, ", col);
      }
      printf("\n");
    }
    That way you don't have to worry about the character conversions while you try to figure out what the for loops are doing.

  3. #3
    Registered User
    Join Date
    Oct 2008
    Posts
    3
    Finally... an explanation thanks, you saved me lots of time and a headache.

    THanks again

  4. #4
    Registered User
    Join Date
    Feb 2009
    Posts
    278
    No problem - to be honest, the character conversions and "math" confused me.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Nested array vs. tree
    By KONI in forum Tech Board
    Replies: 1
    Last Post: 06-07-2007, 04:43 AM
  2. deriving classes
    By l2u in forum C++ Programming
    Replies: 12
    Last Post: 01-15-2007, 04:01 PM
  3. nested switch issue
    By fsu_altek in forum C Programming
    Replies: 3
    Last Post: 02-15-2006, 09:29 PM
  4. Displaying Data from a Nested Structure
    By shazg2000 in forum C++ Programming
    Replies: 1
    Last Post: 01-09-2005, 09:16 AM
  5. Nested Classes
    By manofsteel972 in forum C++ Programming
    Replies: 4
    Last Post: 11-21-2004, 10:57 AM

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