Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Understanding Two-Dimensional Arrays and Functions in C++

Notes May 9 4

Two-Dimensional Arrays

A two-dimensional array extends the concept of a one-dimensional array by adding a second dimension. While a one-dimensional array can be thought of as a single row of elements, a two-dimensional array organizes data in rows and columns, forming a matrix-like structure.

Declaration Methods

There are four primary ways to declare a two-dimensional array:

  1. dataType arrayName[rows][cols]; — Declares without initialization.
  2. dataType arrayName[rows][cols] = {{row1}, {row2}}; — Initializes with nested braces for clarity.
  3. dataType arrayName[rows][cols] = {values}; — Initializes with a flat list.
  4. dataType arrayName[][cols] = {values}; — Omits row count, letting the compiler infer it.

Method 1: Declaration with Manual Assignment

#include <iostream>
using namespace std;

int main() {
    int matrix[2][2];
    matrix[0][0] = 10;
    matrix[0][1] = 20;
    matrix[1][0] = 30;
    matrix[1][1] = 40;
    
    cout << matrix[0][0] << endl;
    cout << matrix[1][1] << endl;
    return 0;
}

Method 2: Initialization with Nested Braces

#include <iostream>
using namespace std;

int main() {
    int matrix[2][3] = {
        {5, 10, 15},
        {20, 25, 30}
    };
    
    for (int r = 0; r < 2; r++) {
        for (int c = 0; c < 3; c++) {
            cout << matrix[r][c] << " ";
        }
        cout << endl;
    }
    return 0;
}

Method 3: Flat Initialization

#include <iostream>
using namespace std;

int main() {
    int matrix[2][2] = {1, 2, 3, 4};
    
    for (int r = 0; r < 2; r++) {
        for (int c = 0; c < 2; c++) {
            cout << matrix[r][c] << " ";
        }
        cout << endl;
    }
    return 0;
}

Method 4: Automatic Row Detection

#include <iostream>
using namespace std;

int main() {
    int matrix[][4] = {1, 2, 3, 4, 5, 6, 7, 8};
    
    for (int r = 0; r < 2; r++) {
        for (int c = 0; c < 4; c++) {
            cout << matrix[r][c] << " ";
        }
        cout << endl;
    }
    return 0;
}

Memory and Address Information

The array name provides access to memory-related information:

#include <iostream>
using namespace std;

int main() {
    int matrix[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };
    
    cout << "Total memory: " << sizeof(matrix) << " bytes" << endl;
    cout << "Memory per row: " << sizeof(matrix[0]) << " bytes" << endl;
    cout << "Memory per element: " << sizeof(matrix[0][0]) << " bytes" << endl;
    cout << "Number of rows: " << sizeof(matrix) / sizeof(matrix[0]) << endl;
    cout << "Number of columns: " << sizeof(matrix[0]) / sizeof(matrix[0][0]) << endl;
    
    cout << "Array address: " << matrix << endl;
    cout << "First row address: " << matrix[0] << endl;
    cout << "First element address: " << &matrix[0][0] << endl;
    return 0;
}

Practical Example: Student Grades

StudentPhysicsChemistryBiology
Alice859278
Bob908895
Charlie758085
#include <iostream>
#include <string>
using namespace std;

int main() {
    int grades[3][3] = {
        {85, 92, 78},
        {90, 88, 95},
        {75, 80, 85}
    };
    string students[] = {"Alice", "Bob", "Charlie"};
    
    for (int i = 0; i < 3; i++) {
        int total = 0;
        for (int j = 0; j < 3; j++) {
            total += grades[i][j];
        }
        cout << students[i] << " - Total Score: " << total << endl;
    }
    return 0;
}

Functions

Functions encapsulate reusable blocks of code, reducing redundancy and improving maintainability.

Function Definition

A function consists of:

  • Return type
  • Function name
  • Parameter list
  • Function body
  • Return statement
returnType functionName(parameterType paramName) {
    // function body
    return value;
}

Example of an addition function:

#include <iostream>
using namespace std;

int add(int x, int y) {
    return x + y;
}

Function Invocation

#include <iostream>
using namespace std;

int add(int x, int y) {
    return x + y;
}

int main() {
    int num1 = 15;
    int num2 = 25;
    int result = add(num1, num2);
    cout << "Sum: " << result << endl;
    return 0;
}

Parameters defined in the function signature are formal parameters, while values passed during the call are actual parameters (arguments).

Pass by Value

When passing by value, the function receives a copy of the argument. Modifications to the parameter do not affect the original variable.

#include <iostream>
using namespace std;

void swapValues(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
    cout << "Inside function: a=" << a << ", b=" << b << endl;
}

int main() {
    int x = 5, y = 10;
    cout << "Before: x=" << x << ", y=" << y << endl;
    swapValues(x, y);
    cout << "After: x=" << x << ", y=" << y << endl;
    return 0;
}

Function Declaration (Prototype)

A function must be declared before it is used. If the definition appears after main(), a forward declaration is required.

#include <iostream>
using namespace std;

int findMaximum(int x, int y); // Function prototype

int main() {
    int a = 42, b = 17;
    cout << "Maximum: " << findMaximum(a, b) << endl;
    return 0;
}

int findMaximum(int x, int y) {
    return (x > y) ? x : y;
}

Header File Organization

For larger projects, functions can be separated into header and source files:

  1. Create a header file (e.g., operations.h) with function declarations.
  2. Create a source file (e.g., operations.cpp) with function definitions.
  3. Include the header in the main file.

operations.h:

#ifndef OPERATIONS_H
#define OPERATIONS_H
int findMaximum(int x, int y);
#endif

operations.cpp:

#include "operations.h"

int findMaximum(int x, int y) {
    return (x > y) ? x : y;
}

main.cpp:

#include <iostream>
#include "operations.h"
using namespace std;

int main() {
    cout << findMaximum(25, 40) << endl;
    return 0;
}
Tags: C++

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Deploying a Maven Web Application to Tomcat 9 Using the Tomcat Manager

Tomcat 9 does not provide a dedicated Maven plugin. The Tomcat Manager interface, however, is backward-compatible, so the Tomcat 7 Maven Plugin can be used to deploy to Tomcat 9. This guide shows two...

Skipping Errors in MySQL Asynchronous Replication

When a replica halts because the SQL thread encounters an error, you can resume replication by skipping the problematic event(s). Two common approaches are available. Methods to Skip Errors 1) Skip a...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.