Thread: Teach Me: Fill a 2d array with loop commands

  1. #1
    Registered User
    Join Date
    Nov 2017
    Posts
    7

    Teach Me: Fill a 2d array with loop commands

    Thanks for entering my thread. I am in an intro to programming class. Unfortunately for me, my instructor didn't manage his time well enough so we are rushing through the C programming sections that prepare us for part 2 of the class.

    My assignment is to fill a 2-dimensional array with the values 1 - 20 in reverse order (descending) with loop commands.

    This was the first one I came up with.
    Code:
    #include <stdio.h>
    
    
    main()
    {
      int x;
      int y;
      int array[20][2]; 
      
      for ( x = 0; x < 20; x++ ) {
          array[x][1] = 20-x;
      }
      
      for ( x = 0; x < 20; x++ ) {
        printf( "%d", array[x][1] );    
        printf( "\n" );
      }
      
    }
    I made this next one with a nested loop. Also, this one doesn't have any empty array values like the previous one.
    Code:
    #include <stdio.h>
    
    
    main()
    {
      int x;
      int y;
      int array[10][2]; 
      
      for ( x = 0; x < 10; x++ ) 
      {
          for ( y = 0; y < 2; y++) 
          {
              array[x][y] = 20-(2*x+y);
          }
      }
      
      for ( x = 0; x < 10; x++ ) 
      {
          for ( y = 0; y < 2; y++) 
          {
            printf( "%d ", array[x][y] ); 
          }
        printf( "\n" );
      }
      
    }
    Am I on the right track?

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    It looks okay to me. Was the assignment specific about where the numbers go?

  3. #3
    Registered User
    Join Date
    Nov 2017
    Posts
    7
    Yes, the first program is closer to what my instructor wants. There was an earlier assignment where we had to fill an array manually with the same numbers (1 to 20 in descending order).

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    So maybe the instructor wants 20 to 11 to go in the left column, and 10 to 1 in the right?

    If that is right then I would say the right formula is 20 / (y + 1) - x

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 12-14-2011, 11:31 AM
  2. Using Loop Commands and odd integers
    By Sammy2011 in forum C++ Programming
    Replies: 11
    Last Post: 10-06-2011, 09:09 AM
  3. Fill the array help
    By IMMORTALX in forum C Programming
    Replies: 7
    Last Post: 09-09-2011, 03:34 AM
  4. Replies: 2
    Last Post: 04-27-2008, 03:39 AM
  5. Trying to fill an int array
    By boojus in forum C++ Programming
    Replies: 3
    Last Post: 11-21-2003, 02:31 PM

Tags for this Thread