I'm currently learning C programming, to better my understanding of matrices in C I've tried to make this program.
I seem to be having problems with the output, as you can see the program has 3 functions.
The first one allows you to input the values for the array and then displays it. The second function performs the multiplication and the last should display the output of the multiplied matrix.
However the output is strange. Here is my code. The output is just below the code.
#include <stdio.h>
void read_matrix(int m2[][3] )
{
int i, j;
printf("input values for matrix in order of rows first \n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
scanf("%d",&m2[i][j]);
}
}
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d ", m2[i][j]);
}
printf("\n");
}
}
void multiply_matrices(int m1[][3], int m2[][3] ,int m3[][3])
{
int i, j, k;
for (i = 0; i < 3; i++){
for (j = 0; j < 3; j++){
for (k = 0; k < 3; k++){
m3[i][j] +=m1[i][k]*m2[k][j];
}
}
}
}
void write_matrix(int m3[][3] )
{
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d ", m3[i][j]);
}
printf("\n");
}
}
int main(void)
{
int matrix1[3][3], matrix2[3][3], matrix3[3][3];
read_matrix(matrix1);
read_matrix(matrix2);
multiply_matrices(matrix1, matrix2, matrix3);
write_matrix(matrix3);
return 0;
}
and this is the output!
input values for matrix in order of rows first
1
2
3
2
2
2
1
2
2
1 2 3
2 2 2
1 2 2
input values for matrix in order of rows first
2
1
1
1
2
1
2
1
2
2 1 1
1 2 1
2 1 2
-858993450 -858993452 -858993451 /*This is the multiplied matrix output!*/
-858993450 -858993452 -858993452
-858993452 -858993453 -858993453
Press any key to continue . . .
I fear it may be just a silly mistake; if so I'm sorry, but I can't see where I am going wrong at this moment.
Any help would be greatly appreciated.
You need to initialize all elements of matrix m3 to 0 before performing this operation
m3[i][j] +=m1[i][k]*m2[k][j];
in function multiply_matrices.
Initialize matrix3 in the function multiply matrix like this
for (int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
m3[i][j]=0;
}
}
After this, do the multiplication and everything will work perfectly.
int m3[][]={};
It initially stores 0 for all available index of m3
Related
#include <stdio.h>
int main()
{
int tarr[3][4];
//this for loop is for making 2d array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
tarr[i][j] = (i++) * (j++);
}
}
// this for loop is for exporting 2d array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
printf("%d ", tarr[i][j]);
}
printf("\n");
}
return 0;
}
expected answer:
1 2 3 4
2 4 6 8
3 6 9 12
actual exported answer:
194 0 -566790131 22024
-1681794240 0 0 0
-566790208 22024 -566790672 2
My expectation was to export as I expected but the weird numbers were exported and I cannot understand where those numbers are from. I want to know where those numbers are from and what should I do for exporting my expected numbers.
Code eventually attempts to access data outside arrays bounds leading to undefined behavior (UB).
for( int j = 0; j<4; j++) {
// On the first iteration, i,j is 0,0
// On the next iteration, i,j is 1,2
tarr[i][j]= (i++)*(j++);
}
Do not increment: (i++)*(j++). Instead, simply add 1.
for( int j = 0; j<4; j++) {
// On the first iteration, i,j is 0,0
// On the next iteration, i,j is 0,1
tarr[i][j]= (i+1) * (j+1);
}
So I am trying to print patterns in C.
For n = 2
Output:
2 2 2
2 1 2
2 2 2
for n = 3
Output:
3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3
and so on.
My Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
scanf("%d",&n);
int nn = n;
int *arr;
arr = (int*)malloc(n*sizeof(int));
int f = 0; //flag to check if I reached the mid of the pattern
int l = 2*n-1; //Lenght of square to be generated
int temp1 = 0;
int temp2 = l;
for(int i = 0;i<l;i++)
{
for(int j = temp1;j<temp2;j++) //change values in range temp1 to temp2
{
arr[j] = n;
}
for(int k = 0;k<l;k++)
{
printf("%d ",arr[k]);
}
printf("\n");
if(n == 1)
{
f = 1;
}
if(f==0) //For upper half of pattern
{
n=n-1;
temp1=temp1+1;
temp2=temp2-1;
}
else if(f==1) //For lower half of pattern
{
n=n+1;
temp1=temp1-1;
temp2=temp2+1;
}
}
return(0);
}
I am getting the correct output for n = 2 but when I am inputting anything above 2 the code is crashing.
I am not able to find what should be done. Can someone help me out and tell me what am I doing wrong?
It would be better to check distances by axis and take a maximum of them to be printed.
Something like:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int vertical_distance;
int horizontal_distance;
int n;
scanf("%d",&n);
for(int i = 0; i < n * 2 + 1; i++)
{
for(int j = 0; j < n * 2 + 1; j++)
{
vertical_distance = abs(n - i);
horizontal_distance = abs(n - j);
if (vertical_distance > horizontal_distance)
printf("%d ", vertical_distance);
else
printf("%d ", horizontal_distance);
}
printf("\n");
}
return(0);
}
Also, when I ran your code it worked nicely with large numbers (3, 7, 15).
I just pasted your code to onlinegdb.com/online_c_compiler and ran it. Can you please add the error message that you have got?
(sry for my English)
in this code piece
for(int j = temp1;j<temp2;j++) //change values in range temp1 to temp2
{
arr[j] = n;
}
j can be bigger than n. but arr malloc space is n. the array overflowed.
it will work with a small change
arr = (int*)malloc(2*n*sizeof(int));
I have to implement a function which, given a matrix of 0s and 1s, returns a new matrix that contains the coordinates of the 1s. For example: if matrix is 3x3 and the output is:
1 0 1
0 1 1
0 0 1
New matrix will be 5x2 and the output will be:
0 0
0 2
1 1
1 2
2 2
Some advice? My method would be this:
int matrix[3][3];
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
if (matrix[i][i] == 1){
//Code i need
}
}
}
The solution really depends on the requirement:
Is it allowed to allocate result matrix with the maximum size possible (in this case 9 x 2).
If point 1 is not allowed, is it strictly required to use fixed size array (no dynamic allocation). If this is the case then may need to pass the matrix twice to allocate the right size of array.
Other solution is of course by using dynamic allocation (using malloc etc).
The simplified version of option 1 & 2 is shown below:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int matrix[3][3];
matrix[0][0] = 1;
matrix[0][1] = 0;
matrix[0][2] = 1;
matrix[1][0] = 0;
matrix[1][1] = 1;
matrix[1][2] = 1;
matrix[2][0] = 0;
matrix[2][1] = 0;
matrix[2][2] = 1;
//Solution 1 - If allowed to allocate matrix with size more than the result,
//i.e. if input is 3x3 matrix, then the maximum size of result matrix is 9 x 2
int resultMatrix1[9][2];
int usedCount1=0;
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++) {
if (matrix[i][j] == 1) {
resultMatrix1[usedCount1][0] = i;
resultMatrix1[usedCount1][1] = j;
usedCount1++;
} //end if
} //end for
} //end for
//Print the result
printf("\nSolution 1\n");
for (int i = 0; i < usedCount1; i++){
printf("%d %d\n", resultMatrix1[i][0], resultMatrix1[i][1]);
} //end for
//Solution 2 - strictly allocate matrix with size equal to the result.
//Without using dynamic allocation, meaning we need to have two passes.
//1st pass is to count the element which satisfy the criteria
int usedCount2=0;
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++) {
if (matrix[i][j] == 1) {
usedCount2++;
} //end if
} //end for
} //end for
int resultMatrix2[usedCount2][2]; //allocate the right size
int idx=0;
//2nd pass is to fill in the result matrix
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++) {
if (matrix[i][j] == 1) {
resultMatrix2[idx][0] = i;
resultMatrix2[idx][1] = j;
idx++;
} //end if
} //end for
} //end for
//Print the result
printf("\nSolution 2\n");
for (int i = 0; i < usedCount2; i++){
printf("%d %d\n", resultMatrix2[i][0], resultMatrix2[i][1]);
} //end for
return 0;
}
Results are the same for both solution:
Solution 1
0 0
0 2
1 1
1 2
2 2
Solution 2
0 0
0 2
1 1
1 2
2 2
If matrix[i][j] == 1 what do you know about the coordinates [i,j] ? That they are the coordinates of a 1 :)
Secondly, will the input matrix always be 3x3? If not, you'll want to store the dimensions of the matrix in variables, and use theses variables for your for loops.
I just started learning C (coding in general) a few months ago. Earlier today when I was in class, I looked at the numpad and wondered whether I would be able to replicate the pattern using nested loops in C.
7 8 9
4 5 6
1 2 3 // This pattern.
I tried to do it myself for a bit, using for loops primarily. Thanks for any help.
#include<stdio.h>
int main()
{
int row, col, i;
printf("Up to what integer? ");
scanf("%d", &row);
for(i=1; i<=row; i++)
{
for(col=1; col<=10; col++)
{
printf(" %d ", i*col);
}
printf("\n");
}
}
Edit: Added supplementary code. Something like this, except to print 3 rows and 3 columns.
The numpad pattern has the equation 3*i + j with i going from 2 to 0 and j going from 1 to 3.
So use these values as upper and lower limits of i and j in nested for loops.
#include <stdio.h>
int main(){
for(int i = 2; i >= 0; i--){
for(int j = 1; j <= 3; j++)
printf("%d ", 3 * i + j);
printf("\n");
}
return 0;
}
See it live here.
Here's how you can do it:
for(int i = 0; i < 3; ++i){
for(int j = 3; j > 0; --j)
printf("%d ", (10 - j) - i * 3);
printf("\n");
}
I am trying to solve this Queen problem of placing 4 queen in 4x4 matrix . I know it can be solved with backtracking algorithm . However i have not studied that and i am trying to solve it with my current knowledge . So what i am trying is to generate all possible combination of Queen in 4x4 matrix and print only one which cannot cancel each other .
1) For generating all combination , i am using rand function .
However there is obviously fault in my above coding . There are some outputs with only three '1' instead of four '1' . I am not able to eliminate this problem .
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main()
{
srand(time(NULL));
int ar[30][30], i , j , a , b , c = -1, d = -1, k = 0;
while (1)
{
for (i = 0 ; i < 4 ; i++)
{
for (j = 0 ; j < 4 ; j++)
{
ar[i][j] = 0;
}
}
for (i = 0 ; i < 2 ; i++)
{
for (j = 0 ; j < 2 ; j++)
{
a = rand() % 3 ;
b = rand() % 3 ;
if (a != c || b != d)
{
ar[a][b] = 1 ; // here 1 = Queen
c = a ;
d = b;
}
}
}
}
}
2) Also is there any way i can reduce the time complexity using only these method ?
Instead of using temporary variables to check whether the array is filled, use the array itself!
for (i = 0 ; i < 2 ; i++)
{
for (j = 0 ; j < 2 ; j++)
{
a = rand() % 3 ;
b = rand() % 3 ;
if (ar[a][b] == 0)
{
ar[a][b] = 1 ; // here 1 = Queen
}
}
}
Your problem is that the inner loop will execute 4 times and you can only control 1 repeat with variables c and d.
Let's say a is 1 and b is 1: you make c = 1 and d = 1.
then a is 2 and b is 1 ... making c = 2 and d = 1.
then if a is 1 and b is 1 again, you cannot check for duplicate.
(1) You check only that a queen isn't placed on the same square as the last queen you placed. Remove the variables c and d and check whether ar[a][b] is still zero.
(2) Your scatter approach will produce many set-ups that are misses. Especially, because you don't enforce that ther cannot be any queens on the same rank and file. (In addition, rand() % 3 produces random values from 0 to 2, inclusively. You will never get a non-threatening configuration that way.)
If you want to use your random (bogosort) approach, you could use a one-dimensional array where the index is the rank and the number is the file where a queen is. Then you start with:
int queen[4] = {0, 1, 2, 3};
and shuffle the array. For 4 queens, that will yield 4! = 24 possibile configurations. You could try to iterate through them systematically.
The following is the brute force, backtracking code for the 8 queens problem, asked some time ago. Just change 8 to 4:
int checkBoard(int board[8][8]);
int putQueens(int board[8][8], int nQueens);
void printBoard(int board[8][8]);
int eightQueens(void)
{
int board[8][8];
memset(board, 0, sizeof(int)*64);
if (putQueens(board, 0)) {
printBoard(board);
return (1);
}
return(0);
}
int putQueens(int board[8][8], int nQueens)
{
int i, j;
for (i=0; i<8; i++) {
for (j=0; j<8; j++) {
if (board[i][j]==0) {
board[i][j]= 1;
if (checkBoard(board)) {
if (nQueens==7) return(1);
if (putQueens(board, nQueens+1)) return(1);
}
board[i][j]= 0;
}
}
}
return(0);
}
int checkBoard(int board[8][8])
{
int i, j;
for (i=0; i<8; i++) {
for (j=0; j<8; j++) {
if (board[i][j]) {
int ii, jj;
for (ii=i+1; ii<8; ii++) {
if (board[ii][j]) return(0);
}
for (jj=j+1; jj<8; jj++) {
if (board[i][jj]) return(0);
}
for (ii=i+1, jj=j+1; ii<8 && jj<8; ii++, jj++) {
if (board[ii][jj]) return(0);
}
for (ii=i-1, jj=j-1; ii>0 && jj>0; ii--, jj--) {
if (board[ii][jj]) return(0);
}
for (ii=i-1, jj=j+1; ii>0 && jj<8; ii--, jj++) {
if (board[ii][jj]) return(0);
}
for (ii=i+1, jj=j-1; ii<8 && jj>0; ii++, jj--) {
if (board[ii][jj]) return(0);
}
}
}
}
return (1);
}
void printBoard(int board[8][8])
{
int i,j;
printf(" ");
for (j=0; j<8; j++) printf(" %1d",j+1); printf("\n");
for (i=0; i<8; i++) {
printf("%1d ",i+1);
for (j=0; j<8; j++)
printf(" %1c", board[i][j]==0? '-':'*');
printf("\n");
}
}