Matrix transposed with pointer-to-pointer in c++ - c++

I am trying to transpose a matrix with pointer-to-pointer in c++ but there is an error: "segmentation fault ('core' dumped)". I tried to find the error on forums and figured out that in matrixTrans function, the 'puntero_trans = new int *[nCol];' line and the for loop next to it, I had to move to getData function. I really do not know why this happens. Thanks for your time. My code below:
#include <iostream>
void getData();
void matrixTrans(int **, int **,int, int);
void showData(int **, int, int);
//Global variables
int **puntero_matrix = nullptr, **puntero_trans;
int nRaws, nCol;
int main() {
getData();
matrixTrans(puntero_matrix,puntero_trans,nRaws,nCol);
showData(puntero_trans, nRaws,nCol);
//Flushing memory...
for (int i = 0; i < nRaws; ++i) {
delete[] puntero_matrix[i];
}
for (int i = 0; i < nCol; ++i) {
delete[] puntero_trans[i];
}
delete[] puntero_matrix;
delete[] puntero_trans;
std::cin.get();
return 0;
}
void getData() {
std::cout << "Please enter the number of raws:"; std::cin >> nRaws;
std::cout << "Please enter the number of columns: "; std::cin >> nCol;
puntero_matrix = new int* [nRaws];
for (int i = 0; i < nRaws; ++i) {
puntero_matrix[i] = new int[nCol];
}
for (int i = 0; i < nRaws; ++i) {
for (int j = 0; j < nCol; ++j) {
std::cout << "Please enter value for [" << i << "][" << j << "]: "; std::cin >> *(*(puntero_matrix + i) + j);
}
}
}
void matrixTrans(int **puntero_matrix, int **puntero_trans, int nRaws, int nCol) {
puntero_trans = new int *[nCol];
for (int i = 0 ; i < nCol; ++i) {
puntero_trans[i] = new int[nRaws];
}
for (int i = 0; i < nRaws; ++i) {
for (int j = 0; j < nCol; ++j) {
*(*(puntero_trans + j) + i) = *(*(puntero_matrix + i) + j);
}
}
}
void showData(int **puntero_trans,int nRaws,int nCol) {
for (int i = 0; i < nCol; ++i) {
for (int j = 0; j < nRaws; ++j) {
std::cout << *(*(puntero_trans + i) + j) << " ";
}
std::cout << std::endl;
}
}

Related

Magic Number output

Alright so I have created this code. However, when i run it, it stops when it displays 104 for the counter??? I am so frustrated because I don't know how this could happen. The purpose of the code is to do the typical magic number output where the rows all add up to the same thing, the columns all add up to the same thing, and the diaganols all add up to the same thing. I believe the functions to do these calculations are correct, but the counter keeps stopping short of the 10000 attempts I am trying to do.
#include <iostream>
#include<time.h>
#include<stdlib.h>
using namespace std;
void getrandom();
void insertnumber(int n);
bool magic();
void create();
const int rows = 3;
const int cols = 3;
int arr[rows][cols] = { {0,0,0}, {0,0,0} , {0,0,0} };
int main() {
int counter = 0;
do
{
counter++;
cout << counter << endl;
getrandom();
if (counter == 100000)
break;
} while (!magic());
create();
cout << "It took " << counter << " tries." << endl;
return 0;
}
void getrandom() {
int n = 0;
const int size = 9;
int oldnum[size];
for (int i = 0; i < rows * cols; i++) {
oldnum[i] = 0;
}
srand(time(NULL)); // had to import the new libraries to use this
bool used = true;
for (int i = 0; i < size; i++) {
do
{
used = true;
n = rand() % 9 + 1;
if (oldnum[n - 1] == 0)
{
oldnum[n - 1] = n;
used = false;
}
} while (used);
insertnumber(n);
}
}
void insertnumber(int n) {
for (int i = 0; i < rows; i++) {
for (int j = 0; i < cols; j++) {
if (arr[i][j] == 0) {
arr[i][j] = n;
return;
}
}
}
}
bool magic() {
int rowsum = arr[0][0] + arr[0][1] + arr[0][2];
for (int i = 1; i < cols; i++)
{
if (arr[i][0] + arr[i][1] + arr[i][2] != rowsum)
return false;
}
for (int j = 0; j < rows; j++)
{
if (arr[0][j] + arr[1][j] + arr[2][j] != rowsum)
return false;
}
if (arr[0][0] + arr[1][1] + arr[2][2] != rowsum)
return false;
if (arr[0][2] + arr[1][1] + arr[2][0] != rowsum)
return false;
return true;
}
void create() {
{
for (int i = 0; i < rows; i++) {
for (int j = 0; i < cols; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
}
You can try using a debugger for such problems.
I think you code crashes because of this:
for (int i = 0; i < rows; i++) {
for (int j = 0; i < cols; j++) {
It looks like you mean j < cols here :)
Check line 76. When I compile and run the code, line 76 is where the exception is thrown.
This line specifically
arr[i][j] = n;
It seems your insertnumber() function is the culprit.

Add the Edges of 2D array and return its answer

What's wrong with my code
I Have to add all the edge values of the 2D Array.
The Function is not returning what I want. Its returning garbage value.
Program Req Output : Add all the edges value of the 2D Array and return its answer.
You are not allowed to use Vector etc.
Here is my Code :
#include <iostream>
using namespace std;
const int rows = 3;
const int cols = 4;
void AddEdges (int arr[rows][cols])
{
int sum = 0;
int totalOfEdges = 0;
int i,j;
int k = 0;
int l = 0;
for (i = 1; i <= rows; i++)
{
for (j = 1; j <= cols; j++)
{
if (i == 1 || i == rows || j == 1 || j == cols)
{
sum = arr[k][l];
totalOfEdges = sum + totalOfEdges;
}
l++;
}
k++;
}
cout << "Total of Edges = " << totalOfEdges << endl;
}
int main()
{
int arr[3][4] = {0};
cout << "Enter Elements for Array = \n";
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cin >> arr[i][j];
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
AddEdges(arr);
}
My Output :
Leaving the Correct Code in Case Any one need it .
#include <iostream>
using namespace std;
const int rows = 3;
const int cols = 4;
void AddEdges (int arr[rows][cols])
{
int sum = 0;
int totalOfEdges = 0;
int i,j;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
if (i == 0 || i == (rows-1) || j == 0 || j == (cols-1))
{
sum = arr[i][j];
totalOfEdges = sum + totalOfEdges;
}
}
}
cout << "Total of Edges = " << totalOfEdges << endl;
}
int main()
{
int arr[3][4] = {0};
cout << "Enter Elements for Array = \n";
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cin >> arr[i][j];
}
}
cout << "--------" << endl;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
AddEdges(arr);
}

Sort rows of two-dimensional array in ascending order according to sum of all positive even elements in every row C++

So I need to find sum of all positive even numbers in every row (which I've already done actually). And then I have to sort these rows depending on their sums
As I think, it must be done in one function (otherwise there will be no connections as I cannot use global variables). In my case it's void print:
void print(const int** arr, int rows, int columns) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
cout << setw(7) << arr[i][j];
}
cout << endl;
}
int sum = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (arr[i][j] > 0 && arr[i][j] % 2 == 0)
{
//cout << setw(7) << arr[i][j];
sum = sum + arr[i][j];
}
}
cout << endl << "Sum of positive even elements in the row " << i + 1 << " = " << sum;
sum = 0;
}
}
Full code:
#include <iostream>
#include <iomanip>
#include <time.h>
#include <conio.h>
#include <algorithm>
using namespace std;
int** createMalloc(int, int);
int** createCalloc(int rows, int columns);
int** createNew(int rows, int columns);
void deleteNew(int** arr, int rows);
void init(int**, int, int);
void freeMemory(int**, int);
void print(const int**, const int, const int);
void initPrint(int** arr, int rows, int columns);
void main() {
int rowCount, colCount;
cout << "Enter number of rows: "; cin >> rowCount;
cout << "Enter number of columns: "; cin >> colCount;
cout << " Array creation algorithm\n";
start:
cout << "Input number : \n1 for malloc\n2 for calloc\n3 for new\n";
int k;
cin >> k;
switch (k) {
case 1: {
int** a = createMalloc(rowCount, colCount);
initPrint(a, rowCount, colCount);
freeMemory(a, rowCount);
break;
}
case 2: {
int** a = createCalloc(rowCount, colCount);
initPrint(a, rowCount, colCount);
freeMemory(a, rowCount);
break;
}
case 3: {
int** a = createNew(rowCount, colCount);
initPrint(a, rowCount, colCount);
deleteNew(a, rowCount);
break;
}
default:cout << "Input 1, 2 or 3, please.";
cout << endl << endl;
goto start;
}
cout << endl << endl;
}
int** createMalloc(int rows, int columns) {
int** arr = (int**)malloc(rows * sizeof(int*));
for (int i = 0; i < rows; i++) {
arr[i] = (int*)malloc(columns * sizeof(int));
}
return arr;
}
int** createCalloc(int rows, int columns) {
int** arr = (int**)calloc(rows, sizeof(int*));
for (int i = 0; i < rows; i++) {
arr[i] = (int*)calloc(columns, sizeof(int));
}
return arr;
}
int** createNew(int rows, int columns) {
int** arr = new int* [rows];
for (int i = 0; i < rows; i++) {
arr[i] = new int[columns];
}
return arr;
}
void initPrint(int** arr, int rows, int columns) {
init(arr, rows, columns);
print((const int**)arr, rows, columns);
}
void init(int** arr, int rows, int columns) {
const int Low = -2, High = 4;
srand((unsigned)time(NULL));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
arr[i][j] = Low + rand() % (High - Low + 1);
}
}
}
void freeMemory(int** arr, int rows) {
for (int i = 0; i < rows; i++) {
free(arr[i]);
}
free(arr);
}
void deleteNew(int** arr, int rows) {
for (int i = 0; i < rows; i++) {
delete[] arr[i];
}
delete[] arr;
}
void print(const int** arr, int rows, int columns) {
// виведення масива на екран
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
cout << setw(7) << arr[i][j];
}
cout << endl;
}
int sum = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (arr[i][j] > 0 && arr[i][j] % 2 == 0)
{
//cout << setw(7) << arr[i][j];
sum = sum + arr[i][j];
}
}
cout << endl << "Sum of positive even elements in the row " << i + 1 << " = " << sum;
sum = 0;
}
}
P.S. Two-dimensional arrays must be necessarily dynamic ones. Also, cannot do this task using vector. Only malloc, calloc and new

Wondering what I am doing wrong with this program?

I am trying to get the program to run from 4 column of the seasons, and 2 columns for years 2016 and 2017. The input is rainfall for both years for each season. It is allowing me to enter numbers for times for winter and then stops and it is not calculating right. Any help as to what I am doing wrong?
#include <iostream>
#include <string>
using namespace std;
void Read(double rainfall[][4], int row);
void Calculate(double rainfall[][4], int row);
void Write(double rainfall[][4], int row);
int main()
{
double rainfall[2][4];
int row = 2;
Read(rainfall, row);
Calculate(rainfall, row);
Write(rainfall, row);
}
void Read(double rainfall[][4], int row)
{
for (int i = 0; i < row - 1; i++)
{
if (i == 0)
cout << "Enter rainfall for Winter: " << endl;
else if (i == 1)
cout << "Enter rainfall for Spring: " << endl;
else if (i == 2)
cout << "Enter rainfall for Summer: " << endl;
for (int j = 0; j < 2; j++)
{
cout << j + 1 << " : " << endl;
cin >> rainfall[i][j];
}
}
}
void Calculate(double rainfall[2][4], int row)
{
int i, j;
double row_sum;
for (i = 0; i < row; i++)
{
row_sum = 0;
for (j = 0; j < 4; j++)
{
row_sum = row_sum + rainfall[i][j];
}
rainfall[i][4] = row_sum;
}
double col_sum;
for (j = 0; j < 4; j++)
{
col_sum = 0;
for (i = 0; i < row - 1; i++)
{
col_sum = col_sum + rainfall[i][j];
}
rainfall[2][j] = col_sum;
}
}
void Write(double rainfall[][4], int row)
{
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < 4; j++)
cout << rainfall[i][j] << " ";
cout << endl;
}
}
Change this line
for (int i = 0; i < row - 1; i++)
to
for (int i = 0; i < row; i++)
In C++, you should use std::vector or std::array instead and avoid C style arrays, that way you get better help when you go out-of-bounds with your array which I think is happening in more places than one.

2D (Maximum From Each Column)

After trying a lot of times and thinking again and again.. It feels like a frustrated person.
I'm here to get some suggestions from you guys..
Actually I'm trying to find the maximum of each ROW and COLUMN.
So by using divide and conquer technique, I write two separate functions one for finding max of each row and store it to row vector that i used as an argument. Respectively for columns.
void maxValuesR(int a[][cols], int rv[], int row)
void maxValuesC(int a[][cols], int cv[], int row)
PROBLEM: The code is not even compile, I just don't understnd the errors..
Please Help..
I Really Need Your Help Here!
The code is as follow:
#include <iostream>
using namespace std;
const int rows = 2; // Declared As Global Variable
const int cols = 3; // Declared As Global Variable
void getData(int arr[][cols], int rows)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
cout << "Enter Element: ";
cin >> arr[i][j];
}
}
}
void printData(int a[][cols], int rows)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
cout << a[i][j] << "\t";
}
cout << endl;
}
}
void print_single(int a[], int row)
{
for(int i = 0; i < row; i++)
{
cout << a[i] << "\t";
}
}
void maxValuesR(int a[][cols], int rv[], int row)
{ int foxi;
for(int i = 0; i < row; i++)
{
foxi = a[i][0];
for(int j = 0; j < cols; j++)
{
if(foxi < a[i][j])
{
foxi = a[i][j];
}
}
rv[i] = foxi;
}
}
void maxValuesC(int a[][cols], int cv[], int row)
{
int maxi;
for(int i = 0; i < cols; i++)
{
maxi = a[0][i];
for(int j = 0; j < row; j++)
{
if(maxi > a[j][i])
{
maxi = a[j][[i];// show error here => expected a '{' introducing lambda body
}
}
cv[i] = maxi;
}
}
int main()
{
int rowVector[rows];
int colVector[cols];
int a[rows][cols];
cout << "Fill Array_1. " << endl;
getData(a, rows);
cout << "Array_1." << "\n\n";
printData(a, rows); cout << endl;
maxValuesR(a, rowVector, rows);
print_single(rowVector, rows);
cout << "\n\n";
maxValuesC(a, colVector, rows);
print_single(colVector, rows);
return 0;
}
To clarify the compile errors:
You forgot the include (or didn't write it here?) #include <iostream>
You didn't specify the namespace for cin, cout and endl (they are in std namespace)
You had a superfluous "[" in the statement a[j][[i], by all likelihood you wanted to write a[j][i]
The compiling code looks like this:
#include <iostream>
const int rows = 2; // Declared As Global Variable
const int cols = 3; // Declared As Global Variable
void getData(int arr[][cols], int rows)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
std::cout << "Enter Element: ";
std::cin >> arr[i][j];
}
}
}
void printData(int a[][cols], int rows)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
std::cout << a[i][j] << "\t";
}
std::cout << std::endl;
}
}
void print_single(int a[], int row)
{
for(int i = 0; i < row; i++)
{
std::cout << a[i] << "\t";
}
}
void maxValuesR(int a[][cols], int rv[], int row)
{ int foxi;
for(int i = 0; i < row; i++)
{
foxi = a[i][0];
for(int j = 0; j < cols; j++)
{
if(foxi < a[i][j])
{
foxi = a[i][j];
}
}
rv[i] = foxi;
}
}
void maxValuesC(int a[][cols], int cv[], int row)
{
int maxi;
for(int i = 0; i < cols; i++)
{
maxi = a[0][i];
for(int j = 0; j < row; j++)
{
if(maxi > a[j][i])
{
maxi = a[j][i];
}
}
cv[i] = maxi;
}
}
int main()
{
int rowVector[rows];
int colVector[cols];
int a[rows][cols];
std::cout << "Fill Array_1. " << std::endl;
getData(a, rows);
std::cout << "Array_1." << "\n\n";
printData(a, rows);
std::cout << std::endl;
maxValuesR(a, rowVector, rows);
print_single(rowVector, rows);
std::cout << "\n\n";
maxValuesC(a, colVector, rows);
print_single(colVector, rows);
return 0;
}
Can't tell whether it produces the output you want, though, because you didn't specify any example input (let alone the corresponding expected output)...