#include<stdio.h>
#include<conio.h>
void main()
{
int a[9][9],b[9][9],c[9][9],i,j,m,n,p,q,k;
clrscr();
printf("Enter the order of the first matrix:");
scanf("%d%d",&m,&n);
printf("Enter the order of the second matrix:");
scanf("%d%d",&p,&q);
if(p==n)
{
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("enter1st matrix element of row %d & column %d:",i+1,j+1);
scanf("%d",a[i][j]);
}
}
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf("enter 2nd matrix element of row %d & column %d:",i+1,j+1);
scanf("%d",b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;i++)
{
c[i][j]=0;
for(k=0;k<p;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
}
else
{
printf("Matrix multiplication is invalid !...");
}
getch();
}
**It has no error while compile but it while running it doesn't show the multiplied matrices as desired it get inputs but not giving an output
Find the mistakes and answer it**
In the actual multiplication loop nest, you have incorrect loop bounds. That won't matter when both matrices are square, but it will at best give you incorrect results when one or both are rectangular. Additionally, you have a typo in the loop counter increment (thanks, #Bob__).
Given that m is the first dimension of the left matrix (a), q is the second dimension of the right matrix (b), and n == p is the common dimension of the two, the multiplication should look like this:
for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) { // note loop bound change here
c[i][j] = 0;
for (k = 0; k < p; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
// ...
Related
I wrote this code that inputs 2 matrices and prints the product after multiplying the 2 matrices using pointers. But when I enter the first element I am getting segmentation fault. I have tried everything with pointers but I think this is some loop error as it says segmentation fault. Please help
#include<stdio.h>
#include<stdlib.h>
#define N 10
void readMatrix(float *arrp, int rows, int cols)
{
for (int i=0; i<rows; i++)
{
for (int j=0; j<cols; j++)
{
printf("Enter element [%d][%d] : ",i+1,j+1);
scanf("%f",&*(arrp + i) + j);
}
}
return;
}
void printMatrix(float *arrp, int rows, int cols)
{
for (int i=0; i<rows; i++)
{
for (int j=0; j<cols; j++) printf("%.2f\t",*((arrp + i) + j));
printf("\n");
}
return;
}
int main()
{
float *ap, *bp, *cp;
int arows, brows, acols, bcols;
printf("Give no. of rows of matrix A (<=%d) = ",N);
scanf("%d",&arows);
printf("Give no. of columns of matrix A (<=%d) = ",N);
scanf("%d",&acols);
if (arows>N || acols>N || arows<1 || acols<1)
{
printf("Illegal rows/cols = %d/%d. Should be <=%d.\n", arows, acols, N);
exit(0);
}
readMatrix(ap, arows, acols); printf("\n");
printf("Matrix A :\n"); printMatrix(ap, arows, acols); printf("\n");
printf("Give no. of rows of matrix B (<=%d) = ", N);
scanf("%d",&brows);
printf("Give no. of columns of matrix B (<=%d) = ", N);
scanf("%d",&bcols);
if (brows>N || bcols>N || brows<1 || bcols<1)
{
printf("Illegal rows/cols = %d/%d. Should be <=%d.\n", brows, bcols, N);
exit(0);
}
if (acols==brows)
{
readMatrix(bp, brows, bcols); printf("\n");
printf("Matrix B :\n"); printMatrix(bp, brows, bcols); printf("\n");
for (int i=0; i<arows; i++)
{
for (int j=0; j<bcols; j++)
{
float sum=0.0;
for (int k=0; k<acols; k++) sum += *((ap + i) + k) * *((bp + k) + j);
*((cp + i) + j) = sum;
}
}
printf("After Multiplication, Matrix C :\n"); printMatrix(cp, arows, bcols);
}
else printf("\nIncompatible matrices\nColumns of matrix A should be equal to rows of matrix B\n");
exit(0);
}
Your program never assigns any values to ap, bp, or cp. You need to reserve memory for the data in some way and set the pointers to point to it.
Additionally, *((ap + i) + k) is equivalent to *(ap + (i + k)). It merely adds i and k. The program needs to compute where the element in row i and column k is. If ap is a pointer to float, you need to multiply i by the number of columns. If ap is a pointer to an array, you need to insert another operator in there—go back to your source material for the class and see what is different about this expression than what the book or the instructor taught.
so I´m trying to print this 2d array as a matrix and it´s not working. any hints? no matter what i change i cant get to print an all 0 3x3 matrix
int main()
{
int i, j, m, n, primeira;
int matrix[10][20];
printf("Enter number of rows : ");
scanf("%d", &m);
printf("Enter number of columns : ");
scanf("%d", &n);
/* first input */
printf("1 ou 0");
scanf("%d", &primeira);
if (primeira = 0) {
matrix [0][0]=0;
matrix [0][1]=0;
matrix [1][0]=0;
matrix [1][1]=0;}
/* Display the matrix */
{
printf("%d\t", matrix[i][j]);
}
printf("\n");
return 0;
}
You would need to create a nested loop to display the matrix. If you want to display a 3x3 matrix you can run something like this.
int matrix[3][3] = { 0 };
/* Display the matrix */
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf ("%d\t", matrix[i][j]);
}
printf ("\n");
}
regarding:
printf("%d\t", matrix[i][j]);
The variables: i and j are not initialized!
Suggest:
for( int i =0; i<10; i++ )
{
for( int j=0; j<20; j++ )
{
printf( "%d ", matrix[i][j] );
}
puts( "" );
}
as that will print all the elements of the matrix and move to a new line after printing each row of the matrix.
I'm doing this exercise
"take as input a matrix of n rows and m columns of natural numbers (n and m are also
acquired from input). The program check if the sum of the numbers
contained in each row is the same for all rows"
I can't figure out how to save the last sum of the rows in the matrix. If I insert a temporary variable to allocate the last sum then it is overwritten in the next for cycle
int main ()
{
int i, j;
int sum;
int temp;
int n=3, m=3;
int matrix[n][m];
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("Enter: ");
scanf("%d",&matrix[i][j]);
}
}
for(i=0;i<m;i++)
{
sum=0;
for(j=0;j<n;j++)
{
sum+=matrix[i][j];
}
}
}
Keeping the code really similar to what you have right now you could do something like this:
int main (){
int i, j;
int sum = 0;
int oldsum = 0;
int temp;
int n=3, m=3;
int matrix[n][m];
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("Enter: ");
scanf("%d",&matrix[i][j]);
}
}
for(i=0;i<m;i++)
{
sum=0;
for(j=0;j<n;j++)
{
sum+=matrix[i][j];
}
if (i == 0 || sum == oldsum){
oldsum = sum;
}
else {
printf("The sums are not equal!\n");
return 1;
}
}
printf("All the sums are equal!\n");
return 0;
}
Since you need to check if the sum for all rows is the same you can safely stop the program when you find a sum that is different from the previous one, in this case when you find a different sum you return 1 otherwise you return 0 at the end of main.
The || in the condition is used to handle the first sum calculation when both sum and oldsum are still 0;
Add one more int array Row_sum[n]
int main ()
{
int i, j;
int sum;
int temp;
int n=3, m=3;
int matrix[n][m];
int Row_sum[n]
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("Enter: ");
scanf("%d",&matrix[i][j]);
}
}
for(i=0;i<m;i++)
{
sum=0;
for(j=0;j<n;j++)
{
sum+=matrix[i][j];
}
Row_sum[i] = sum;
}
for(i = 0; i < n; i++)
{
for(j = i + 1; j < n; j++)
{
if(Row_sum[i] == Row_sum[j])
{
printf("Sum of rows in matrix are equal", i, j);
}
}
}
printf("\nSum of rows in matrix are not equal", flag);
}
I need to add two 3x3 matrices together using while loops. I am able to read and print both matrices using while loops but cannot work out how to add the matrices with while loops.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i=0,j=0,k=0,l=0,m=0,n=0;
int a[3][3],b[3][3],c[3][3];
printf("Enter the first matrix \n \n");
while(i<3)
{
j=0;
while(j<3)
{
scanf("%d",&a[i][j]);
j++;
}
i++;
}
printf("\n");
printf("The first matrix is \n\n");
i=0;
while(i<3)
{
j=0;
while(j<3)
{
printf("%d ",a[i][j]);
j++;
}
printf("\n");
i++;
}
printf("\n");
//////////////////////////////////////////////////////////////////////////
printf("Enter the second matrix \n \n");
while(k<3)
{
l=0;
while(l<3)
{
scanf("%d",&b[k][l]);
l++;
}
k++;
}
printf("\n");
printf("The second matrix is \n\n");
k=0;
while(k<3)
{
l=0;
while(l<3)
{
printf("%d ",b[k][l]);
l++;
}
printf("\n");
k++;
}
printf("\n");
///////////////////////////////////////////////////////////////////////////////
printf("The sum of the matrix's is \n \n");
return 0;
}
int matrix_a [3][3] = {{1,2,3},{3,4,5},{4,5,6}};
int matrix_b [3][3] = {{5,6,7},{6,7,8},{7,8,9}};
int i = 0;
while (i < 3) {
j = 0;
while (j < 3) {
matrix_a[i][j] += matrix[i][j];
++ j;
}
++ i;
}
for loops are a much better choice:
for (int i = 0; i < 3; ++ i) {
for (int j = 0; j < 3; ++ j) {
matrix_a[i][j] += matrix_b[i][j];
}
}
Superoptimal pointer-arithmetic alternative:
int* ptr_a = matrix_a;
int* ptr_b = matrix_b;
int size = 3 * 3;
while (size --) {
* ptr_a++ += * ptr_b++;
}
Break your problem down into smaller sub problems to help solve it.
EXAMPLE:
How to loop through a 2-D array?
How to get values and assign them to a variable from looping through the array?
How to manipulate the values to are obtaining (In your case adding them to something else)
How to insert these values into the correct position in a new array.
You can add the below code to do the addition:
k=0;
while(k<3)
{
l=0;
while(l<3)
{
c[k][l] = a[k][l]+b[k][l];
l++;
}
k++;
}
And, to display your matrix, you can use for loop instead of while.
Example:
for(int p =0;p<3;p++){
for(int q=0;q<3;q++){
c[p][q] = a[p][q] + b[p][q] ;
}
}
for(int p =0;p<3;p++){
for(int q=0;q<3;q++){
printf("%d \t",c[p][q]) ;
}
printf("\n");
}
The inverse of my matrix shows always 0 and I don't understand why. Thank you for advance.
4 fonctions :
-main : user enters the matrix, and the results (of matrix, determinant, LU factorisation and inverse) are display.
#include<stdio.h>
#include<conio.h>
#include<math.h>
float determinant(float[20][20],float);
void cofactor(float[20][20],float);
void transpose(float[20][20],float[20][20],float);
void main()
{
float A[20][20]= {0},L[20][20]= {0}, U[20][20];
float B[20]= {0}, X[20]= {0},Y[20]= {0};
int i,j,k,n;
printf("Enter the order of square matrix: ");
scanf("%d",&n);
printf("\nEntrer les elements de la matrice A:\n");
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
printf("Entrer l'element A[%d][%d] : ", i,j);
scanf("%f",&A[i][j]);
}
}
printf("\nEntrer les termes de la matrice B\n");
for(i=0; i<n; i++)
{
printf("B[%d]",i);
scanf("%f",&B[i]);
}
for(j=0; j<n; j++)
{
for(i=0; i<n; i++)
{
if(i<=j)
{
U[i][j]=A[i][j];
for(k=0; k<i-1; k++)
U[i][j]-=L[i][k]*U[k][j];
if(i==j)
L[i][j]=1;
else
L[i][j]=0;
}
else
{
L[i][j]=A[i][j];
for(k=0; k<=j-1; k++)
L[i][j]-=L[i][k]*U[k][j];
L[i][j]/=U[j][j];
U[i][j]=0;
}
}
}
printf("[L]: \n");
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
printf("%9.3f",L[i][j]);
printf("\n");
}
printf("\n\n[U]: \n");
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
printf("%9.3f",U[i][j]);
printf("\n");
}
//Y pour calculer X
for(i=0; i<n; i++)
{
Y[i]=B[i];
for(j=0; j<i; j++)
{
Y[i]-=L[i][j]*Y[j];
}
}
for(i=0; i<n; i++)
{
printf("%9.3f",Y[i]);
}
for(i=n-1; i>=0; i--)
{
X[i]= Y[i];
for(j=i+1; j<n; j++)
{
X[i]-=U[i][j]*X[j];
}
X[i]/=U[i][i];
}
printf("\n\n[X]: \n");
for(i=0; i<n; i++)
{
printf("%9.3f",X[i]);
}
printf("\n\nLe determinant de la matrice A est = %f",n);
if (n==0)
printf("\nCette matrice n'a pas d'inverse!\n");
else {
cofactor(A,k);
}
getch();
}
float determinant(float a[20][20],float k)
{
float s=1,det=0,b[20][20];
int i,j,m,n,c;
if (k==1)
{
return (a[0][0]);
}
else
{
det=0;
for (c=0;c<k;c++)
{
m=0;
n=0;
for (i=0;i<k;i++)
{
for (j=0;j<k;j++)
{
b[i][j]=0;
if (i != 0 && j != c)
{
b[m][n]=a[i][j];
if (n<(k-2))
n++;
else
{
n=0;
m++;
}
}
}
}
det=det + s * (a[0][c] * determinant(b,k-1));
s=-1 * s;
}
}
return (det);
}
void cofactor(float num[20][20],float f) //fonction which will calculate the cofactof of matrix
{
float b[20][20],fac[20][20];
int p,q,m,n,i,j;
for (q=0;q<f;q++)
{
for (p=0;p<f;p++)
{
m=0;
n=0;
for (i=0;i<f;i++)
{
for (j=0;j<f;j++)
{
if (i != q && j != p)
{
b[m][n]=num[i][j];
if (n<(f-2))
n++;
else
{
n=0;
m++;
}
}
}
}
fac[q][p]=pow(-1,q + p) * determinant(b,f-1);
}
}
transpose(num,fac,f);
}
/*Finding transpose of matrix*/
void transpose(float num[20][20],float fac[20][20],float r)
{
int i,j;
float b[20][20],inverse[20][20],n;
for (i=0;i<r;i++)
{
for (j=0;j<r;j++)
{
b[i][j]=fac[j][i];
}
}
n=determinant(num,r);
for (i=0;i<r;i++)
{
for (j=0;j<r;j++)
{
inverse[i][j]=b[i][j] / n;
}
}
printf("\n\n\nThe inverse of matrix is : \n");
for (i=0;i<r;i++)
{
for (j=0;j<r;j++)
{
printf("\t%f",inverse[i][j]); //show inverse of the matrix
}
printf("\n");
}
}
There are several issues with your code, but the principal error is that you pass a wrong parameter to
cofactor(A,k);
Here, k is a loop variable that has the value it had after it was used in the code that does the triangular decomposition. (You can see that this value is 1, because only one entry of the matrix is printed.)
You should use the order of the matrices, n:
cofactor(A, n);
In general, you should use a more consistent nomenclature. In main, the order of the matrices is n, in determinant it's k, in cofactor you use the floating-point variable f and in transpose, you use the floating-point variable r. To add to the confusion, n is a float here that represents the determinant. I suggest you use the integer n for the order, local integers i, j and k as loop variables – C99 allows you to define them only for the scope of the loop, e.g. for (int i = 0; ...) – and more or less meaningful names for the floating-point numbers; det for the determinant is good.
Further suggestions:
Don't write explicit loops to print matrices every time; write a function to print a matrix and a function to print a vector instead and call them.
Separate calculating from printing. For example, the code to print the inverse should not be part of (the badly named?) transpose. Instead, transpose should fill a matrix passed in from main, and main should then print that matrix.
Ideally, triangular decomposition and solving the equation should be functions, too. Experience the joys of nicely organised code. :)