TWO-DIMENSIONAL ARRAYS - MATRICES IN C++ PROGRAMMING LANGUAGE

Page Contents

Welcome to the page dedicated to two-dimensional and multidimensional arrays in C++! This page provides all the key information, code examples, and practical tips for working with matrices and multidimensional data structures. Using the table of contents, you can quickly jump to interesting sections and find the content that interests you.

Introduction

Two-dimensional arrays, or matrices, are a key concept in C++ programming, allowing efficient storage and manipulation of data in tabular format. This page provides a comprehensive introduction to working with two-dimensional arrays, including declaration, initialization, and practical examples that illustrate their use in real-world situations.

Creating a matrix

Example 1: Printing by rows and columns

Suppose we want to print a sequence of the first 100 natural numbers, but they should be written in 10 rows and 10 columns, as in the image below:​Matrični prikaz 100 brojeva u 10 redovaTo write this we use a nested for loop:​
#include <iostream>
using namespace std;

// Program to print the first 100 natural numbers in 10 rows and 10 columns
int main() {

for (int i = 0; i < 10; i++) {
// 'i' represents the row (starts at 0 and goes up to 9)
for (int j = 0; j < 10; j++) {
// 'j' represents the column (starts at 0 and goes up to 9)
int number = 10 * i + (j + 1); // Calculate the number based on the row and column
cout << number << " "; // Print the number on the same line
}
cout << endl; // Move to a new line after finishing the columns
}

return 0; // End of program
}

Memorizing Numbers Using a Two-Dimensional Array (Matrix)

To store these numbers in memory, we would need to either introduce 10 arrays of 10 elements each, or, if we want to store all the data in a single variable, we would use a two-dimensional array (matrix).

The following declaration creates an integer matrix with 10 rows and 10 columns:

int matrica[10][10]; // This is a matrix of integers with 10 rows and 10 columns

To access a specific element, for instance, the one located in the 3rd row and 5th column, you would use:


matrica[3][5];
    

The previous example would be slightly modified.

#include <iostream>
using namespace std;

// Program for filling and printing a two-dimensional array (matrix)
int main() {
int matrix[10][10]; // Declaration of a matrix with 10 rows and 10 columns

// Filling the matrix
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
matrix[i][j] = 10 * i + (j + 1); // Calculate the value and store it in the matrix
}
}

// Printing the matrix
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
cout << matrix[i][j] << " "; // Print the elements in the row
}
cout << endl; // New line after the row
}

return 0; // End of the program
}
U svakom ciklusu izračunat broj a se smešta u matricu u i-ti red i j-tu kolonu.

Test your code in the editor below

// Write your C++ code here...

Matrix initialization

If we already know the numbers to be placed in the matrix, we can define them in a similar way to how we initialize a one-dimensional array, but in this case it is an array of arrays. For example, the grades for several subjects for multiple students can be stored in a matrix:

intgrades[3][8] = { {2,3,2,2,4,5,5,4},  
                                       {2,3,2,2,4,5,5,4},  
                                       {2,3,2,2,4,5,5,4} };
    

In the square brackets, the dimensions must be specified even if they are implicitly determined by the arrays used for initializing the matrix – here, 3 rows and 8 columns. This indicates that the matrix is actually an array of elements, where those elements are also arrays, and each row and column has its own index to access individual elements (in this example, rows are indexed from 0 to 2, and columns from 0 to 7).

To calculate the average of all elements in the matrix, you first need to sum all the elements and then divide the total by the overall number of elements. A nested for loop is used for this purpose.

Example 2: Average grades of all students

Text: Calculate the average grade of all students from the previously assigned series
#include <iostream>
using namespace std;

// Function to calculate the average grade of all students
void average() {
int grades[3][8] = { {2, 3, 2, 2, 4, 5, 5, 4}, // Grades of the first student
{2, 5, 2, 5, 4, 5, 5, 4}, // Grades of the second student
{2, 4, 4, 2, 4, 3, 5, 4} }; // Grades of the third student

int sum = 0; // Variable to accumulate the total of all grades
double avg; // Variable to store the average

// Loop to iterate through all grades in the matrix
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 8; j++) {
sum = sum + grades[i][j]; // Add the current grade to the total
cout << grades[i][j] << " "; // Print the current grade
}
cout << endl; // New line after each row of grades
}

cout << "Average: ";
avg = sum / (3.0 * 8.0); // Calculate the average (3 rows x 8 grades)
cout << avg; // Print the average
}

int main() {
average(); // Call the function to calculate the average
return 0; // End of program
}

Explanation:​

Steps to Calculate the Average Grade from a Matrix

  1. Matrix Declaration:
    The matrix grades[3][8] contains the grades of three students, each with eight grades.
  2. Matrix Traversal:
    A nested for loop iterates through all rows and columns of the matrix.
    Each grade is added to the variable sum.
  3. Calculating the Average:
    The average is calculated by dividing the total sum of grades by the number of all elements in the matrix (3 x 8).
  4. Output:
    The grades are printed row by row, and after traversing all the grades, the average grade is printed.
After starting​:
Računanje proseka-izvršenje konzolne aplikacije

Example 3: Average grades for each student

Text: Calculate the average grade for each student individually from previously assigned sets​In order to calculate the average for each student, then we must separately add each row of grades and divide by the number of elements of each inner array because each row of grades represents the grades of one student. The average will now be an array of numbers:​
#include <iostream>
using namespace std;

// Function to calculate the average grade for each student
void calculateAverages() {
int grades[3][8] = { {2, 3, 2, 2, 4, 5, 5, 4}, // Grades of the first student
{2, 5, 2, 5, 4, 5, 5, 4}, // Grades of the second student
{2, 4, 4, 2, 4, 3, 5, 4} }; // Grades of the third student

double sum = 0; // Variable for summing the grades of one student
double average[3]; // Array to store the averages for each student

// Loop to iterate through each student's grades
for (int i = 0; i < 3; i++) {
// Iterating through all grades of the current student
for (int j = 0; j < 8; j++) {
sum += grades[i][j]; // Adding the current grade to the sum
cout << grades[i][j] << " "; // Printing the current grade
}
average[i] = sum / 8; // Calculating the average for the current student
sum = 0; // Resetting the sum for the next student
cout << endl; // New line after printing one student's grades
}

// Printing the averages for each student
cout << "Averages per student:" << endl;
for (int i = 0; i < 3; i++) {
cout << "Student " << i + 1 << ": " << average[i] << endl;
}
}

int main() {
calculateAverages(); // Calling the function to calculate averages per student
return 0; // End of the program
}

Explanation:

1. Declaration of the matrix and arrays:

  • The matrix ocene[3][8] stores students' grades.
  • The array prosek[3] holds the average grades of each student.

2. Calculating the average:

  • The first for loop iterates through the students.
  • The inner loop goes through the current student's grades and sums them into zbir.
  • After calculating the average for one student, zbir is reset.

3. Displaying the averages:

  • At the end of the program, the averages of all students are displayed.
After starting:Izračunavanje prosečne ocene pojedinačno-izvršenje programa

Entering the matrix

U prethodnom primeru, matrica ocena je bila zadata. Da bi korisnik mogao samostalno da unese matricu, potrebno je prvo učitati broj redova i kolona matrice. Ovaj proces se može postići sledećim koracima:

int matrica[10][10], m, n;
cin >> m >> n; // Učitavanje dimenzija matrice
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> matrica[i][j]; // Učitavanje elemenata matrice
}
}

Complete solution:

#include <iostream>
using namespace std;

// Function for user input of a matrix
void ucitajMatricu() {
int matrica[10][10]; // Matrix with a maximum size of 10x10
int m, n; // Number of rows and columns

cout << "Enter the number of rows and columns (maximum 10x10): ";
cin >> m >> n; // Reading matrix dimensions

if (m > 10 || n > 10 || m <= 0 || n <= 0) {
cout << "Invalid matrix dimensions!" << endl;
return; // Exit function if dimensions are invalid
}

cout << "Enter the matrix elements:" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> matrica[i][j]; // Reading matrix elements
}
}

cout << "The entered matrix is:" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cout << matrica[i][j] << " "; // Printing matrix elements
}
cout << endl; // New line for the next row
}
}

int main() {
ucitajMatricu(); // Calling the function to input the matrix
return 0; // End of the program
}

Example 5: Attacking jumper

Problem: Knight in Chess

Read the position of the knight in chess (m, n) and determine which squares the knight attacks. If the columns are labeled 1-8 and the rows A-H, mark the squares attacked by the knight with their respective codes. Mark all other squares with an asterisk, except for the square where the knight is located.

Input:

  • Row and column representing the knight's position.
  • Values are in the range: 1 ≤ m ≤ 8, 1 ≤ n ≤ 8.

Output:

  • Codes of the squares that the knight attacks.
  • An empty field at the position where the knight is located.
  • Asterisks on all other squares.

Instructions

To display the appropriate text in the corresponding field, we will use a matrix whose elements are of type string. Since the chessboard is of size 8×8 and the matrix index starts from zero, we will create a 9×9 matrix.

string tabla[9][9];

We need to iterate through all the elements of the matrix sequentially. Since the last row of the matrix corresponds to the first row of the chessboard, a nested for loop should be structured as follows:

for(int i = 8; i >= 1; i--) {
    for(int j = 1; j <= 8; j++) {
        ...
    }
}

When the position i = m and j = n is reached, from that point onward, the codes of the fields attacked by the knight should be printed. For example, the positions:

  • i = m + 2, j = n - 1
  • i = m + 2, j = n + 1
  • ...
Primer: Skakač napada
Example:
Input
4
4
OutputPrimer Skakač napada - izvršenje
Rešenje analiza

Solution:

#include <iostream>
#include <string>
using namespace std;

int main() {
int m, n;
string tabla[9][9]; // Matrix for the chessboard

cout << "Enter the knight's position (row and column): ";
cin >> m >> n;

for (int i = 8; i >= 1; i--) {
for (int j = 1; j <= 8; j++) {
if (i == m && j == n) {
tabla[i][j] = " "; // The knight's square remains empty
} else if ((i == m + 2 && (j == n - 1 || j == n + 1)) ||
(i == m - 2 && (j == n - 1 || j == n + 1)) ||
(i == m + 1 && (j == n - 2 || j == n + 2)) ||
(i == m - 1 && (j == n - 2 || j == n + 2))) {
tabla[i][j] = "S"; // Square attacked by the knight
} else {
tabla[i][j] = "*"; // All other squares are asterisks
}
}
}

cout << "Chessboard:" << endl;
for (int i = 8; i >= 1; i--) {
for (int j = 1; j <= 8; j++) {
cout << tabla[i][j] << " ";
}
cout << endl; // New line after each row of the board
}

return0;
}

Explanation

User Input: The user enters the row and column where the knight is located.

Chessboard Logic:

  • The matrix tabla represents the chessboard.
  • Nested loops iterate through all rows and columns of the board.
  • The squares attacked by the knight are determined using the rules of chess movement.

Output:

  • " " for the square where the knight is located.
  • "S" for the squares attacked by the knight.
  • "*" for all other squares.

Practice tasks

​In order to better understand working with two-dimensional arrays in C++, we have prepared several practical exercises that will help you master the basic concepts.

​1. Creating a table to record student grades

Task Description:

Create a program that uses a two-dimensional array to store the grades of students in several subjects. The array should have rows representing the students and columns representing the subjects.

The program should allow for the input of grades, display the grades of each student, and calculate the average grade for each student as well as for each subject.

Example output:

​Enter grades for 3 students and 4 subjects:
Student 1: 5 4 3 5
Student 2: 4 3 4 4
Student 3: 5 5 5 4

Average grade per student:
Student 1: 4.25
Student 2: 3.75
Student 3: 4.75

Average grade per subject:
Subject 1: 4.67
Subject 2: 4.00
Subject 3: 4.00
Subject 4: 4.33

2. Izračunavanje prosečne vrednosti elemenata u matrici

Opis zadatka:
Napravite program koji koristi dvodimenzionalni niz za unos brojeva u matricu dimenzija N×MN \times MN×M.​
Primer ulaza i izlaza:​​Unesite dimenzije matrice (redovi i kolone): 2 3
Unesite elemente matrice:
1 2 3
4 5 6

Prosečna vrednost elemenata matrice: 3.5

3. Implementacija igre "Iks-Oks" (Tic-Tac-Toe)

Opis zadatka:
Kreirajte jednostavnu verziju igre "Iks-Oks" za dva igrača.
Primer igre:
​Trenutno stanje table:
_ _ _
_ _ _
_ _ _

Igrač 1 (X) bira polje (red, kolona): 1 1
Trenutno stanje table:
X _ _
_ _ _
_ _ _

Igrač 2 (O) bira polje (red, kolona): 1 2
Trenutno stanje table:
X O _
_ _ _
_ _ _

Igrač 1 (X) bira polje (red, kolona): 2 2
...

Igrač 1 (X) je pobedio!

​Višedimenzionalni nizovi – Proširenje koncepta

Dvodimenzionalni nizovi su korisni za predstavljanje matrica, tabela i sličnih struktura. Međutim, ponekad su potrebni složeniji modeli podataka, gde dolazimo do višedimenzionalnih nizova, poput trodimenzionalnih nizova.
Šta su trodimenzionalni nizovi?Trodimenzionalni nizovi su nizovi sa tri indeksa. Možemo ih zamisliti kao niz "matrica" ili kao prostornu strukturu, poput kocke, gde svaki element ima:
Sintaksa za deklaraciju trodimenzionalnog niza u C++:
int niz[dim1][dim2][dim3];
​Primer:int trodimenzionalniNiz[2][3][4];
Ovaj niz ima:
Primer upotrebe trodimenzionalnog nizaKao praktičan primer, trodimenzionalni nizovi se mogu koristiti za čuvanje vrednosti u različitim vremenskim intervalima, poput:
Kratak primer:
#include<iostream>
usingnamespace std;

int main() {
// Deklaracija trodimenzionalnog niza za temperature (grad, dan, vreme)
float temperature[2][3][4] = {
{ {22.5, 23.1, 21.8, 22.0}, {24.2, 25.0, 23.5, 24.1}, {19.8, 20.0, 18.7, 19.5} },
{ {28.5, 27.9, 29.0, 28.7}, {26.5, 25.8, 27.0, 26.9}, {30.0, 31.2, 29.8, 30.5} }
};

// Prikaz temperature za drugi grad, prvi dan, drugo vreme
cout << "Temperatura u drugom gradu, prvog dana, u drugom vremenu: "
<< temperature[1][0][1] << "°C" << endl;
return 0;
}
Rezultat:
​Temperatura u drugom gradu, prvog dana, u drugom vremenu: 27.9°C

Dalje učenje

Ako želite detaljnije da naučite o trodimenzionalnim i višedimenzionalnim nizovima u C++-u i njihovoj primeni, posetite sledeći resurs:



Srodni članci

Matrice-primeri
Nizovi-primeri
Matematički algoritmi
Klase i objekti
Grananje u programu u C/C++