Multiplying two 3x3 matrices in C - c

I am trying to multiply two 3x3 matrices. The first 2 numbers in the first
and second row are the only correct answer. What am I doing
wrong? Is the stuff I need declared in mult_matrices?
#include <stdio.h>
void mult_matrices(int a[][3], int b[][3], int result[][3]);
void print_matrix(int a[][3]);
int main()
{
int p[3][3] = {{1, 2, 3},{4, 5, 6}, {7, 8, 9}};
int q[3][3] = {{10, 11, 12}, {13, 14, 15}, {16, 17, 18}};
int r[3][3];
mult_matrices(p, q, r);
print_matrix(r);
}
void mult_matrices(int a[][3], int b[][3], int result[][3])
{
int i, j, k;
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
for(k = 0; k < 3; k++)
{
result[i][j] += a[i][k] * b[k][j];
}
}
}
}
void print_matrix(int a[][3])
{
int i, j;
for (i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
printf("%d\t", a[i][j]);
}
printf("\n");
}
}

Make sure you initialize r to all zeros before you use it.
int r[3][3] = { 0 };

Looks like you're not initializing your result matrix.
i.e. Change:
int r[3][3];
to
int r[3][3] ={{0,0,0},{0,0,0},{0,0,0}};

One thing that I notice that you don't do is initialize you're r[3][3] array. I am not sure if this is the root of you're problem but it very well could be. Essentially what the values of r are set to is whatever was "left over" in memory in that location. Sometimes they will all be 0 but most likely they will not be. So it could be the issue you are having, but even if it isn't it is good to always get in a habit of initializing all of you're variables.

int main(){
int A[3][3],B[3][3],C[3][3],i,j;
printf("Please Enter 9 Numbers for First Matrix")
for(i=0;i<=2;i++){
for(j=0;j<=2;j++){
scanf("%d",A[i][j]);
}
}
printf("Please Enter 9 Numbers for Second Matrix")
for(i=0;i<=2;i++){
for(j=0;j<=2;j++){
scanf("%d",B[i][j]);
}
}
for(i=0;i<=2;i++){
for(j=0;j<=2;j++){
C[i][j]=A[i][j]+B[i][j]
printf("%d "C[i][j]);
}
printf("\n");
}
}

Related

double pointer help me [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
in visuals studio i try to make respectively sum of rows. but first sum multiplied by 4 . i didnt understand this situation
get_sum(int **q, int p, int n);
int main(void)
{
int num[3][5] = { 10,11,12,13,14,15,16,17,18,19,20,21,22,23,24 };
get_sum(&num[0][0], 3, 5);
}
get_sum(int **q, int p, int n)
{
/*for (int i = 0; i < ; i++)
printf("%d\n", *(q + i));*/
for (int k = 0; k < p; k++)
{
int sum = 0;
for (int i = 0; i < n; i++)
{
sum =*(q + n*k + i)+sum;
printf("%d\n", sum);
}
}
}
If I understand you simply want to create a function that sums the elements of the array passed as a parameter, along with the dimensions of the array, then you have the right idea, but woefully wrong syntax.
Rather than verbally discussing each change, the simple example contains all the changes. Look over the changes and why they were made:
#include <stdio.h>
int get_sum (int (*q)[5], int p, int n);
int main (void)
{
int num[3][5] = {{ 10, 11, 12, 13, 14 },
{ 15, 16, 17, 18, 19 },
{ 20, 21, 22, 23, 24 }};
int sum = get_sum (num, 3, 5);
printf (" -----------\n sum : %d\n", sum);
return 0;
}
int get_sum (int (*q)[5], int p, int n)
{
int sum = 0;
for (int k = 0; k < p; k++) {
for (int i = 0; i < n; i++)
sum += q[k][i];
printf ("row[%2d] : %d\n", k, sum);
}
return sum;
}
(note: the loop output within get_sum provides are running-total of the sum after the addition of each row elements. You can tailor this to meet your needs.)
Example Use/Output
$ ./bin/get_sum
row[ 0] : 60
row[ 1] : 145
row[ 2] : 255
-----------
sum : 255
Let me know if you have any questions.
You are indexing a 1-D array as if it is a 2-D array, but there is no need to define it as 2-D, and anyway, you initialise it as if it were a 1-D array.
#include <stdio.h>
void get_sum(int *q, int p, int n); // only one start
int main(void)
{
int num[] = { 10,11,12,13,14,15,16,17,18,19,20,21,22,23,24 }; // 1-D linear array
get_sum(num, 3, 5);
return 0;
}
void get_sum(int *q, int p, int n) // added return type
{
int k, i, sum;
for (k = 0; k < p; k++) {
sum = 0;
for (i = 0; i < n; i++) {
sum = *(q + n*k + i) + sum;
}
printf("%d\n", sum); // moved out of inner loop
}
}
Program output
60
85
110
Alternatively if you do want a 2-D array and then index into it as if it were a 1-D array, you can do this. Note I have initialised the array differently but get_sum is the same.
#include <stdio.h>
void get_sum(int *q, int p, int n); // only one start
int main(void)
{
int num[3][5] = {{10,11,12,13,14}, {15,16,17,18,19}, {20,21,22,23,24}};
get_sum(&num[0][0], 3, 5);
return 0;
}
void get_sum(int *q, int p, int n) // added return type
{
int k, i, sum;
for (k = 0; k < p; k++) {
sum = 0;
for (i = 0; i < n; i++) {
sum = *(q + n*k + i) + sum;
}
printf("%d\n", sum); // moved out of inner loop
}
}

Why does this program segfault when returning a pointer to a local static variable?

This is related to an earlier question of mine. I tried expanding the code a little bit and to play around with different ways of returning pointers to local static variables, especially returning two-dimensional arrays. (This is seriously just to understand how pointers to arrays work and how they behave in function environments. It has not even the slightest intent of returning arrays the smart way using structs.) I wrote two functions both transpose matrices. The function transpose() only transposes 2x4-matrices and the function transpose_generic() is supposed to transpose matrices of arbitrary size. There is no real use to them. After I have declared and defined the functions I call them from int main(int argc, char *argv[]){}. The two matrices that have been transposed are supposed to be printed to stdout in a simple for-loop. And here is something I don't understand. Depending on whether I declare the matrices that are supposed to be transposed as global or local variables I get a segfault or "clean" exit. I can also prevent the compiled program from segfaulting by using a for loop after the for loop that prints the transposed matrices to stdout. But the for-loop needs to use a new index. I'm sure I'm missing something very basic but I cannot figure this out on my own. Even after extensive internet searching I'm still puzzled. So maybe someone can enlighten me. Here is the code:
Will segfault
#include <stdio.h>
int mat1[2][4] = {
{9, 10, 11, 12},
{13, 14, 15, 16}
};
int mat2[2][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8}
};
typedef matx[2];
matx *transpose(int matrix[][4]);
typedef maty[];
maty *transpose_generic(int nrow, int ncol, int matrix1[nrow][ncol], int matrix2[nrow][ncol]);
int main(int argc, char *argv[]) {
/* This may need a little bit of clarification. Here we want to declare a
* pointer to an array and we need the round brackets () for this. If we
* were simply to write *mat_transpose[2] we would declare an array of
* pointers since [] has higher precedence than *. */
int (*mat_transpose)[2];
int tmat[2][4];
int i;
int j;
mat_transpose = transpose(mat1);
transpose_generic(2, 4, mat2, tmat);
for (j = 0; j < 2; j++) {
for (i = 0; i < 4; i++) {
printf("mat_transpose[%d][%d] = %d\n", i, j, mat_transpose[i][j]);
printf("tmat[%d][%d] = %d\n", i, j, tmat[i][j]);
}
}
return 0;
}
matx *transpose(int matrix[][4]) {
static int mat[4][2];
int i;
int j;
printf("Transpose a 2x4 matrix\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 4; j++) {
mat[j][i] = matrix[i][j];
}
}
return mat;
}
maty *transpose_generic(int nrow, int ncol,
int matrix1[nrow][ncol],
int matrix2[nrow][ncol]) {
int i;
int j;
printf("Transpose a matrix\n\n");
for (i = 0; i < nrow; i++) {
for (j = 0; j < ncol; j++) {
matrix2[j][i] = matrix1[i][j];
}
}
return matrix2;
}
Will exit clean
#include <stdio.h>
typedef matx[2];
matx *transpose(int matrix[][4]);
typedef maty[];
maty *transpose_generic(int nrow, int ncol, int matrix1[nrow][ncol], int matrix2[nrow][ncol]);
int main(int argc, char *argv[]) {
int mat1[2][4] = {
{9, 10, 11, 12},
{13, 14, 15, 16}
};
int mat2[2][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8}
};
/* This may need a little bit of clarification. Here we want to declare a
* pointer to an array and we need the round brackets () for this. If we
* were simply to write *mat_transpose[2] we would declare an array of
* pointers since [] has higher precedence than *. */
int (*mat_transpose)[2];
int tmat[2][4];
int i;
int j;
mat_transpose = transpose(mat1);
transpose_generic(2, 4, mat2, tmat);
for (j = 0; j < 2; j++) {
for (i = 0; i < 4; i++) {
printf("mat_transpose[%d][%d] = %d\n", i, j, mat_transpose[i][j]);
printf("tmat[%d][%d] = %d\n", i, j, tmat[i][j]);
}
}
return 0;
}
matx *transpose(int matrix[][4]) {
static int mat[4][2];
int i;
int j;
printf("Transpose a 2x4 matrix\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 4; j++) {
mat[j][i] = matrix[i][j];
}
}
return mat;
}
maty *transpose_generic(int nrow, int ncol,
int matrix1[nrow][ncol],
int matrix2[nrow][ncol]) {
int i;
int j;
printf("Transpose a matrix\n\n");
for (i = 0; i < nrow; i++) {
for (j = 0; j < ncol; j++) {
matrix2[j][i] = matrix1[i][j];
}
}
return matrix2;
}
Will exit clean
#include <stdio.h>
int mat1[2][4] = {
{9, 10, 11, 12},
{13, 14, 15, 16}
};
int mat2[2][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8}
};
typedef matx[2];
matx *transpose(int matrix[][4]);
typedef maty[];
maty *transpose_generic(int nrow, int ncol, int matrix1[nrow][ncol], int matrix2[nrow][ncol]);
int main(int argc, char *argv[]) {
/* This may need a little bit of clarification. Here we want to declare a
* pointer to an array and we need the round brackets () for this. If we
* were simply to write *mat_transpose[2] we would declare an array of
* pointers since [] has higher precedence than *. */
int (*mat_transpose)[2];
int tmat[2][4];
int i;
int j;
int k;
mat_transpose = transpose(mat1);
transpose_generic(2, 4, mat2, tmat);
for (j = 0; j < 2; j++) {
for (i = 0; i < 4; i++) {
printf("mat_transpose[%d][%d] = %d\n", i, j, mat_transpose[i][j]);
printf("tmat[%d][%d] = %d\n", i, j, tmat[i][j]);
}
}
for (k = 0; k < 1; k++) {
printf("H");
}
return 0;
}
matx *transpose(int matrix[][4]) {
static int mat[4][2];
int i;
int j;
printf("Transpose a 2x4 matrix\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 4; j++) {
mat[j][i] = matrix[i][j];
}
}
return mat;
}
maty *transpose_generic(int nrow, int ncol,
int matrix1[nrow][ncol],
int matrix2[nrow][ncol]) {
int i;
int j;
printf("Transpose a matrix\n\n");
for (i = 0; i < nrow; i++) {
for (j = 0; j < ncol; j++) {
matrix2[j][i] = matrix1[i][j];
}
}
return matrix2;
}
In this line,
printf("tmat[%d][%d] = %d\n", i, j, tmat[i][j]);
When i>1 your code causes undefined behaviour since you tmat is declared as int tmat[2][4];.
The same problem exists in all three code snippets and you just happen to get segfault only for the first one. This is not at all related to whether you return a a pointer to a function scoped static variable.

Find the union of two sets of 10 digit numbers

I'm trying to find the union of two sets of 10 digit numbers, I'm passing along three int arrays: first, second, and comp (this will hold the union set).
So far, I've added first and second into one array. I was thinking about finding the matching indices in comp[] then filter through deleting them. I figure there's a much easier way. Can anyone give me a hint?
Basically I'm taking
first[] = [1,2,3,4,5,6,7,8,9,10];
second[] = [1,2,3,4,11,12,13,14,15,16];
and I want to return
comp[] = [5,6,7,8,9,10,11,12,13,14,15,16];
The numbers won't necessarily be in order.
int compound(int first[],int second[],int comp[]){
int i=0;
int indicies[20];
for(int j = 0; j<SIZE; j++){
comp[i]=first[j];
i++;
}
for(int k = 0; k<SIZE; k++){
comp[i]=second[k];
i++;
}
int z=0;
for(int l = 0; l<SIZE*2; l++){
for(int m = 0; m<SIZE*2; m++){
if(comp[l]==comp[m]){
indicies[z]=m;
z++;
}}}
return 0;
}
A first good step is (nearly) always sorting.
Sort both input-sets (unless you know they are already sorted).
Then iterate over both at once (two indices) and only add those elements to the output which fulfill your criteria (seems to be union minus intersection, thus only in one).
Bonus: The output-set will be sorted.
I suggest you start by writing a contains(int[], int) method like
#include <stdio.h>
#include <stdbool.h>
bool contains(int arr[], int val) {
int offset;
for (offset = 0; arr[offset] != '\0'; offset++) {
if (arr[offset] == val) return true;
}
return false;
}
Then your compound method could be implemented using it with something like
int compound(int first[],int second[],int comp[]){
int i=0;
int j;
for(j = 0; first[j] != '\0'; j++){
int val = first[j];
if (contains(second, val) && !contains(comp, val))
comp[i++] = val;
}
return i;
}
Finally, you can test it like
int main(int argc, char *args[]) {
int a[] = {1,2,3,'\0'};
int b[] = {2,3,4,'\0'};
int c[3];
int count = compound(a,b,c);
int i;
for (i = 0; i < count; i++) {
printf("%i\n", c[i]);
}
}
Output is
2
3
If the numeric range is small you could do this:
#include <stdio.h>
#define MAX 20 // small numeric range
#define sz(a) (sizeof(a)/sizeof(*(a)))
int xunion(int *a, int sa, int *b, int sb, int *c) {
int n[MAX] = {0};
for (int i=0; i<sa; i++) n[a[i]] = 1;
for (int i=0; i<sb; i++) n[b[i]] = 1;
int j=0;
for (int i=0; i<MAX; i++) if (n[i]) c[j++] = i;
return j;
}
void prn(int *a, int s) {
while (s-- > 0) printf("%d ", *a++);
putchar('\n');
}
int main() {
int a[] = {6, 3, 4, 7, 5};
int b[] = {2, 4, 5, 7, 6, 3};
int c[MAX];
prn(a, sz(a));
prn(b, sz(b));
int n = xunion(a, sz(a), b, sz(b), c);
prn(c, n);
return 0;
}

check if array contains all array values from another array in C

I tried to make a program that will check if an an array contains all the array values from another array. So, if that's true, the program will return 1 using a value for it. If it isn't true, it will return 0(I named it p). I failed to make that program though. Could you please help me?
#include <stdio.h>
int isSubset(int arr1[], int arr2[], int m, int n)
{
int i = 0;
int j = 0;
for (i=0; i<n; i++)
{
for (j = 0; j<m; j++)
{
if(arr2[i] == arr1[j])
break;
}
/* If the above inner loop was not broken at all then
arr2[i] is not present in arr1[] */
if (j == m)
return 0;
}
/* If we reach here then all elements of arr2[]
are present in arr1[] */
return 1;
}
int main()
{
int arr1[] = {11, 1, 13, 21, 3, 7};
int arr2[] = {11, 2, 7, 1};
int m = sizeof(arr1)/sizeof(arr1[0]);
int n = sizeof(arr2)/sizeof(arr2[0]);
if(isSubset(arr1, arr2, m, n))
printf("arr2[] is subset of arr1[] ");
else
printf("arr2[] is not a subset of arr1[]");
getchar();
return 0;
}
Ideone Link up and running : http://ideone.com/4u9oQm

Printing 2D Array using pointers in C

#include "stdio.h"
void main(){
int a[2][2]={1, 2, 3, 4};
int a[2][2]={1, 2, 3, 4};
display(a, 2, 2);
show(a, 2, 2);}
}
display(int *k, int r, int c){
int i, j, *z;
for(i = 0; i < r; i++){
z = k + i;
printf("Display\n");
for(j = 0; j < c; j++){
printf("%d", *(z + j));
}
}
}
show(int *q, int ro, int co){
int i, j;
for(i = 0; i < ro; i++){
printf("\n");
for(j = 0; j < co; j++){
printf("%d", *(q + i*co + j));
}
}
}
Output:
Display
12
23
Show
12
34
Why Display() is not showing 1223 while show() gives 1234? Both uses the same logic to display the 2d array. Can any one help please?
In display you are using two counters, i for rows and j for columns. Since the array is laid out sequentially in memory you need to increase i by the size of a column, i.e. c, each time you want to move from one row to the next. So, you should add i*c to k, not i.
The complete function:
display(int *k,int r,int c){
int i,j,*z;
for(i=0;i<r;i++){
z=k+i*c;
printf("Display\n");
for(j=0;j<c;j++){
printf("%d",*(z+j));
}
}
}
To access 2D array using pointers:
#define R 2
#define C 2
...
int A[R][C]={1, 2, 3, 4};
for(i=0;i<R;i++)
for(j=0;j<C;j++)
printf("%d ",*(*(A+i)+j));
...

Resources