Заполнить матрицу
A размерности n*m случайными числами. Переписать в массив B элементы aii первой главной диагонали матрицы A, в массив C — элементы другой главной диагонали матрицы A. Полученные массивы вывести на экран в виде таблицы из трех колонок.Если захотите сделать программу более изящной воспользуйтесь статьей — динамические массивы. В конце программы не забываем освобождать память под выделенные массивы.
// matrix_a.cpp: определяет точку входа для консольного приложения.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int main(int argc, char* argv[])
{
srand(time(0)); // генерация случайных чисел
cout << "Enter the number of rows: "; // введите количество строк
int rows_number = 0;
cin >> rows_number;
cout << "Enter the number of columns: "; // введите количество столбцов
int columns_number = 0;
cin >> columns_number;
// динамическое создание двумерного массива вещественных чисел на десять элементов
int **ptrarray_a = new int* [rows_number]; // строки в массиве
for (int count = 0; count < rows_number; count++)
ptrarray_a[count] = new int [columns_number]; // столбцы
// заполнение массива
for (int count_row = 0; count_row < rows_number; count_row++)
for (int count_column = 0; count_column < columns_number; count_column++)
ptrarray_a[count_row][count_column] = rand() % 10 + 1; //заполнение массива случайными числами с масштабированием от 1 до 10
for (int count_row = 0; count_row < rows_number; count_row++)
{
for (int count_column = 0; count_column < columns_number; count_column++)
cout << setw(2) << ptrarray_a[count_row][count_column] << " "; //вывод массива
cout << endl;
}
int b_size_array =0; // переменная хранящая размер массивов B и С
rows_number < columns_number ? b_size_array = rows_number : b_size_array = columns_number; // определяем размер одномерных массиво В и С
int *ptrarray_b = new int [b_size_array];
int *ptrarray_c = new int [b_size_array];
for (int counter = 0; counter < b_size_array; counter++)
{
ptrarray_b[counter] = ptrarray_a[counter][counter];// переписать в массив B элементы aii главной диагонали матрицы A
ptrarray_c[counter] = ptrarray_a[counter][b_size_array - 1 - counter]; // переписать в массив C элементы второй главной диагонали матрицы A
}
// вывод трёх столбцов
cout << endl;
int count_column_a = 0, count_rows_b = 0, out_counter= 0; // вспомогательные переменны для вывода
for (int count_row = 0; count_row < (columns_number*rows_number); count_row++)
{
cout << setw(4) << ptrarray_a[count_rows_b][count_column_a] << " ";
count_column_a++;
if (count_column_a == columns_number)
{
count_column_a = 0;
count_rows_b++;
}
if (out_counter <= (b_size_array - 1))
{
cout << ptrarray_b[count_row] << " " << setw(4) << ptrarray_c[count_row] << " ";
out_counter++;
}
cout << endl;
}
delete [] ptrarray_b; // высвобождение памяти массива B
delete [] ptrarray_c; // высвобождение памяти массива C
// удаление двумерного динамического массива
for (int count = 0; count < 2; count++)
delete []ptrarray_a[count];
system("pause");
return 0;
}
Итак, программа генерирует случайные числа в диапазоне [1;10] и заполняет ими двумерный массив, после чего выводит его на экран. Массивы B и С заполняются элементами главных диагоналей, после этого все три массива выводятся на экран в три столбца (см. Рисунок 1). Все используемые в программе массивы объявлены динамически, что соответствует хорошему тону программирования.
CppStudio.com
Enter the number of rows: 4 Enter the number of columns: 5 8 2 5 5 9 8 5 4 3 1 10 1 2 5 8 5 10 5 1 6 8 8 5 2 5 4 5 2 1 5 1 5 9 8 5 4 3 1 10 1 2 5 8 5 10 5 1 6
Комментарии
Alex Antonyuk
/* Fill the matrix A of dimension n * m random numbers. Rewrite the array B elements aii first main diagonal of the matrix A, in an array of C - the other elements of the main diagonal of the matrix A. The resulting arrays to display a table of three columns. http://cppstudio.com/post/1306/ by Oleksiy Antonyuk alex.antonyuk17@gmail.com 17.02.2017 */ #include <iostream> #include <vector> #include <stdlib.h> #include <ctime> #include <iomanip> using namespace std; int main() { int n, m; cout << "Rows: "; cin >> n; cout << "Columns: "; cin >> m; srand ( time(0) ); int matrix[n][m]; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { matrix[i][j] = rand() % 99; cout << setw(3) << matrix[i][j]; } cout << endl; } vector <int> first; vector <int> second; for (int i = 0, j = 0; i < n && j < m; ++i, ++j) { first.push_back(matrix[i][j]); } for (int i = n - 1, j = 0; i >= 0 && j < m; --i, ++j) { second.push_back(matrix[i][j]); } cout << endl; for (int i = 0; i < first.size(); ++i) { cout << setw(3) << first[i] << setw(3) << second[i] << endl; } return 0; }