char Name[6][10];
char Name[6][10] = {"Mr. Bean","Mr. Bush","Nicole","Kidman","Arnold","Jodie"};
Score[6]; |
Take note that for strings the null character (\0) still needed. From the shaded square area of the Figure we can determine the size of the array. For an array Name[6][10], the array size is 6 x 10 = 60 and equal to the number of the colored square. In general:
array_name[x][y];
The array size is = First index x second index = xy.
This also true for other array dimension, for example three dimensional array:
array_name[x][y][z] = First index x second index x third index = xyz.
For example:
ThreeDimArray[2][4][7] = 2 x 4 x 7 = 56.
And if you want to illustrate the 3D array, it could be a cube with wide, long and height. Can you imagine the 4D, 5D and higher dimension arrays?
Let put the 2D array in the real C program. Create an empty Win32 console application project named myextarray, add source file namedmyextarraysrc and set your project compiled as C code, build and run the following program example.
#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]); } |
|
In the program example, two arrays, Name[6][10] is a 2D array and Score[6] is a 1D array. Name[ ][ ] is an array of characters and Score[ ] is an array of integers. To access a slot in Score[ ], only one index has to be specified but to access a slot in Name[ ], two indexes have to be specified. The first index is called row and the second one column.
For the program example, during the execution, the values for Score[ ] will be read in and stored in the Score[ ] array. The Name[6][10] array has two subscript/indexes. The first subscript specifies that there are 6 players and the second specifies that there are up to 9 characters in the names of these players, not including the null character (‘\0’).
Name[2][2] has the value of ‘c’. That is in the slot where the row is 2 and the column is 2, the value is ‘c’.Name[0][0] has the value of ‘M’. Here the row is 0 and the column index is 0. The names of 6 game players are stored in this array. They are character strings so each one ends with a null character. When printing strings, all characters are printed in order until a null character is encountered, so Name[2] has the value of “Mr. Bean”. The Name[ ][ ] array holds the names of players and Score[ ] array holds the scores of the corresponding players. For example, the game score of 25 is stored in Score[2] for “Nicole” which is stored in Name[2].
After the definition of variables, we see nested for loop 1, which counts the number of a’s and A’s. The first loop varies i from 0 to 5 in increments of 1. The nested loop varies j from 0 in increment of 1 until the end of the string is encountered.
// 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);
What happens here is that i stays fixed at 0, while in the inside loop, j varies until a null character is found. After that, i stays at 1 and j varies from 0 until a null character is found, and so on. While the loop make i and j vary so that all valid characters are accessed, the if statement counts the number of ‘a’ and ‘A’.
Sorting of data is a common task that needs to be done when processing data. In C++ common routines could useStandard Template Library (STL). There are many sorting algorithms, but the ones that are easy to understand are called “natural sorts”. Selection sort is a natural sort because it is one of the algorithms by which sorting is done by humans. Most text may use the “bubble sort”, but it is not any faster nor is it a natural sort.
From the program example we want to sort out the two arrays so that the scores are in descending order (high to low) and Name[][] is also sorted so that the names and scores stay together. In other words, “Kidman” with score 65 (both in slot number 3) will both be moved to slot number 0 after the sort is complete. Likewise, “Jodie” with a score of 49 will be moved from slot number 5 to slot number 1, since he has the second highest score and so on. While sorting, we need to keep the players’ names with their respective scores.
You can see how this sort process works in the following Figure. The shaded cells in the Figure show how much of the array is sorted during each pass. During the first pass, the person with the highest score, “Kidman” is moved to an index of 0. “Mr. Bean” with a score of 10 and who occupied this position, is moved down to the index of 3. A swap has occurred because “Kidman” needed to be in the first position and “Mr. Bean” needed a new slot/index.
Now we find the player with the highest score in the array starting at index 1. “Jodie” is swapped into position 1 with “Mr. Bush” taking “Jodie”’s place in index 5. Next for the third pass “Mr. Bush” takes the position at index 2, swapping with “Nicole” and the process goes on until we have a descending sorted array.
The largest score has to be found many times as the sort progresses. During each pass, the next largest is found. Finding the largest score is not sufficient, but we need to know the index of the score with the largest value. We need to know where that largest score exists because a swap has to occur. For instance, for the first pass, when “Kidman” is found to have the highest score, we needed to know that he was stored at slot 3 so that “Kidman” and “Mr. Bean” and their scores could be swapped.
The swapping is a three-step process and we need an empty slot for temporary storage. From the program example, we start at Temp = Score[i]. Here we need to swap the values stored at Score[i] and Score[LargestIdx]. When swapping “Kidman” and “Mr. Bean”, i is 0 and LargestIdx is 3. We take 10 which is at Score[0] and place it in Temp. Then the 65 in Score[LargestIdx] is placed in Score[0], the 0th slot and the 10 that was in Temp is placed in Score[3], the slot from which the largest number was copied. The process is depicted in the following Figures.
// 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);
Original position: Prepare a temporary storage,Temp.
Step 1: Store 10 into Temp.
Step 2: Store 65 into Score[0]
Step 3: Store 10 into Score[3]
Te three-step swapping process is repeated for the players. Since the players are strings, the strcpy_s() function must be used rather than the assignment statements, which were used for the scores. Notice the Name[ ][ ], only one subscript is used because we are processing strings not the individual character. When we were counting the number of a’s, we were processing individual characters that were in each slot. Then we needed to use both indexes.
#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"); } }
|
|
| |
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. | |
The flowchart for this program example is given on the right.
| |
#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"); } }
|
|
#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"); } }
|
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"); } }
|
#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"); } }
| ------------------------------------------------------
|
a[3][4] = {{1,2,3}, {5,6,7,8}, {9,10,11,12}};
| |
#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"); } }
|
|