"C" i couldnt understand how i can add two matrises - c

I'm a begginer about c and i need help about it please help
{
int matris[2][2];
for(int i=0;i<2;i++)
{
for(int j=0;j<4;j++)
{
printf("Sayi giriniz: "); scanf("%d",&matris[i][j]);
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<2;j++)
{
printf("%d ",matris[i][j]);
}
printf("\n");
}
}

As a beginner, you need to realize that programming is nothing more than problem-solving, well there is the bit about expressing the answer in a programming language.
Doing matrix addition -- how do you do it, how would a mathematician define it? Arnaldo has given you the answer to this, $A + B = C$ where $c_{ij} = a_{ij} + b_{ij}$. So already, this starts to set some restrictions on the two matrices that your are working with, notably they have to have the same number of rows and columns.
Representation of matrices -- ok, now that you know how to add to matrices, you need to figure out how you are going to represent a matrix in your program. Computer memory is a one-dimensional array of storage units, so we need to map our two dimensional structure onto this one-dimensional array. There are two ways of doing this. The first is row major which means that we write the first row to memory, then the second row and so on. The second is column major which means that we write the first column to memory and then the second row.
Consider the following 2x3 matrix:
| a b c |
| d e f |
in row-major form, it would be laid out in memory as:
+---+---+---+---+---+---+
| a | b | c | d | e | f |
+---+---+---+---+---+---+
and in column-major form, in would be laid out in memory as:
+---+---+---+---+---+---+
| a | d | b | e | c | f |
+---+---+---+---+---+---+
Remember that computer science is zero based, so where a mathematician would designate the first element in the first row as a_{11}, we will be using zero based indicies so we will designate it as a_{00}.
Most modern program languages use row-major form to store two dimensional arrays (or in this discussion matrices). So what you might ask? Well, because we are mapping a two dimensional array to a one dimensional array, and all we really know about the one dimensional array is its starting point in memory, we need to be able to change the pair (row, col) into a single index. You should convince yourself that the following equation is correct, assuming that nRow and nCol are the number of rows and columns in the matrix.
index = nCol * row + col
So, now write some code to add to matrices together. In pseudo-code form this would be:
A <-- read in first n-by-m matrix
B <-- read in second n-by-m matrix
C <-- initialize a n-by-m matrix to all zero elements.
for(r = 0; r < nRow; r++)
for(c = 0; c < nCol; c++)
C[r][c] = A[r][c] + B[r][c]
print C
It is an implementation detail to decide if you want to use fix sized matrices, i.e. 'A[2][2]', or potentially use a dynamically allocated matrix, i.e. 'A = malloc(nRow * nCol * sizeof(int));' (assuming we are storing integers). This will determine exactly how the addition line in the above pseudo-code would be written.
Hope this helps, and kinda show you how to approach problems like this.
Don't be afraid to ask additional questions if you get stuck on attempting the implementation.
Best of Luck,
T

I don't fully understand what your question is, but I can definately show you how to add two matricies of the same length elementwise, if that's what you're looking for.
#include <stdio>;
int main()
{
//this part is declaring the two arrays you want to add,
//and the array you want to store the result in.
int arrayA[3];
int arrayB[3];
int result[3];
//this part is just initializing the data in the array
arrayA[0] = 1;
arrayA[1] = 2;
arrayA[2] = 3;
arrayB[0] = 5;
arrayB[1] = 6;
arrayB[2] = 7;
//loops from 0 to 2, and adds the nth element of arrayA and
// arrayB to store in result
for(int n =0; n < 3; n++)
{
result[n] = arrayA[n] + arrayB[n];
}
//at this point, result is the addition of your arrays.
//You can print it, or whatever it is you wanted to do with it.
return 0;
}
There are many different things that could be 'adding matricies', but this is one of them.
However, the code you submitted looks like you're trying to store numbers from the keyboard into a 2D array. You're on the right track there, but on your first nested for loop your inner loop goes too far, so it's going outside of the array bounds. Try more liek this:
int matris[2][2];
for(int i=0;i<2;i++)
{
//you had j<4 here. That will put you in invalid memory!
for(int j=0;j<2;j++)
{
printf("Sayi giriniz: "); scanf("%d",&matris[i][j]);
}
}
//you had i<3 here. That will also put you in invalid memory.
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
printf("%d ",matris[i][j]);
}
printf("\n");
}
I hope I've addressed whatever question you were going for.
İyi şanslar!

Related

Why is the Index NOT out of bounds although it intuitively should?

I'm relatively new to C programming and I stumbled upon a for me unexplainable behaviour while running the following code and debugging it using gdb and lldb.
In short: When swapping the indices i and j (max i != max j) when accessing a value in a two-dimensional Array inside a double nested for-loop it does not seem to matter if I access the value using array[i][j] or array[j][i].
The two loops and arrays are mostly identical.
unsigned matrix[3][1] =
{
{3},
{4},
{5}
};
//Loop1
for (size_t i = 0; i < sizeof(matrix) / sizeof(*matrix); i++)
{
for (size_t j = 0; j < sizeof(matrix[i]) / sizeof(*matrix[i]); j++)
{
matrix[i][j] <<= 1;
printf("matrix[%zu][%zu] has the value: %d\n", i, j, matrix[i][j]);
}
}
//same two dimensional array as matrix
unsigned matrix2[3][1] =
{
{3},
{4},
{5}
};
//Loop2, basically the same loop as Loop1
for (size_t i = 0; i < sizeof(matrix2) / sizeof(*matrix2); i++)
{
for (size_t j = 0; j < sizeof(matrix2[i]) / sizeof(*matrix2[i]); j++)
{
//swapped i and j here
matrix2[j][i] <<= 1;
printf("matrix2[%zu][%zu] has the value: %d\n", j, i, matrix2[j][i]);
}
}
Am I missing here something?
In both cases i is passed the value 2 at the end of the outer loop and j the value 0 at the end of the inner loop.
Intuitively, matrix[0][2] should throw an exception as each row only has one element.
I will take a slightly different approach than the other respondents.
You are technically not reading outside of the array's boundary as far as the memory layout is concerned. Looking at it from a human perspective you are (the index [0][2] doesn't exist!), but the memory layout of the array is contiguous. Each of the "rows" of the matrix are stored next to each other.
In memory, your array is stored as: | ? | 3 | 4 | 5 | ? |
So when you index to matrix[1][0] or matrix [0][1] you are accessing the same position in memory. This would not be the case if your array was larger than 1 dimension wide.
For example, replace your array with the following one and experiment. You can access integer '4' either by indexing matrix[0][2], or matrix [1][0]. The position [0][2] shouldn't exist, but it does because the memory is contiguous.
unsigned matrix[3][2] =
{
{3, 6},
{4, 8},
{5, 10}
};
Oops, matrix[0][2] should throw an exception as each row only has one element...
Some languages do warn the programmer by an exception if they try an out of bound access, but C does not. It just invokes Undefined Behaviour. On a technical point of view, it means that the compiler does not have to test the out of bound condition. On an operational point of view, it means that anything can happen, including expected behaviour... or an immediate crash... or a modification of an unrelated variable... or...
If my C skills aren't mega-rusty you're reading "unsafe memory".
Essentially your matrix is declared as a block of bytes. After that block of bytes there are more bytes. What are they? Usually more variables that are declared as your program's data. Once you reach the end of the program's data block you reach the user code memory block (encoded ASM instructions).
Most languages perform checks and throw an exception when you run out of bounds by somehow keeping track of the last index that is valid to access. C does not do that and doing such thing is your very own responsibility. If you aren't careful you might be overwriting important parts of your program's code.
There are attacks that one can perform on C programs that don't sanitize user input, like a buffer overrun; which exploits what it's been described.
Essentially if you declare a char[] of length N and store a string that comes from outside and this string happens to be of length N+X you'll be overwriting program memory (instructions).
With the right sequence of characters you can inject your very own assembly code into a running program which doesn't sanitize user input
As your array is int and all elements are of the same size, i don't see any problem as your array is stored in contiguous space in RAM and you use a special case of matrix where inverting indexes has no side effect.
In the first loop your indexes are [0][0], [1][0], [2][0]
In the second loop your indexes are [0][0], [0][1], [0][2]
now try to linear the access, as your array is saved as linear array into the RAM.
address of element = row * NCOL + col
row: is row number
NCOL: number of columns into your matrix
col : the column number
so the linear index for :
[0][2] ==> 0 * 1 + 2 = 2 /* the third element*/
[2][0] ==> 2 * 1 + 0 = 2 /* always the third element */
But if you use a matrix of n x m , n >= 1 and m > 1 and n != m.
if you inverse the indexes, the result will not be the same.
so if you take a 4 x 2 matrix
linear index of [3][1] = 3 * 2 + 1 = 7
linear index of [1][3] = 1 * 2 + 3 = 5 /* even [1][3] is out of the range of your matrix index */
[1][3] you will manipulate the element [2][1]
So be worry when manipulating matrix indexes.

i want to combine two 2d array into array with points

I want to combine two 2D arrays into one Nx2 array.
For example a=[1,2,3] b=[4,5,6], and I want to make c=[(1,4),(2,5),(3,6)].
i want to do it in python, but i don't know what command should i use. any hint?
you can do that in any language you want, the algorithm will likely be the same. What you want to do is
create matrix c
read through each array
grab the point at index i in each
put a[i] into matrix row i column 0
put b[i] into matrix row i column 1
here's some pseudo code to illustrate
int [][] c;
for (int i = 0; i < a.length; i++) {
c[i][0] = a[i];
c[i][1] = b[i];
}

Delete a column from a double array

I'm stuck here. I've got a matrix of size NxN stored in a double array. Then I want to delete a given column, lets say the first column. So I created a new double array of size NxN-1 and copy the values from the first matrix to the second one, except the 1st column of course. But then I want to set the first array to be the second array. I am blanking here.
double matrix[N][N]
//fill up the matrix code here...
// remove first column of array
double newMatrix[N][N-1];
for(i = 0; i < N; i++){
for(j = 1; j < N; j++){
newMatrix[i][j-1] = matrix[i][j];
}
}
matrix = newMatrix; // how do I set this correctly? Do I need to realloc the first array?
You cannot assign arrays in C, which I assume that your compiler tells you. To do such dynamic memory management, you will need to use pointers instead of arrays. I suggest you read up on how malloc() and free() work so that you can do what you want.
Edit:
Another solution comes to mind if you are only removing columns (or rows): keep track of the number of rows and columns used in the array. Then you can remove a row or column within the original array without creating a copy first. Just move the data past the delete column (or row) to the left (or up) then decrement your size counters. (I hope this make sense. If not let me know and I'll elaborate.)
like Code-guru said malloc() and free() should help alot, but if u simply wanted to delete the last column the you wouldn't need two arrays:
double matrix[2][3] = {1,2,3,4,5,6}; //declaring a 2 by 3 matrix
for (i=0;i<2;i++) //rows
{
for (j=0;j<3-1;j++) //columns - 1
{
printf("%.1f ",matrix[i][j]); //I chose to display matrix...
}
printf("\n");
}
Instead of accessing elements from array[i][j], one might opt to access elements from array + stride_x[x] + stride_y[y]; where array is originally introduced as double matrix[N*N]; or double *matrix = malloc(sizeof(double)*N*N);.
The stride_y[x] would originally contain offsets of columns for all rows: 0 1 2 3 4 ... N-1 and stride_y[y] would contain similar offsets multiplied with original row width 0 N 2*N 3*N..
From these 1-D arrays one can more effortlessly delete or exchange complete rows and columns, which may come handy in eg. recursive implementation of determinant calculation / Gauss Jordan elimination.

Concatenate two matrices in C

I'm trying to concatenate the same matrix in C, and the only idea that crossed to my mind is addition, but it doesn't work. For example, if I have: {1,1;2,2}, my new matrix should be {1,1,1,1;2,2,2,2}. I want to double the number of rows. I Googled, but I didn't find anything.
Here is my code:
matrix2=realloc(matrix1,sizeof(int*)*(row));
int i,j;
for(i=0;i<row;i++){
for(j=0;j<col;j++){
matrix2[i][j]=matrix1[i][j]+matrix1[i][j];
}
}
Use the psuedocode I provide below. Note that for any C before C99, you cannot instantiate arrays with int matrix[2*W][H] (if W and H are not #defines)
Given matrix1 and matrix 2 of equal W,H
make matrix3 of 2*W,H
for h to H
for i to W
matrix3[h][i] = matrix1[h][i]
matrix3[h][i+W] = matrix2[h][i]
Making the matrix will require 1 malloc per row, plus 1 malloc to store the array of row pointers.
Note how you will need 2 assignments in the loop instead of the one you had before. This is because you are setting in two places.
You sound like you have a background with higher level languages like matlab. In C the plus operator does not concatenate matrices. This will add the values in the matrices and store the new value into the new matrix.
Here we are copying the input matrix into a new matrix twice
for(int i = 0; i < m; i++){for(int j = 0; j < n;j++)
{ mat2[i][j] = mat[i][j];}}
for(int i = 0 ; i < m ; i++){for(int j = n; j < (2*n) ; j++){ mat2[i][j] = mat[i][j-n];}}

alternative to multidimensional array in c

tI have the following code:
#define FIRST_COUNT 100
#define X_COUNT 250
#define Y_COUNT 310
#define z_COUNT 40
struct s_tsp {
short abc[FIRST_COUNT][X_COUNT][Y_COUNT][Z_COUNT];
};
struct s_tsp xyz;
I need to run through the data like this:
for (int i = 0; i < FIRST_COUNT; ++i)
for (int j = 0; j < X_COUNT; ++j)
for (int k = 0; k < Y_COUNT; ++k)
for (int n = 0; n < Z_COUNT; ++n)
doSomething(xyz, i, j, k, n);
I've tried to think of a more elegant, less brain-dead approach. ( I know that this sort of multidimensional array is inefficient in terms of cpu usage, but that is irrelevant in this case.) Is there a better approach to the way I've structured things here?
If you need a 4D array, then that's what you need. It's possible to 'flatten' it into a single dimensional malloc()ed 'array', however that is not quite as clean:
abc = malloc(sizeof(short)*FIRST_COUNT*X_COUNT*Y_COUNT*Z_COUNT);
Accesses are also more difficult:
*(abc + FIRST_COUNT*X_COUNT*Y_COUNT*i + FIRST_COUNT*X_COUNT*j + FIRST_COUNT*k + n)
So that's obviously a bit of a pain.
But you do have the advantage that if you need to simply iterate over every single element, you can do:
for (int i = 0; i < FIRST_COUNT*X_COUNT*Y_COUNT*Z_COUNT; i++) {
doWhateverWith *(abc+i);
}
Clearly this method is terribly ugly for most uses, and is a bit neater for one type of access. It's also a bit more memory-conservative and only requires one pointer-dereference rather than 4.
NOTE: The intention of the examples used in this post are just to explain the concepts. So the examples may be incomplete, may lack error handling, etc.
When it comes to usage of multi-dimension array in C, the following are the two possible ways.
Flattening of Arrays
In C, arrays are implemented as a contiguous memory block. This information can be used to manipulate the values stored in the array and allows rapid access to a particular array location.
For example,
int arr[10][10];
int *ptr = (int *)arr ;
ptr[11] = 10;
// this is equivalent to arr[1][0] = 10; assign a 2D array
// and manipulate now as a single dimensional array.
The technique of exploiting the contiguous nature of arrays is known as flattening of arrays.
Ragged Arrays
Now, consider the following example.
char **list;
list[0] = "United States of America";
list[1] = "India";
list[2] = "United Kingdom";
for(int i=0; i< 3 ;i++)
printf(" %d ",strlen(list[i]));
// prints 24 5 14
This type of implementation is known as ragged array, and is useful in places where the strings of variable size are used. Popular method is to have dynamic-memory-allocation to be done on the every dimension.
NOTE: The command line argument (char *argv[]) is passed only as ragged array.
Comparing flattened and ragged arrays
Now, lets consider the following code snippet which compares the flattened and ragged arrays.
/* Note: lacks error handling */
int flattened[30][20][10];
int ***ragged;
int i,j,numElements=0,numPointers=1;
ragged = (int ***) malloc(sizeof(int **) * 30);
numPointers += 30;
for( i=0; i<30; i++) {
ragged[i] = (int **)malloc(sizeof(int*) * 20);
numPointers += 20;
for(j=0; j<20; j++) {
ragged[i][j]=(int*)malloc(sizeof(int) * 10);
numElements += 10;
}
}
printf("Number of elements = %d",numElements);
printf("Number of pointers = %d",numPointers);
// it prints
// Number of elements = 6000
// Number of pointers = 631
From the above example, the ragged arrays require 631-pointers, in other words, 631 * sizeof(int *) extra memory locations for pointing 6000 integers. Whereas, the flattened array requires only one base pointer: i.e. the name of the array enough to point to the contiguous 6000 memory locations.
But OTOH, the ragged arrays are flexible. In cases where the exact number of memory locations required is not known you cannot have the luxury of allocating the memory for worst possible case. Again, in some cases the exact number of memory space required is known only at run-time. In such situations ragged arrays become handy.
Row-major and column-major of Arrays
C follows row-major ordering for multi-dimensional arrays. Flattening of arrays can be viewed as an effect due this aspect in C. The significance of row-major order of C is it fits to the natural way in which most of the accessing is made in the programming. For example, lets look at an example for traversing a N * M 2D matrix,
for(i=0; i<N; i++) {
for(j=0; j<M; j++)
printf(“%d ”, matrix[i][j]);
printf("\n");
}
Each row in the matrix is accessed one by one, by varying the column rapidly. The C array is arranged in memory in this natural way. On contrary, consider the following example,
for(i=0; i<M; i++) {
for(j=0; j<N; j++)
printf(“%d ”, matrix[j][i]);
printf("\n");
}
This changes the column index most frequently than the row index. And because of this there is a lot of difference in efficiency between these two code snippet. Yes, the first one is more efficient than the second one!
Because the first one accesses the array in the natural order (row-major order) of C, hence it is faster, whereas the second one takes more time to jump. The difference in performance would get widen as the number of dimensions and the size of element increases.
So when working with multi-dimension arrays in C, its good to consider the above details!

Resources