1) Create a two-dimensional array of 5x5, fill it with random numbers from 10 to 99 and display. Swap the maximum element of each row with the first element in the corresponding row. The problem solved by the pointer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | #include <iostream> #include <ctime> using namespace std; int main() { setlocale(LC_ALL, "rus"); srand(time(NULL)); int size = 5; // выделяем память для указателей на строки матрицы int** arrWithDigits = new int* [size]; for (int i = 0; i < size; i++) { arrWithDigits[i] = new int[size]; // выделение памяти для каждого элемента строки матрицы } for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { arrWithDigits[i][j] = 10 + rand() % 90; // заполняем числами от 10 до 99 cout << arrWithDigits[i][j] << " | "; // показываем } cout << endl; } cout << endl << endl; // поиск максимального значение в строке матрицы int max = 0; // для записи максимального значения int buf = 0; // буфер для перестановки местами значений int x = 0; // для записи номера строки в котором ищем максимальное значение int y = 0; // для записи номера столбца с максимальным значением for (int i = 0; i < size; i++) { max = arrWithDigits[i][0]; for (int j = 1; j < size; j++) { if (arrWithDigits[i][j] > max) { max = arrWithDigits[i][j]; x = i; // запоминаем номер строки y = j; // запоминаем номер столбца } } // замена максимума с первым элементом в строке if (arrWithDigits[i][0] < max) { buf = arrWithDigits[i][0]; arrWithDigits[i][0] = max; arrWithDigits[x][y] = buf; } } cout << "Матрица после перестановки максимальных значений в строке: "<< endl; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { cout << arrWithDigits[i][j] << " | "; } cout << endl; } cout << endl << endl; // освобождение памяти for (int i = 0; i < size; i++) { delete[] arrWithDigits[i]; // освобождаем память ячеек } delete[] arrWithDigits; // память под указатели на строки матрицы return 0; } |
The question of, how to allocate memory for the two-dimensional array, disclosed in detail in this lesson – Tasks: Указатели в С (task №3). Basically, comments in the source code should be enough, to deal with the solution of this problem. But if questions remain – ask.
The result of the program work:
2) The challenge for the multiplication of matrices. The user arbitrarily sets the dimension of the two arrays and fills the values manually. Do not forget, that it is necessary to allocate the appropriate memory locations for matrices, that the user will fill in for the final third of the matrix. Next, display on the screen, both the matrix and filled the resulting matrix (their play).
Maybe someone knows, how to multiply matrices. Watch this short video (author: Prihodovsky MA)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | #include <iostream> #include <conio.h> using namespace std; int main() // матрицы произвольного размера { setlocale(LC_ALL, "rus"); int a; // размерность матриц int b; int c; int d; do { system("cls"); cout << "Введите размерность 1-й матрицы: "; cin >> a; cin >> b; cout << endl; cout << "Введите размерность 2-й матрицы: "; cin >> c; cin >> d; cout << endl; if (b != c) { system("cls"); cout << " Эти матрицы невозможно умножить!"; cout << "\n Нажмите Enter для повторного ввода!"; _getch(); } } while (b != c); // выделяем память под матрицы с заданным размером int **M1 = new int*[a]; // сначала для массива указателей на строки матрицы for (int i(0); i < a; i++) M1[i] = new int[b]; // и для каждого элемента int **M2 = new int*[c]; for (int i(0); i < c; i++) M2[i] = new int[d]; int **M3 = new int*[a]; for (int i(0); i < a; i++) M3[i] = new int[d]; system("cls"); cout << "Заполните 1-ю матрицу " << a << "x" << b << endl; for (int i(0); i < a; i++) { for (int j(0); j < b; j++) { cin >> M1[i][j]; } cout << endl; } cout << "Заполните 2-ю матрицу " << c << "x" << d << endl; for (int i(0); i < c; i++) { for (int j(0); j < d; j++) { cin >> M2[i][j]; } cout << endl; } for (int i(0); i < a; i++) // обнуляем 3-ю матрицу { for (int j(0); j < d; j++) { M3[i][j] = 0; } } system("cls"); cout << "Первая матрица: " << endl; for (int i(0); i < a; i++) { cout << "| "; for (int j(0); j < b; j++) { cout << M1[i][j]; if (j < b - 1) cout << " "; else cout << " |" << endl; } } cout << "\nВторая матрица : " << endl; for (int i(0); i < c; i++) { cout << "| "; for (int j(0); j < d; j++) { cout << M2[i][j]; if (j < d - 1) cout << " "; else cout << " |" << endl; } } // умножение (произведение) матриц for (int i(0); i < a; i++) { for (int j(0); j < d; j++) { for (int m(0); m < b; m++) M3[i][j] += M1[i][m] * M2[m][j]; } } cout << "\nИтоговая матрица : " << endl; for (int i(0); i < a; i++) { cout << "| "; for (int j(0); j < d; j++) { cout << M3[i][j] << " "; } cout << "|" << endl; } // освободим память for (int i(0); i < a; i++) // сначала элементы строк { delete[] M1[i]; delete[] M2[i]; delete[] M3[i]; } delete[] M1; // затем память указателей на строки delete[] M2; delete[] M3; } |
For your homework: Write a function for entering matrices of dimension, allocation and deallocation, display and matrix multiplication.
Результат работы:
#include
#include
#include
using namespace std;
void logo()
{
cout << "+————————————————-+" << endl;
cout << "|Matrix arithmetic program|" << endl;
cout << "+————————————————-+" << endl << endl;
}
void DeleateMatrix(int**& matrix, int rows, int cols)
{
for (int i = 0; i < rows; i )
{
delete[] matrix[i];
}
delete[] matrix;
matrix = nullptr;
}
void CreateMatrix(int **&matrix, int rows, int cols)
{
matrix = new int* [rows];
for (int i = 0; i < rows; i )
{
matrix[i] = new int[cols];
}
for (int i = 0; i < rows; i )
{
for (int j = 0; j < cols; j )
{
matrix[i][j] = 0;
}
}
}
void InputMatrix(int **&matrix, int rows, int cols)
{
for (int i = 0; i < rows; i )
{
cout << i + 1 << " string: " << endl;
for (int j = 0; j < cols; j )
{
cout <= k; k *= 10)
{
cout << " ";
}
cout << j + 1;
cout <> matrix[i][j];
}
}
}
void OutputMatrix(int **& matrix, int rows, int cols)
{
cout << endl;
for (int i = 0; i < rows; i )
{
for (int j = 0; j < cols; j )
{
if (j == 0)
{
cout << "{ ";
}
cout << matrix[i][j];
if (j != cols – 1)
{
cout << "\t";
}
if (j == cols – 1)
{
cout << " }";
}
}
cout << endl;
}
cout << endl;
}
int main()
{
setlocale(LC_ALL, "rus");
while (true)
{
bool pause = 0;
bool error = false;
char repeat = 0;
int** firstMatrix = 0;
int firstRows = 0;
int firstCols = 0;
int** resultMatrix = 0;
int** secondMatrix = 0;
int secondRows = 0;
int secondCols = 0;
do {
system("cls");
logo();
error = false;
cout <> firstRows;
cout <> firstCols;
CreateMatrix(firstMatrix, firstRows, firstCols);
cout << endl;
cout <> secondRows;
cout <> secondCols;
CreateMatrix(secondMatrix, secondRows, secondCols);
if (firstCols != secondRows)
{
cout << "\n\aОщибка! The number of columns in the first matrix is not equal to the number of rows in the second matrix(press any key to continue)" << endl;
pause = _getch();
error = true;
}
else if (repeat == 'R' || repeat == 'r' || repeat == 'К' || repeat == 'к')
{
cout << "\nПроверьте правильно ли вы ввели параметры матрицы." << endl
<< "Если вы неправильно ввели параметры, then press the R key to, to enter the parameters again" << endl
<< "(press any key to continue)" << endl;
repeat = _getch();
error = true;
}
if (firstRows == 0 || firstCols == 0 || secondRows == 0 || secondCols == 0)
{
cout << "\n\aОщибка! The number of rows or columns cannot be zero(press any key to continue)" << endl;
pause = _getch();
error = true;
}
} while (error);
do {
error = false;
system("cls");
logo();
cout << "\nЗаполните первую матрицу" << endl;
InputMatrix(firstMatrix, firstRows, firstCols);
OutputMatrix(firstMatrix, firstRows, firstCols);
cout << "\nПроверьте правильно ли вы ввели данные в матрицу." << endl
<< "Если вы неправильно ввели данные, then press the R key to, to enter data again" << endl
<< "(press any key to continue)" << endl;
repeat = _getch();
if (repeat == 'R' || repeat == 'r' || repeat == 'К' || repeat == 'к')
{
error = true;
}
} while (error);
do {
error = false;
system("cls");
logo();
cout << "Первая матрица: " << endl;
OutputMatrix(firstMatrix, firstRows, firstCols);
cout << "Заполните вторую матрицу" << endl;
InputMatrix(secondMatrix, secondRows, secondCols);
OutputMatrix(secondMatrix, secondRows, secondCols);
cout << "\nПроверьте правильно ли вы ввели данные в матрицу." << endl
<< "Если вы неправильно ввели данные, then press the R key to, to enter data again" << endl
<< "(press any key to continue)" << endl;
repeat = _getch();
if (repeat == 'R' || repeat == 'r' || repeat == 'К' || repeat == 'к')
{
error = true;
}
} while (error);
do {
error = false;
system("cls");
logo();
cout << "Первая матрица: " << endl;
OutputMatrix(firstMatrix, firstRows, firstCols);
cout << "Вторая матрица: " << endl;
OutputMatrix(secondMatrix, secondRows, secondCols);
cout << "Выберите арифметическую операцию, which you want to accomplish with these matrices" << endl << endl;
cout << "1. Multiplication(the number of rows in the first matrix must be equal to the number of columns in the second matrix)" << endl;
cout << "2. Addition(matrices must be the same size)" << endl;
cout << "3. Subtraction(matrices must be the same size)" << endl;
CreateMatrix(resultMatrix, firstRows, secondCols);
char choice = _getch();
system("cls");
logo();
cout << "Первая матрица: " << endl;
OutputMatrix(firstMatrix, firstRows, firstCols);
cout << "Вторая матрица: " << endl;
OutputMatrix(secondMatrix, secondRows, secondCols);
switch (choice)
{
case '1':
for (int i = 0; i < firstRows; i )
{
for (int l = 0; l < secondCols; l++)
{
for (int j = 0; j < firstCols; j )
{
resultMatrix[i][l] += firstMatrix[i][j] * secondMatrix[j][l];
}
}
}
cout << "Результат умножения двух матриц: " << endl;
break;
case '2':
if (firstRows != secondRows && firstCols != secondCols)
{
cout << "Ощибка! Matrices must be the same size(press any key to continue)" << endl;
}
else
{
for (int i = 0; i < firstRows; i )
{
for (int j = 0; j < firstCols; j )
{
resultMatrix[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
}
}
cout << "Результат сложения двух матриц: " << endl;
}
break;
case '3':
if (firstRows != secondRows && firstCols != secondCols)
{
cout << "Ощибка! Matrices must be the same size(press any key to continue)" << endl;
}
else
{
for (int i = 0; i < firstRows; i )
{
for (int j = 0; j < firstCols; j )
{
resultMatrix[i][j] = firstMatrix[i][j] – secondMatrix[i][j];
}
}
cout << "Результат вычитания двух матриц: " << endl;
}
break;
}
OutputMatrix(resultMatrix, firstRows, secondCols);
} while (error);
DeleateMatrix(firstMatrix, firstRows, firstCols);
DeleateMatrix(secondMatrix, secondRows, secondCols);
DeleateMatrix(resultMatrix, firstRows, secondCols);
cout << "Нажмите любую клавишу чтобы продолжить" << endl; _getch();
}
return 0;
Can anyone suggest, why if int maxRowValue = arr[i][0],
gives an error message?
#include <iostream>
using namespace std;
int main()
{
int size = 5;
int** arr = new int *[size];
for (int i = 0; i < size; i )
{
arr[i] = new int[size];
}
for (int i = 0; i < size; i )
{
for (int j = 0; j < size; j )
{
arr[i][j] = 10 + rand() % + 89;
cout << arr[i][j] << "\t";
}
cout << endl;
}
cout << endl;
for (int i = 0; i < size; i )
{
int maxRowValue = 0; /*arr[i][0];*/
int *buf = 0;
for (int j = 0; j < size; j )
{
if (arr[i][j] > maxRowValue)
{
maxRowValue = arr[i][j];
buf = &(arr[i][j]);
}
}
*buf = arr[i][0];
arr[i][0] = maxRowValue;
}
for (int i = 0; i < size; i )
{
for (int j = 0; j < size; j )
{
cout << arr[i][j] << "\t";
}
cout << endl;
}
for (int i = 0; i < size; i )
{
delete[] arr[i];
} delete[]arr;
}
#include <iostream>
using namespace std;
int main()
{
int size = 5;
int** arr = new int *[size];
for (int i = 0; i < size; i )
{
arr[i] = new int[size];
}
for (int i = 0; i < size; i )
{
for (int j = 0; j < size; j )
{
arr[i][j] = 10 + rand() % + 89;
cout << arr[i][j] << "\t";
}
cout << endl;
}
cout << endl;
for (int i = 0; i < size; i )
{
int maxRowValue = 0; /*arr[i][0];*/
int *buf = 0;
for (int j = 0; j < size; j )
{
if (arr[i][j] > maxRowValue)
{
maxRowValue = arr[i][j];
buf = &(arr[i][j]);
}
}
*buf = arr[i][0];
arr[i][0] = maxRowValue;
}
for (int i = 0; i < size; i )
{
for (int j = 0; j < size; j )
{
cout << arr[i][j] << "\t";
}
cout << endl;
}
for (int i = 0; i < size; i )
{
delete[] arr[i];
} delete[]arr;
}
good afternoon,on your website, when clicking on “+” code does not appear
#include
#include
#include
using namespace std;
int main (){
const int SIZE = 5;
srand(time(NULL));
int arr[SIZE][SIZE];
for(int i=0;i<SIZE;i ){
for (int j = 0; j < SIZE; j ){
arr[i][j]= 10 + rand() % 90;
}
}
for(int i=0;i<SIZE;i ){
for (int j = 0; j < SIZE; j ){
cout << arr[i][j] << '\t';}
cout << endl;}
for(int i=0;i<SIZE;i ){
int j,k;
int *max;
max = &arr[i][0];
int **first;
first = &max;
for( j=0;j *max){
max=&arr[i][j];}}
k = **first;
*max = arr[i][0];
arr[i][0] = k;
}
cout << endl << endl << endl;
for(int i=0;i<SIZE;i ){
for (int j = 0; j < SIZE; j ){
cout << arr[i][j] << '\t';}
cout << endl;}
return 0;
}
Only fills itself, #Lazy People's Lives are Important
#include
#include
int main()
{
setlocale(LC_ALL, “rus”);
srand(time(NULL));
int rows1 = 0;
int both = 0;
int cols2 = 0;
std::cout <> rows1;
std::cout <> both;
std::cout <> cols2;
int** dArray1 = new int* [rows1]; // Allocation of memory for the first matrix
for (int i = 0; i < rows1; i )
{
dArray1[i] = new int[both];
}
int** dArray2 = new int* [both]; // Allocation of memory for the second matrix
for (int i = 0; i < both; i )
{
dArray2[i] = new int[cols2];
}
int** dArray3 = new int* [rows1]; // Allocation of memory for the third matrix
for (int i = 0; i < rows1; i )
{
dArray3[i] = new int[cols2];
}
for (int i = 0; i < rows1; i ) // Filling the first matrix with numbers from 1 to 9
{
for (int j = 0; j < both; j )
{
dArray1[i][j] = 1 + rand() % 9;
}
}
for (int i = 0; i < rows1; i ) // Output of the first matrix
{
for (int j = 0; j < both; j )
{
std::cout << dArray1[i][j] << " | ";
}
std::cout << "\n";
}
std::cout << "\n\n\n";
for (int i = 0; i < both; i ) // Filling the second matrix with numbers from 1 to 9
{
for (int j = 0; j < cols2; j )
{
dArray2[i][j] = 1 + rand() % 9;
}
}
for (int i = 0; i < both; i ) // Output of the second matrix
{
for (int j = 0; j < cols2; j )
{
std::cout << dArray2[i][j] << " | ";
}
std::cout << "\n";
}
std::cout << "\n\n\n";
for (int i = 0; i < rows1; i )
{
for (int j = 0; j < cols2; j )
{
int buffer = 0;
for (int c = 0; c < both; c++)
{
buffer += dArray1[i][c] * dArray2[c][j];
}
dArray3[i][j] = buffer;
}
}
for (int i = 0; i < rows1; i )
{
for (int j = 0; j < cols2; j )
{
std::cout << dArray3[i][j] << " | ";
}
std::cout << "\n";
}
for (int i = 0; i < rows1; i ) {
delete[] dArray1[i];
}
delete[] dArray1;
for (int i = 0; i < both; i ) {
delete[] dArray2[i];
}
delete[] dArray2;
for (int i = 0; i < rows1; i ) {
delete[] dArray3[i];
}
delete[] dArray3;
return 0;
}