How to Loop Fill a 2-Dimensional Array in C++

C++ is a popular, general purpose programming language use in the creation of a wide variety of software applications. A two-dimensional array is a special data type within C++ that collects data and stores it for later use. The "shape" of a 2-D array like a chart that contains a specified number of rows and columns. Each column of data is identified by the value of the row to which that column is linked. Loops are a convenient way to fill a 2-D array because they can quickly assign values to their correct row and column. This is much more efficient than a programmer manually entering individual data into the array.

Instructions

    • 1

      Initialize a two-dimensional array. This involves specifying the type of array, such as "int" or "char," and specifying the dimensions of the array. For example, initializing a two-dimensional integer array with three rows and three columns takes this general form:

      int 2darray[3][3];

    • 2

      Create a "for" loop to indicate the current row being filled. For example, to specify the row number to fill in the 3 x 3 integer array 2darray the code looks like this:

      for(int row = 0; row < 3; row ++) {
      }

      This for loop begins at the first row, loops, jumps to the next row, loops again, jumps to the third row then stops.

    • 3

      Created a second, "nested" for loop inside of the first for loop to fill in the values of the elements in each column. For example, the code to fill in the columns for the 2darray array looks like this:

      for(int column = 0; column < 3; column ++) {
      }

      As for the outer loop, this for loop begins at the first row, loops, jumps to the next row, loops again, jumps to the third row then stops.

    • 4

      Assign each element within each column with a value. The assignment operation occurs from within the inner, nested for loop. For example, to multiply the column coordinate by the row coordinate the code looks like this:

      for(int column = 0; column < 3; column ++) {

             2darray[row][column] = row * column;

      }

    • 5

      Check your code to ensure it is properly structured. For example, the correct code to fill 2darray with the elements equal to the multiplied values of the row and column coordinates looks like this:

      for(int column = 0; column < 3; column ++) {

              for(int column = 0; column &lt; 3; column ++) {
      2darray[row][column] = row * column;
      }

      }

Related Searches

References

Related Ads

Check It Out

Prep for Black Friday Checklist [Infographic]