Multiplying 3x3 matrices in C++ [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm working on a program to multiply two 3X3 matrices together. I have hit a few problems and I can't figure out the problems. Any help would be appreciated :D
#include <iostream>
using namespace std;
int main(){
int matrix1[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int matrix2[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int results[3][3];
int product = 0;
int i;
int j;
for (i = 1; i <= 3; i++){
for (j = 1; j <= 3; j++){
product += matrix1[i][j] * matrix2[j][i];
cout << product << endl;
}
results[i][j] = product;
product = 0;
}
cout << endl << "Output Matrix: " << endl;
for (int i = 1; i < 4; i++){
for (int j = 1; j < 4; j++){
cout << results[i][j];
}
cout << endl;
}
system("pause");
return 0;
}
And this is the result I get out of it:
25
73
-1717986851
48
129
-858993331
-1867771963
1566576709
1595991863
Output Matrix:
-858993460-858993460-858993460
-1717986851-858993460-858993460
-85899333112
Press any key to continue . . .
Thanks again in advance! :D

So to begin with you don't need the int i, j; lines at the beginning. If you didn't have them there the compiler would correctly told you that results[i][j] = product; is in the wrong place. Also arrays' first value isn't at A[1] but at A[0]. And for the matrix multiplication I suggest you to read this.
Therefore the solution should look like this:
int matrix1[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int matrix2[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int results[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) {
for (int u = 0; u < 3; u++)
results[i][j] += matrix1[i][u] * matrix2[u][j];
}
cout << endl << "Output Matrix: " << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << results[i][j] << ".";
}
cout << endl;
}

Your code for matrix multiplication is wrong. Look at this literal implementation:
for (i = 0; i < 3; i++){
for (j = 0; j < 3; j++){
product = 0;
for (k = 0; k < 3; k++){
product += matrix1[i][k] * matrix2[k][j];
}
matrix3[i][j] = product;
}
}

Matrix multiplication is implemented the following way (for 2 N x N matrices):
for i = 1..N
for j = 1..N
result[i][j] = 0.
for k = 1..N
result[i][j] += matrix1[i][k] * matrix2[j][k] // "row times column"
end for
end for
end for
This will return you the product result = matrix1 * matrix2. In C++ you have to use e.g.
for (int i = 0; i < N; i++)
for a loop. You have to start with 0 and end with N-1 (that's why you use < and not <=). In your example set int N = 3.
You only use a delete for every new. So you do not need to delete arrays if you do not allocate the matrix dynamically.

Related

Need to find the sum of all even numbers in 2D array (then divide it on the amount of all even numbers to get the average value) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I think there's some stupid mistake of mine when I initialized two-dimensional array in 'while' or something
#include <iostream>
#include <iomanip>
using namespace std;
int sumOfEvenNumbers(int arr[], int Rows, int Columns) {
int s = 0;
for (int i = 0; i < Rows; i++) {
for (int j = 0; j < Columns; j++)
while (arr[i][j] % 2 == 0)
s += arr[i * Columns + j];
}
return s;
}
void main() {
const int rowCount = 4, colCount = 5;
int b[rowCount][colCount] = { { 2, 5, 6, 7, 0 }, { 8, 6, 4, 7, 1 }, { 3, 6, 1, 9, 5 }, { 5, 6, 7, 3, 2 } };
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < colCount; j++)
cout << setw(6) << b[i][j];
cout << endl;
}
cout << endl;
cout << "Sum = " << sumOfEvenNumbers(&b[0][0], rowCount, colCount);
}
Debugging details
What am I doing wrong?
Replace
while (arr[i][j] % 2 == 0)
with
if (arr[i * Columns + j] % 2 == 0)
As has been commented, you could also just use one loop:
for (i = 0; i < Columns * Rows; ++i)

My program is working properly but still at the end its showing Segmentation fault

gdb already Tried :0
void Reverse(struct Array *arr)
{
int i, j;
for (i = 0, j = arr->length - 1; i < j; i++, j--)
{
swap(&arr->arr[i], &arr->arr[j]);
}
}
void Reverse2(struct Array *obj)
{
int *b;
int i, j;
b = new int;
for (i = obj->length - 1, j = 0; i >= 0; i--, j++)
b[j] = obj->arr[i];
for (i = 0; i < obj->length; i++)
obj->arr[i] = b[i];
}
void Display(struct Array obj1)
{
int i;
cout << "yOur elements are: ";
for (i = 0; i < obj1.length; i++)
cout << obj1.arr[i] << " ";
}
int main()
{
struct Array obj = {{9, 8, 7, 6, 5, 3}, 10, 6};
cout << "your array is: ";
Display(obj);
cout << "\nAfter reversing using swap ";
Reverse(&obj);
Display(obj);
cout << "\nAfter reversing: ";
Reverse2(obj);
Display(obj);
return 0;
}
This is the output
your array is: yOur elements are: 9 8 7 6 5 3
After reversing using swap yOur elements are: 3 5 6 7 8 9
After reversing: yOur elements are: 3 5 6 7 8 9 Segmentation fault
Your code allocates a single integer, but then treats that integer as an array. Here
b = new int;
for (i = obj->length - 1, j = 0; i >= 0; i--, j++)
b[j] = obj->arr[i];
should be
b = new int[obj->length];
for (i = obj->length - 1, j = 0; i >= 0; i--, j++)
b[j] = obj->arr[i];

Merge sort same output C++

I wrote the below code for merge sort but it's not working, And I am unable to find out problem!
Every time the output becomes same as input, I think that problem may occur due to vector reference.
I think mergeSort is not creating a new vector for sub array. But I am still confused.
input vector: 5, 4, 3, 2, 1
output: 5, 4, 3, 2, 1
Req output: 1, 2, 3, 4, 5
#include <iostream>
#include <vector>
using namespace std;
void merge(vector<int> &la, vector<int> &ra, vector<int> &A) {
int i = 0, j = 0, k = 0;
// overwriting A using its solved sub arrays i.e la, ra
while (i < la.size() && j < ra.size()) {
if (la[i] <= ra[j]) {
A[k] = la[i];
i++;
k++;
} else {
A[k] = ra[j];
j++;
k++;
}
}
// if any subarray left then
while (i < la.size()) {
A[k] = la[i];
k++;
i++;
}
while (j < ra.size()) {
A[k] = ra[j];
k++;
j++;
}
}
mergeSort function:
void mergeSort(vector<int> &A) {
if (A.size() < 2)
return;
int len = A.size();
vector<int> la, ra;
for (int i = 0; i < len / 2; i++)
la.push_back(A[i]);
for (int i = len / 2; i < len; i++)
ra.push_back(A[i]);
// dividing the proble into subproblem
mergeSort(la);
mergeSort(ra);
// merging the solved subproblem
merge(la, ra, A);
}
Driver function:
int main(void) {
int arr[] = { 5, 4, 3, 2, 1 };
vector<int> A(arr, arr + 5);
for (int i = 0; i < A.size(); i++)
cout << A[i] << " ";
cout << endl;
mergeSort(A);
for (int i = 0; i < A.size(); i++)
cout << A[i] << " ";
return 0;
}
The code posted does not seem to have a problem.
Executing it produces the expected output: 1 2 3 4 5, so there is something else going on that could cause your observations: you might be running an executable produced by a previous or at least different version of the code.

In-place transpose of a 2-d vector passed by reference

I am trying to compute the transpose of a matrix. Now, I have passed the matrix as a 2-d vector, and since I want the function to calculate the transpose in-place, I passed the 2-d vector by reference. But it seems to take no effect.
I tried to use std::swap(mat[i][j], mat[j][i]), it had no effect. Again, I tried to manually swap the integers (using a third variable), still no effect.
#include<iostream>
#include<vector>
#include<algorithm>
#define N 5
void inPlaceTranspose(std::vector<std::vector<int> > &mat) {
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
int temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
//std::swap(mat[i][j], mat[j][i]);
}
}
std::cout << "Transpose:\n";
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
std::cout << mat[i][j] << " ";
}
std::cout << "\n";
}
}
int main() {
std::vector<std::vector<int> > mat(N, std::vector<int>(N));
mat = {
{1, 2, 3, 4, 5},
{7, 8, 9, 10, 11},
{13, 14, 15, 16, 17},
{19, 20, 21, 22, 23},
{25, 26, 27, 28, 29},
};
std::cout << "Original Matrix:\n";
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
std::cout << mat[i][j] << " ";
}
std::cout << "\n";
}
inPlaceTranspose(mat);
return 0;
}
The Original Matrix and Transpose are coming out to be same.
The problem is not in the way you pass the matrix, or in the way you do the swap. The problem is in your logic here:
for(int j = 0; j < N; j++) {
which results in swapping the elements twice, thus cancelling out your attempt to transpose the matrix.
Try looping until i, instead of N, like this:
for(int j = 0; j < i; j++) {
instead.

Maximum Sub-Array Sum C++

Given an array, I am trying to find the maximum sub-array sum. A sub-array is as follows. For example, I get the following array: [9, -7, 5, 3, 91]. Whilst [9, -7, 5] is a sub-array, [9, 5, 3, 91] is not. My code is below:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int arraylen, subarraylen, subarraysum, itervar1, itervar2, itervar3, incrementvar;
cin >> arraylen;
vector<int> mainarray(arraylen);
vector<int> sumarray(arraylen * (arraylen-1) + 1);
for (itervar1 = 0; itervar1 < arraylen; itervar1++) {
cin >> mainarray[itervar1];
}
sumarray[0] = 0;
for (itervar1 = 0; itervar1 < arraylen; itervar1++) {
for (itervar2 = arraylen; itervar2 > 0; itervar2--) {
subarraylen = itervar2-itervar1;
if (subarraylen < 1) {
continue;
}
vector<int> subarray(subarraylen);
incrementvar = 0;
for (itervar3 = itervar1; itervar3 < itervar2; itervar3++) {
subarray[incrementvar] = mainarray[itervar3];
incrementvar++;
}
subarraysum = 0;
for (itervar3 = 0; itervar3 < subarraylen; itervar3++) {
subarraysum += subarray[itervar3];
}
}
}
return 0;
}
For some reason, it doesn't work; just infinitely loops around. Any help would be appreciated.
First, here is a routine to list all the sub arrays:
vector<int> vec{ 9, -7, 5, 3, 91 };
int sz = vec.size();
for(int start = 0; start < sz; start++)
{
for(int end = start; end < sz; end++)
{
for(int j = start; j <= end; j++)
{
cout << vec[j] << ", ";
}
cout << "\n";
}
}
Now you just have to get the total in loop j, add to a vector sum. You don't need to know the size of sum before hand. Use push_back to add total to sum.
Note, the array itself is included as a sub array, you can exclude that array depending on what the definition is.