Calculate the sum in the rows of the array - c++

I have a two-dimensional array A. I need
the elements of the array are written to the elements of the dynamic array elements record the calculated sum of the row of the array A. The dynamic array elements are displayed using pointers.
const unsigned row = 3;
const unsigned col = 4;
int A[row][col];
std::cout << "Input A:\n";
for (int index = 0; index < row; ++index)
{
for (int j = 0; j < col; ++j)
{
std::cout << "A[" << index << "][" << j << "]=";
std::cin >> A[index][j];
}
}
unsigned* array = new unsigned[row];
for (int index = 0; index < row; ++index)
{
for (int j = 0; j < col; ++j)
{
array[index] += A[index][j];
}
}
for (unsigned* index = array; *index; ++index)
{
std::cout << *index << "\n";
}
But alas, it does not work properly. Help me figure it out.
UPD:
unsigned* end = array + row + 1;
std::cout << "Array:\n";
for (unsigned *ptr = array, index = 1; ptr <= end; ++ptr, ++index)
{
std::cout << *ptr << "\t";
}

You never initialized the array so this line has undefined behavior:
array[index] += A[index][j];
You can simply fix if with:
for (int index = 0; index < row; ++index) {
array[index] = 0;
}
Or:
for (int index = 0; index < row; ++index) {
unsigned sum = 0;
for (int j = 0; j < col; ++j) {
sum += A[index][j];
}
array[index] = sum;
}
And the last output can be changed too. Your version reads out of bounds so yet another undefined behavior.
for (int index = 0; index < row; ++index) {
std::cout << array[index] << "\n";
}

Related

Find the column with the maximum negative matrix element and the column with the minimum element

I want to know the column with the maximum negative matrix element and the column with the minimum element so that I can rearrange them. More specifically, I'm interested in return values of The column with the maximum negative element: and The column with the minimum element: But about half the time, the results about which columns they are return completely wrong. The interesting thing is that the results don't always come back wrong. What am I doing wrong?
#include <iostream>
#include <time.h>
#include <cmath>
using namespace std;
int main(void) {
// random number for rand()
srand(time(0));
int m = 5; // row count
int n = 5; // column count
// declaration of a dynamic array of pointers
double **arr = (double**) malloc(n * sizeof(double));
// filling the array with pointers
for (int i = 0; i < n; i++)
arr[i] = (double*) malloc(m * sizeof(double));
// array initialization with random numbers
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = (double) (rand() % 400 - 199) / 2.0; // (-100.0; 100.0)
// matrix output
cout << "\n\033[92mOriginal array:\033[94m" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
printf("%5.1f ", arr[i][j]);
cout << endl;
}
// array for the sums of modules of the row elements
float *sumOfAbsolutes = (float*) malloc(m * sizeof(float));
// Initializing the array with zeros
for (int i = 0; i < m; i++) sumOfAbsolutes[i] = 0;
// filling the array with the sums of element modules
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
sumOfAbsolutes[i] += abs(arr[i][j]);
// output
cout << "\n\033[92mSums of modules of array row elements:" << endl;
for (int i = 0; i < m; i++)
cout << "\033[92m" << i << ": \033[94m"<< sumOfAbsolutes[i] << " ";
cout << "\n\n";
// sorting
for (int i = 0; i < (m - 1); i++)
for (int j = i; j < m; j++)
if (sumOfAbsolutes[i] > sumOfAbsolutes[j]) {
double tmp = sumOfAbsolutes[i];
sumOfAbsolutes[i] = sumOfAbsolutes[j];
sumOfAbsolutes[j] = tmp;
double *tmp2 = arr[i];
arr[i] = arr[j];
arr[j] = tmp2;
}
// matrix output
cout << "\033[92mSorted array:\033[94m" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
printf("%5.1f ", arr[i][j]);
cout << endl;
}
int columnWithMaxNegNum = 0; // the column with the maximal negative element
int minNumber = 0; // the column with the minimum element
// search for the maximal negative element
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (arr[i][j] < 0 && arr[i][j] > arr[i][columnWithMaxNegNum])
columnWithMaxNegNum = j;
// minimum element search
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (arr[i][j] < arr[i][minNumber]) minNumber = j;
cout << "\n\033[92mThe column with the maximum negative element: \033[94m" << columnWithMaxNegNum << endl;
cout << "\033[92mThe column with the minimum element: \033[94m" << minNumber << endl;
// rearrangement of columns
for (int i = 0; i < m; i++) {
double temp = arr[i][columnWithMaxNegNum];
arr[i][columnWithMaxNegNum] = arr[i][minNumber];
arr[i][minNumber] = temp;
}
cout << "\n\033[92mRearrangement of columns:" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
printf("\033[94m%5.1f ", arr[i][j]);
cout << "\n\033[0m";
}
// memory cleanup
free(sumOfAbsolutes);
for (int i = 0; i < n; i++)
free(arr[i]);
free(arr);
}
I assume that this is some kind of homework, since normally, we'd use vectors and algorithms to write much shorter code.
The following loop doesn't find the maximal negative:
// search for the maximal negative element
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (arr[i][j] < 0 && arr[i][j] > arr[i][columnWithMaxNegNum])
columnWithMaxNegNum = j;
Because the the search is dependent of the line. You'd need to go for:
double maxNegNum = -100.0; // tbd
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (arr[i][j] < 0 && arr[i][j] > maxNegNum) {
columnWithMaxNegNum = j;
maxNegNum = arr[i][j];
}
The same applies for the minimum :
double minN=100.0;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (arr[i][j] < minN) {
minNumber = j;
minN = arr[i][j];
}
Not related: if you go for C++ forget malloc and free, and use new/delete and new[]/delete[] instead. Here a first attempt: Online demo
Caution/Limitations:
If by no negative number are found, the maximum negative value would be inaccurate.
If several equal maximum negative values and minimum values are found, only the first one( from left to right and to bottom) will be considered.

How to delete column in 2d array c++ with dynamic array?

I want to delete column with max integer in 2d array, I do it in this way, but why is deleting the column and also row? Can I fix that and delete only column? The task was do it with delete command, but now I think it's impossible
#include <iostream>
using namespace std;
int main()
{
int row = 3, col = 3;
int** arr = new int* [row];
for(int i = 0; i < row; i++){
arr[i] = new int[col];
}
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++) {
cin >> arr[i][j];
}
}
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
cout << " ------------- " << endl;
int max = 0, index = 0;
for(int i =0; i < row; i++){
for(int j = 0; j < col; j++){
if(arr[i][j] > max){
max = arr[i][j];
index = i;
}
}
}
delete [] arr[index];
int** tmp = new int*[index - 1];
int tmpI = 0;
for(int i = 0; i < col; i++){
if(i != index){
tmp[tmpI++] = arr[i];
}
}
delete [] arr;
arr = tmp;
col = col - 1;
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
For starters the variable index is set to a row number
index = i;
Then this row is deleted
delete [] arr[index];
But you are going to remove a column instead of a row. So this code does not make a sense.
Also you are incorrectly searching the maximum element. If the user will enter all negative values then the maximum value will be equal to 0 though an element with such value is not present in the array.
In this declaration
int** tmp = new int*[index - 1];
you allocated an array with rows that one less than the number of rows in the original array. Moreover if index is equal to 0 then there is allocated a very large extent of memory.
This statement
delete [] arr;
produces a memory leak.
It seems what you need is something like the following
#include <iostream>
int main()
{
size_t row = 3, col = 3;
int **arr = new int * [row];
for ( size_t i = 0; i < row; i++ )
{
arr[i] = new int[col];
}
for ( size_t i = 0; i < row; i++ )
{
for ( size_t j = 0; j < col; j++ )
{
std::cin >> arr[i][j];
}
}
for ( size_t i = 0; i < row; i++ )
{
for ( size_t j = 0; j < col; j++ )
{
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << "------------- " << std::endl;
size_t max_i = 0, max_j = 0;
for ( size_t i = 0; i < row; i++ )
{
for ( size_t j = 0; j < col; j++ )
{
if ( arr[max_i][max_j] < arr[i][j] )
{
max_i = i; max_j = j;
}
}
}
int **tmp = new int*[row];
for ( size_t i = 0; i < row; i++ )
{
tmp[i] = new int[col-1];
}
for ( size_t i = 0; i < row; i++ )
{
for ( size_t j = 0, k = 0; j < col; j++ )
{
if ( j != max_j ) tmp[i][k++] = arr[i][j];
}
}
for ( size_t i = 0; i < row; i++ )
{
delete [] arr[i];
}
delete [] arr;
arr = tmp;
--col;
for ( size_t i = 0; i < row; i++ )
{
for ( size_t j = 0; j < col; j++ )
{
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}
for ( size_t i = 0; i < row; i++ )
{
delete [] arr[i];
}
delete [] arr;
return 0;
}
The program output might look like
1 2 3
6 5 4
7 9 8
-------------
1 3
6 4
7 8
Here's an alternate suggestion: You are storing the data in row x column format. If you change to column x row format, it becomes easier to delete a column. I also made a helper function to print the matrix and I combined the input loop and the loop that finds the max.
#include <iostream>
#include <iomanip>
#include <cstdlib> // for rand
#include <climits>
using namespace std;
void print_matrix(int** arr, int rows, int columns)
{
for(int row = 0; row < rows; row++){
for(int col = 0; col < columns; col++) {
cout << setw(2) << arr[col][row] << " ";
}
cout << "\n";
}
}
int main()
{
srand(time(nullptr)); // For testing
int rows = 3, columns = 3;
// Create the matrix
int** arr = new int *[columns];
for (int col = 0; col < columns; col++) {
arr[col] = new int[rows];
}
// Input values - finding max, too
int max_value = INT_MIN, max_value_column = -1;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < columns; col++) {
//cin >> arr[col][row];
arr[col][row] = rand() % 50; // Using rand for testing.
if (arr[col][row] > max_value) {
max_value = arr[col][row];
max_value_column = col;
}
}
}
print_matrix(arr, rows, columns);
cout << " ------------- " << endl;
// Delete the column with max
delete [] arr[max_value_column];
columns--;
// Shift columns to the right of the deleted column left one
for (int col = max_value_column; col < columns; col++) {
arr[col] = arr[col + 1];
}
print_matrix(arr, rows, columns);
return 0;
}

How to create a 2D array and calculate the average of it?

THE PROBLEM
Create a 4X3 integer array and fill it, column by column, with the odd numbers starting with 1. In a separate, one dimensional array, store the average of each column of the 4X3 array. Output the 4X3 array (as a 4X3 array) and output the average of each column underneath each column. Label these as the average.
#include <iostream>
using namespace std;
int main() {
// variables defined here
int i, j, A[4][3], average[3], sum = 0, oddnumber = 1;
for(i = 0; i < 3; i++) {
for(j = 0; j < 4; j++) {
A[j][i] = oddnumber;
oddnumber = oddnumber + 2;
sum = sum + A[j][i];
}
average[i] = sum / 4.0;
sum = 0;
}
// output
cout << "The Array is: \n";
for(i = 0; i < 4; i++) {
for(j = 0; j < 3; j++) {
cout << A[i][j] << "\n";
}
}
cout << "Average: \n";
for(i = 0; i < 3; i++) {
cout << average[i] << "\n";
}
}
When I run the program, the values does not appear in a table (2D array) but in one column only.
You get one column only because you output a newline (\n) after each number.
for(i = 0; i < 4; i++) {
for(j = 0; j < 3; j++) {
cout << A[i][j] << "\n"; // here
}
}
Instead, output the newline after each row has been printed. You may also want to insert a tab (\t) or space between the numbers in each row to not get a very long number as output:
for(i = 0; i < 4; i++) {
for(j = 0; j < 3; j++) {
std::cout << A[i][j] << '\t'; // a tab after each number in the row
}
std::cout << '\n'; // newline after the row is done
}

Swapping elements in 2d array

So, I'm trying to swap the matrix elements with respect to the main diagonal. I have tried using temp method (switching values while using temp variable), also tried std::swap(a,b). Somehow it only swaps upper right side of the matrix and leaves another half not changed.
How do I make everything swap?
My code:
#include <iostream>
using namespace std;
int main()
{
const int n = 7;
srand (time(NULL));
int matrix[n][n];
cout << "Original Matrix :" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
(i == j) ? matrix[i][j] = 0 : matrix[i][j] = rand() % 100+1;
cout << matrix[i][j] << "\t";
}
cout << endl;
}
cout << "\nRemade Matrix:" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
// swap(matrix[i][j], matrix[j][i]); //another method
cout << matrix[i][j] << "\t";
}
cout << endl;
}
return 0;
}
You are basically swapping them twice, replace your swapping loops with this. Notice the condition of the second loop, it's j < i. Then, you can print it with another set of loops.
for (int i = 0; i < n; i++)
for (int j = 0; j < i ; j++)
swap(matrix[i][j], matrix[j][i]);
Your logic is almost ok. Just the inner loop counter will start from "i+1" else after the swapping the value is again getting overlapped. Try the following code and make sure you understand it. Happy coding!
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << matrix[i][j] << "\t";
}
cout << endl;
}

How do I set all the diagonals in a matrix equal to zero?

I have a problem with my homework that asks me to have the compiler print out a matrix in which all the diagonals are outputted as zero. I also have to pass it to a function. However, I have no idea how to do this..
Here is my code:
#include <iostream>
using namespace std;
int diagonals();
int main()
{
//problem 1
int matrix[3][3];
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3 ; j++)
{
cout << "Row " << i << " column " << j<< ": ";
cin >> matrix[i][j];
}
}
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
cout << "\nReverse of the matrix:" << endl;
for (int j = 1; j <= 3; j++)
{
for (int i = 1; i <= 3; i++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}//end of problem 1
//problem 2
cout << "Diagonals changed to 0:\n" << endl;
}
your matrix declaration says int matrix[3][3]; that it has three 1-D array & in each 1-D array you can store three elements. And in C/C++ array index starts from zero.
Problematic statement is for (int i = 1; i <= 3; i++) as you are skipping matrix[0][0] and trying to store into matrix[3][3] which doesn't exist which in turn causes undefined behavior.
So firstly start iterating loop from 0 to number of rows & column respectively.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3 ; j++) {
cout << "Row " << i << " column " << j<< ": ";
cin >> matrix[i][j];
}
}
Coming to task you mentioned, print out a matrix in which all the diagonals are outputted as zero. ? write one condition so that if row value & col value are equal then assign it to zero otherwise scan from user. Here is the sample code
int main(void) {
int matrix[3][3] = { 0 }; /* initialize it */
int row = sizeof(matrix)/sizeof(matrix[0]); /* find no of rows */
int col = sizeof(matrix[0])/sizeof(matrix[0][0]);/* find no of columns */
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if( i == j)
matrix[i][j] = 0;/* when i and j are equal means thats diagonal and assign it to zero */
else /* if its not diagonal then scan from user */
std::cin>>matrix[i][j];
}
}
return 0;
}
Secondly, I also have to pass it to a function. for this learn how to pass 2d array to a function. Here is the sample example.
void diagonal(int (*mat)[3],int row, int col) { /* mat is pointer to an array */
std::cout<<"printing matrix "<<std::endl;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
std::cout<<mat[i][j]<<"\t";
}
std::cout<<std::endl;
}
}
And call diagonal() like below from main() function as
diagonal(matrix,row,col); /* pass matrix, no of rows, no of columns */