Coding Challenge < C++ >

What will this program output?
C++
#include <iostream>

class Matrix {
public:
Matrix(int rows, int cols) : rows(rows), cols(cols) {
data = new int*[rows];
for (int i = 0; i < rows; ++i) {
data[i] = new int[cols];
for (int j = 0; j < cols; ++j) {
data[i][j] = i * cols + j + 1;
}
}
}

~Matrix() {
for (int i = 0; i < rows; ++i) {
delete[] data[i];
}
delete[] data;
}

void print() const {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
std::cout << data[i][j] << " ";
}
std::cout << std::endl;
}
}

private:
int** data;
int rows;
int cols;
};

int main() {
Matrix matrix(3, 4);
matrix.print();
return 0;
}
C++
#include <iostream>

class Matrix {
public:
Matrix(int rows, int cols) : rows(rows), cols(cols) {
data = new int*[rows];
for (int i = 0; i < rows; ++i) {
data[i] = new int[cols];
for (int j = 0; j < cols; ++j) {
data[i][j] = i * cols + j + 1;
}
}
}

~Matrix() {
for (int i = 0; i < rows; ++i) {
delete[] data[i];
}
delete[] data;
}

void print() const {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
std::cout << data[i][j] << " ";
}
std::cout << std::endl;
}
}

private:
int** data;
int rows;
int cols;
};

int main() {
Matrix matrix(3, 4);
matrix.print();
return 0;
}
2 Replies
Petr Dvořák
Petr Dvořák11mo ago
The output is a matrix of 3 rows and 4 columns. The content of the matrix are numbers from 1 to 12 in the following composition: 1 2 3 4 5 6 7 8 9 10 11 12
Marvee Amasi
Marvee Amasi11mo ago
It consoles 4 x 3 matrix , 1 2 3 4 in row one , 5 6 7 8 in row two and 9 10 11 12 in row 3
Want results from more Discord servers?
Add your server