Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C++ Two-Dimensional Arrays #202

Open
Qingquan-Li opened this issue Jun 30, 2022 · 0 comments
Open

C++ Two-Dimensional Arrays #202

Qingquan-Li opened this issue Jun 30, 2022 · 0 comments
Labels

Comments

@Qingquan-Li
Copy link
Owner

Concept: A two-dimensional array is like several identical arrays put together. It is useful for storing multiple sets of data.

double array[Rows][Columns];
// Assigns the value 99.5 to the element at
// row#2 column#1 of the scores array:
scores[1][0] = 99.5;

1. Two-dimensional array initialization

#include <iostream>
using namespace std;

int main() {
    const int ROWS = 3;
    const int COLUMNS = 4;
    // The extra braces that enclose each row's initialization list
    // is optional.
    // int num_ppl[ROWS][COLUMNS] = {
    //     4, 5, 2, 3, 0, 0, 5, 5, 5, 4, 2, 0
    // };
    int num_ppl[ROWS][COLUMNS] = {{4, 5, 2, 3},
                                  {0, 0, 5, 5},
                                  {5, 4, 2, 0}
                                 };
    
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLUMNS; j++) {
            cout << num_ppl[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

Output:

4 5 2 3 
0 0 5 5 
5 4 2 0 

2. Passing Two-Dimensional Arrays to Functions

When a two-dimensional array is passed to a function, the parameter type must contain a size declarator for the number of columns.

Here is the header for the function print_2D_array below:

void print_2D_array(int arr[][COLUMNS], int rows)
#include <iostream>

using namespace std;

const int COLUMNS = 4;

// Function prototype:
void print_2D_array(int[][COLUMNS], int);

int main() {
    const int ROWS = 3;
    int num_ppl[ROWS][COLUMNS] = {{1, 2, 2, 3},
                                  {0, 0, 5, 5},
                                  {5, 4, 2, 0}
    };

    print_2D_array(num_ppl, ROWS);

    return 0;
}

void print_2D_array(int arr[][COLUMNS], int rows) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < COLUMNS; j++) {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
}

Output:

1 2 2 3 
0 0 5 5 
5 4 2 0 

@Qingquan-Li Qingquan-Li changed the title C++ Rwo-Dimensional Arrays C++ Two-Dimensional Arrays Jun 30, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant