| Main |< C & C++ Array Data Type 4 | C & C++ 2D Array 2 >| Site Index | Download |


 

 

 

 

 

 

C LAB WORKSHEET 10

2 Dimensional (2D) Array 1

 

 

 

 

 

 

  1. The C & C++ 2D array data type.

  2. 2D array declaration and initialization.

  3. Flowcharts, swapping array elements etc.

  4. Tutorial reference that should be used together with this worksheet are C & C++ array part 1 and C & C++ array part 2.

 

 

 

 

 

 

 

 

 

 

 

 

 
  • In previous worksheet we were introduced with one dimensional array, 1D array as in the previous worksheet example, score[6]. A dimension is the size of the array. If we say that an array is 1D, it means the size of the array is one dimension. Array can has more than one dimension and in this worksheet we will deal with two dimension array, 2D array. Look at the following 2D array declaration:

char Name[6][10];

  • Here we have two indexes/subscripts. Normally the two indexes refer to the rows and columns, that is the [6] refers to rows and [10] refers to columns. If we assign initial string values for the 2D array it will look something like the following.

char Name[6][10] = {"Mr. Bean", "Mr. Bush", "Nicole", "Kidman", "Arnold", "Jodie"};

  • Here, we can initialize the array with 6 strings, each with maximum 9 characters long. If depicted in rows and columns it will look something like the following and can be considered as contiguous arrangement in the memory.

C & C++ 2D array storage illustration

  • And compare to the 1D array shown below.

Score[6];

C & C++ array storage illustration

array_name[x][y];

 

The array size is = First index x second index = xy.

array_name[x][y][z] = First index x second index x third index = xyz.

ThreeDimArray[2][4][7] = 2 x 4 x 7 = 56.

#include <stdio.h>

// for strcpy_s()

#include <string.h>

 

void main()

{

      // array that holds 6 strings, each max 9 characters long

      char Name[6][10] ={"Mr. Bean", "Mr. Bush", "Nicole", "Kidman", "Arnold", "Jodie"};

      // array that holds scores for 6 players of "name[ ][ ]"

      int Score[6],

     // a variable to count the number of a's.

     Count = 0,

     // index for the largest score while doing the sorting

     LargestIdx,

     // used in the for loop

     i, j,

     // used to temporarily store a score while doing the swapping

     Temp;

     // used to temporarily store a name while doing the swapping

     char TempStr[10];

     // loop and nested loop to count the number of a's in all the names

     // loop for the rows...

     for(i = 0; i <= 5; i = i + 1)

            // loop for the columns

            for(j = 0; Name[i][j] != '\0'; j = j + 1)

                  // start counting the 'a' and 'A'

                  if(Name[i][j] == 'a' || Name[i][j] == 'A')

                        Count = Count + 1;

     printf("The number of a's is %d.\n\n", Count);

     // loop to get the scores of all 6 players

     for(i = 0; i <= 5; i = i + 1)

     {

            printf("Enter score for %s: ", Name[i]);

            // scanf("%d", &Score[i]);

            scanf_s("%d", &Score[i], 1);

     }

     // nothing here, just to see the entered scores...

     printf("The entered scores: ");

     for(i = 0; i <= 5; i = i + 1)

            printf("%d ", Score[i]);

     // start the sorting, i is the number of the pass

     for(i = 0; i <= 4; i = i + 1)

     {

            // find index that has the largest number for this pass

            LargestIdx = i;

            for(j = i + 1; j <= 5; j = j + 1)

                  if(Score[j] > Score[LargestIdx])

                        LargestIdx = j;

            // swap the first score and name for this pass with that of the largest score

            Temp = Score[i];

            Score[i] = Score[LargestIdx];

            Score[LargestIdx] = Temp;

            // strcpy(TempStr, Name[i]);

            strcpy_s(TempStr, 9, Name[i]);

            strcpy_s(Name[i], 9, Name[LargestIdx]);

            strcpy_s(Name[LargestIdx], 9, TempStr);

     }

     // print out the sorted scores and names

     printf("\nThe descending score:\n");

     for(i = 0; i <= 5; i = i + 1)

            printf("%d\t%s\n", Score[i], Name[i]);

}

 

C & C++ 2D reading and writing data into array

Accessing 2D Array Using Nested for Loop

// loop for the rows...

for(i = 0; i <= 5; i = i + 1)

            // loop for the columns

            for(j = 0; Name[i][j] != '\0'; j = j + 1)

                  // start counting the 'a' and 'A'

                  if(Name[i][j] == 'a' || Name[i][j] == 'A')

                        Count = Count + 1;

             printf("The number of a's is %d.\n\n", Count);

Selection Sort

C & C++ 2D array storage illustration with string data

            // swap the first score and name for this pass with that of the largest score

            Temp = Score[i];

            Score[i] = Score[LargestIdx];

            Score[LargestIdx] = Temp;

            strcpy_s(TempStr, 9, Name[i]);

            strcpy_s(Name[i], 9, Name[LargestIdx]);

            strcpy_s(Name[LargestIdx], 9, TempStr);

C & C++ 2D array storage illustration - swapping array element 1

C & C++ 2D array storage illustration - swapping array element 2

C & C++ 2D array storage illustration - swapping array element 3

C & C++ 2D array storage illustration - swapping array element 4

Experiment And Practice

 

  1. Build, run and show the output for the following program then answer the questions. In this program, i (the row) is fixed, j (column) varies.

 

#include <stdio.h>

 

void main()

{

      int i, j;

      for(i = 1; i <= 3; i = i + 1)

      {

            for(j = 1; j <= 4; j = j + 1)

                  printf("i = %d\tj = %d\n", i, j);

                  printf("\n");

      }

}

  1. There are two loops above, the i loop and the j loop. Which loop is the outer loop?

  2. Which loop would you call the nested loop?

  3. Which loop is done only once? Which one is repeated?

  4. How many times is i set to 1? How many times is j set to 1?

  5. Which variable varies faster than the other?

  6. What is the effect of omitting the braces of the i loop?

C & C++ 2D array with for loop output example

  1. The i loop is the outer loop.

  2. j loop is the nested loop.

  3. i loop was done once and j loop was repeated.

  4. 4 times.

  5. j variable.

  6. By omitting the braces, only the last printf() will be effected. In this program only one line of code available and effect each of the for loop. The last printf() only print new line for every outer for loop iteration. A sample output is shown below when the outer for loop braces have been omitted.

 

C & C++ 2D array with for loop - playing with indexes

 

 

 

 

 

 

 

 

 

 

 

 

The Figure on the right is an illustration of the inner and outer for loops. The green area is the inner loop that will be executed while the outer loop depicted in blue is true.

C & C++ 2D array with for loop illustration - for inner and outer loops

The flowchart for this program example is given on the right.

 

C & C++ 2D array flowchart illustration

   
  1. Let do some operation on the array. We do some modification in the first printf(). Show the output and answer the questions.

 

#include <stdio.h>

 

void main()

{

      int i, j;

      for(i = 1; i <= 3; i = i + 1)

      {

            for(j = 1; j <= 4; j = j + 1)

                  printf("i*j = %d\t", i*j);

            printf("\n");

      }

}

  1. Firstly, i is 1 and j is 1. What is printed at that time?

  2. Then, i is 1 and j is 2. What is printed at that time? Why is it on the same line?

  3. Eventually, i is 1 and j is 4. What is printed at that time?

  4. Now that the j loop is complete for the first time, what happens before i becomes 2?

  5. When i is 2 and j is 3, what is printed?

  6. When i is 3 and j is 4, what is printed?

C & C++ 2D array manipulating the array elements

  1. 1 was printed because 1*1 = 1.

  2. 2 was printed because 1*2 = 2.

  3. 4 was printed because 1*4 = 4.

  4. It goes to a new line because of the printf("\n"); statement.

  5. 6 was printed because 2*3 = 6.

  6. 12 was printed because 3*4 = 12.

   
  1. Complete the for statement for the j loop so that the output is as shown below. When i is 1, we want j to go as far as 1. When i is 2, we want j to go as far as 2 and so on.

 

#include <stdio.h>

 

void main()

{

      int i, j;

      for(i = 1; i <= 4; i = i + 1)

      {

            for(j =_______; j <= ______; j = j + 1)

                  printf("%d\t", i*j);

            printf("\n");

      }

}

 

1

2     4

3     6     9

4     8     12    16

#include <stdio.h>

 

void main()

{

    int i, j=0;

    for(i = 1; i <= 4; i = i + 1)

    {

        for(j = 1; j <= i; j = j + 1)

            printf("%d\t", i*j);

        printf("\n");

    }

}

 

C & C++ 2D array - output sample for for loops

   
  1. Next, can you replace i * j with something else in the printf() to give the following output?

 

2

3     4

4     5     6

5     6     7     8

#include <stdio.h>

 

void main()

{

    int i, j=0;

    for(i = 1; i <= 4; i = i + 1)

    {

        for(j = 1; j <= i; j = j + 1)

            printf("%d\t", i+j);

        printf("\n");

    }

}

 

C & C++ 2D array - manipulating the for loops

   
  1. a[ ][ ] is a 2D array. The first index is always the row index and the second one is always the column. a[ ][ ] here has 3 rows and 4 columns. i, being the first index, is the index for the row. If j was the first index, then it would have been the row index. The array is initialized in memory as shown below. Show the output for the program example and answer the questions.

 

 

#include <stdio.h>

 

void main()

{

      int i, j, a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};

      for(i = 0; i <= 2; i = i + 1)

      {

            for(j = 0; j <= 3; j = j + 1)

                  printf("a[%d][%d] = %d  ", i, j, a[i][j]);

            printf("\n");

      }

}

  1. When i is 0 and j is 0, the element in the first row and the first column is printed. When i is 0 and j is 1, the element in which slot is printed?

  2. When i is 0 and j is 3, the element in which slot is printed?

  3. When i is 2 and j is 1, the element in which slot is printed?

 

------------------------------------------------------

 

C & C++ 2D array- indexes and element data values

  1. Element in the first row and second column.

  2. Element in the first row and fourth column.

  3. Element in the third row and second column.

   
  • We also can force the arrangement of the array content by using another curly brace as shown below. It is very convenient method in forcing the arrangement of the array element.

 a[3][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};

  • Here we have a very clear arrangement of the array element for 3 rows, each with 4 columns. Let drop one element, a[0][3] in the first row of the array, then we have:

a[3][4] = {{1,2,3}, {5,6,7,8}, {9,10,11,12}};

  • In this case, the element a[0][3] will be filled with 0. You can try using this array initialization in other program examples.

   
  1. In the following example, we swap i with j in the previous program example. Show the output and answer the questions.

 

#include <stdio.h>

 

void main()

{

      int i, j, a[4][3] = {1,2,3,4,5,6,7,8,9,10,11,12};

      for(i = 0; i <= 3; i = i + 1)

      {

            for(j = 0; j <= 2; j = j + 1)

                  printf("a[%d][%d] = %d  ", j, i, a[j][i]);

            printf("\n");

      }

}

  1. When i is 0 and j is 0, the element in which slot is printed?

  2. When i is 0 and j is 1, the element in which slot is printed?

  3. When i is 0 and j is 2, the element in which slot is printed?

  4. When i is 1 and j is 0, the element in which slot is printed?

C & C++ 2D array - i, j and indexes manipulation

  1. Element in first row and first column.

  2. Element in first row and second column.

  3. Element in first row and third column.

  4. Element in second row and first column.

 

 

 

 

 

 

www.tenouk.com

 

| Main |< C & C++ Array Data Type 4 | C & C++ 2D Array 2 >| Site Index | Download |


The C & C++ 2D Array Manipulation: Part 1 | Part 2 | Part 3