Scanning values into a matrix without using [ ] C language - c

I have a problem. I was asked to write a program that transposes a matrix, without using []...for example, i know that if it was a one dimensional array, i could say that array[3] is the same as *(array+3)...but how do i do that with a matrix?
here's my code for scanning:
void scan_matrix(matrix mat1,int number_of_rows, int number_of_columns)
{
int row_index,column_index;
for(row_index=0;row_index<number_of_rows;row_index++)
{
printf("Enter the values of row %d\n",row_index);
for(column_index=0;column_index<number_of_columns;column_index++)
scanf("%d",WHAT GOES HERE?????);
}
}

If mat1 is a simple pointer, then this should do the job for you :
for(row_index=0;row_index<number_of_rows;row_index++)
{
printf("Enter the values of row %d\n",row_index);
for(column_index=0;column_index<number_of_columns;column_index++)
scanf("%d", (mat1 + row_index*number_of_columns + column_index));
}
The program uses the fact that matrices (2-d arrays) are in fact stored as 1-dimensional arrays in memory.
Lets take a 2d matrix :
1 2 3
4 5 6
This is stored in memory as :
1 2 3 4 5 6
So, the correct variable is accessed by using a way to map the logical positions of array elements with the actual positions. All we need is to find out the relation which turns out to be :
Pos = Row*Num_Of_Col + Col

if mat is two dimensional int array like : mat[3][3]
then scanf code would be : scanf("%d",(*(mat+row_index)+column_index));
a[3] : *(a+3)
a[3][3] : (*(a+3)+3)

Related

Multidimensional array : Split and put back together

I am trying to turn a 3 dimensional array "upside-down" as:
I have tried the inverse function, but if we look at the inverse operation in mathematical terms, it gives us another result. I need to turn without changing the data in the array. How to do that?
To split the 3-dimensional array (A x B x C) into A-sub-array (2d, B x C) I have used squeeze: k=squeeze(array(n,:,:)). Now I have a 2-dimensional array of size B x C. How to put it back together (in 3 dimensional array)?
You can use permute() to change the order of dimensions, which can be used as a multidimensional transpose.
Putting 2D matrices into a 3D one then is a simple indexing operation. Read more in indexing here.
A = rand(10,10,10);
B = permute(A, [ 3 2 1 ]); % Permute he order of dimensions
mat1 = rand(10,10);
mat2 = rand(10,10);
mat_both(:,:,2) = mat2; % Stack 2D matrices along the third dimension
mat_both(:,:,1) = mat1;
mat_both = cat(3,mat1, mat2); % Stacks along the third dimension in a faster way

about multi dimensional in c language [duplicate]

This question already has answers here:
Initializing a 2D array like a 1D array
(3 answers)
Closed 5 years ago.
If the array is initialized like this:
int a[4][3]={1,2,3,4,5,6,7,8,9};
Could someone please help me how the elements are stored in array indices, like a[0][0] will be which element and so on
Statement:
int a[4][3]={1,2,3,4,5,6,7,8,9};
is equivalent to:
int a[4][3] = {
{1,2,3}, //every row contains 3 element because second dimension is 3
{4,5,6},
{7,8,9}
};
With this way of representation, you can easily identify the value at a particular location in the given array.
a[0][0] will be which element and so on
a[0] is {1,2,3} and in this array the element at 0th location is 1. So,
a[0][0] is 1, Similarly
a[0][1] is 2
a[0][2] is 3
a[1][0] is 4
and so on.
May you write a program for better understanding, like this:
#include <stdio.h>
int main() {
int a[4][3]={1,2,3,4,5,6,7,8,9};
int i,j;
for (i = 0; i < 4; i++) {
for (j = 0; j < 3; j++) {
printf ("a[%d][%d] : %d\n", i, j, a[i][j]);
}
}
return 0;
}
The output of this program is:
a[0][0] : 1
a[0][1] : 2
a[0][2] : 3
a[1][0] : 4
a[1][1] : 5
a[1][2] : 6
a[2][0] : 7
a[2][1] : 8
a[2][2] : 9
a[3][0] : 0
a[3][1] : 0
a[3][2] : 0
Here you can see the last row (a[3]) is having all elements value 0. This is because in array initialization if there are fewer initializers than elements in the array then, remaining elements are automatically initialized to 0. Since you are providing only 3 rows in the initialization of the array of 4 rows, the elements of the last row will be initialized with 0.
The array a is:
1 2 3
4 5 6
7 8 9
0 0 0
A multi-dimensional array store arrays.Suppose you have arr[4][3],this means that that array "arr" is consist of 4 arrays, each of length you specified in the second bracket.
Also in order to assign multi-dimensional array you should do it like this
int arr[size1][size2] = {{contents of first},{content of second},{content of third},{etc}};
arr[0][0] will contain element located at first index of first array
mapping multi-dimensional data on it can be done in several ways. there are mainly two types of data store procedure in 2D Array.
1.Row Major
Computer memory will be represented as a linear array with low addresses on the left and high addresses on the right. Also, we're going to use programmer notation for matrices: rows and columns start with zero, at the top-left corner of the matrix. Row indices go over rows from top to bottom; column indices go over columns from left to right.
As mentioned above, in row-major layout, the first row of the matrix is placed in contiguous memory, then the second, and so on.
Image of Row Major :-- Click Below
Array & Memory Representation of Storing Data in 2D Array by Row Major
2.Column Major
Describing column-major 2D layout is just taking the description of row-major and replacing every appearance of "row" by "column" and vice versa. The first column of the matrix is placed in contiguous memory, then the second, and so on:
Image of Column Major:--- Click Below
Array & Memory Representation of Storing Data in 2D Array by Column Major
I hope this will help you to understand how the value stored in araay.

Knapsack with a few twist

i'm struggling a bit to make my program work, it's a school homework we have to do for the holidays and basically this is what we have to do :
We are trying to fill a knapsack to it's maximum capacity while maximising it's value with objets from a given list.
i won't bore you with the details so i'll just go straight to where i'm currently having an issue.
i have a 2d dynamic array, i'm trying to check if a line of said array doesn't contain one of the elements in another array and if it does then i need to put everything on that line in a second array.
let's say i have this code :
int **exc, rexc, *lexc, i=0;
printf("\nHow many exclusion :");
scanf("%d", &rexc);
exc = malloc( sizeof(int *) * rexc);
for(i=0;i<rexc;i++){
printf("\nHow many elements in exclusion %d : ", i);
scanf("%d", &lexc[i]);
exc[i] = malloc( sizeof(Objet) * lexc[i]);
printf("\n the elements are :");
for(j=0;j<lexc[i];j++){
scanf("%d",&exc[i][j]);
}
}
With this i have initialized and filled my array.
Now i have another array with values let's say it's something like
inter[1]={5,6}
impos[1]={3,7}
And let's say our 2d array looks like this :
exc[3][3]={3,6,2}{2,7,1}{5,2,4}
What i need to do is search through my 2d array, if any line contain 3 or 7 ( it cannot contain both, i check that by using a function that make sure that there's no problem before running this function ), then every other elements of that line need to be added to the inter[] array.
How i thought i'd make this work was by doing something like this :
int count=0,i=0, j=0, k=0;
while(count<cimp){
for(i=0;i<rexc;i++){
for(j=0;j<lexc[i];j++){
if (exc[i][j] = impos[count])
for (k=0;k<lexc[i];k++){
if(k!=j){
inter[cinter+1]=exc[i][k];
cinter++;
}
}
}
count++;
}
cinter/cimp is a variable where i stored the number of elements in inter/impos.
the result i'm getting is kinda funky tho here's an output :
How many exclusion : 3
How many elements in exclusion 1 : 3
the elements are : 3 6 2
How many elements in exclusion 2 : 3
the elements are : 2 7 1
How many elements in exclusion 3 : 3
the elements are : 5 2 4
How many obligatory elements : 1
Which are : 5
Forbidden list : 5 0 6 2 5 2 5 5 7 1 5 1 5 5 2 4 5 4 5
I'm still getting used to C, hope i could get any help from you guys and sorry for making it such a long post !

How to perform split and join functions on Array in C?

How can I perform join and split functions on array elements in C?
For example, let's say I have two arrays:
int value[]= {0,1,2,3};
int id[] = {1,1,3,3};
// I want to join the elements of "value" array whoz value of "id" are same.
//In my case 0,1 elements from "value" array has the same "id" value that is 1,1
//and 2,3 from "value" has same "id" value 3,3. So it will join {01,23}
//And if i want to perform split function it will give me back{0,1,2,3}
I did the same thing in perl script but i am not sure how can I get this functionality in C?
C doesn't have built-in "dynamic" arrays like those of many higher-level languages.
You must allocate the needed storage yourself using malloc(), then copy the desired data element by element into the new array.
Also I can't quite understand the desired operations that you describe ... "Join elements of value whose value of id are the same" doesn't make sense.
Do you want to compute the intersection of the arrays? But they're clearly not sets, so that doesn't sound right either.
The following will do what you want:
#include <stdlib.h>
#include <stdio.h>
int main(){
int i,v;
int ID_SIZE=7;
int value[]={0,1,2,3,1,4, 7};
int id[]= {1,1,3,3,2,2,10};
//Discover largest and smallest ids in order to allocate memory
int min=0,max=0,length;
for(i=1;i<ID_SIZE;++i){
if(id[i]<id[min]) min=i;
if(id[i]>id[max]) max=i;
}
//Replace ids with values
min=id[min];
max=id[max];
length=max-min+1;
int **unions;
int *append;
append=(int *)calloc(length,sizeof(int));
for(i=0;i<length;++i)
append[i]=-1; //Initial insertion point for each id is at 0
//Create 2D array unions[IDS HERE][VALUES HERE]
unions=(int **)calloc(length,sizeof(int*));
for(i=0;i<length;++i)
unions[i]=(int *)calloc(ID_SIZE,sizeof(int));
//Join arrays
for(i=0;i<ID_SIZE;++i){
printf("Inserting %d into %d at %d\n",value[i],id[i],append[id[i]-min]+1);
unions[id[i]-min][++append[id[i]-min]]=value[i];
}
for(i=0;i<length;++i){
if(append[i]>=0){
printf("Id %d has: ",i+min);
for(v=0;v<=append[id[i]-min];++v)
printf("%d ",unions[i][v]);
printf("\n");
}
}
return 0;
}
It creates two dynamic arrays.
One array, called append keeps track of how many values have been found for each id.
The other array, called unions stores the result of the computation.
In the case of the input I define in the program, the following is returned:
Inserting 0 into 1 at 0
Inserting 1 into 1 at 1
Inserting 2 into 3 at 0
Inserting 3 into 3 at 1
Inserting 1 into 2 at 0
Inserting 4 into 2 at 1
Inserting 7 into 10 at 0
Id 1 has: 0 1
Id 2 has: 1 4
Id 3 has: 2 3
Id 10 has: 7

Linear Sort of a 2D Array

I am a newbie to C programming and was trying to prepare some sorting programs. I made the program of linear/ normal Sorting.
Now I want to make a program to sort 2D array.
i.e. If the matrix is
4 6 1
3 2 9
5 7 8
Then the result should be
1 2 3
4 5 6
7 8 9
Since you want your 2D array to be sorted row-wise, which happens to be the order in which multidimensional arrays are stored in C, you could pretend it is a 1D array and sort it that way.
Assuming you have a function void sort(int[], int size); that takes a pointer to the first element of a 1D array and its size, you could do
int a[3][3] = {{4,6,1}, {3,2,9}, {5,7,8}};
sort(&a[0][0], 9);
Naturally, this only works for true 2D arrays, not for arrays of pointers, which is how dynamically allocated 2D arrays are often implemented in C.
You can use pretty much the same function, if you are allocating the memory as a regular multi-dimensional declaration... Since multi-dimensional arrays are stored in memory row after row and each row is just a regular array.
Just pass to the function the address of the first element of the matrix (usually name_of_the_matrix[0]) and the number of elements in the matrix.
Hope I could help.
The basic idea is to sort the array based on cell ordering, so you need to have a way to get a cell based on it's order and a way to write a cell based on it's ordering.
int getCellOrder(int x, int y) {
return x*(x_width) + y;
}
int getXpos(int cellOrder) {
return cellOrder / x_width;
}
int getYpos(int cellOrder) {
return cellOrder % x_width;
}
With those two elements, you can now grab any two cell orders for your array, and the values they reference.
int valueAt(int cellOrder) {
return array[getXpos(cellOrder)][getYpos(cellOrder];
}
How you compare the orders and how you swap them now becomes a simple 1D array problem.
you can use Bubble-Sort: Wikipedia and go through the array with a for-loop.
You could also take the C++ approach and do the following while representing your matrix in 1D:
#include <vector>
#include <algorithm>
using namespace std;
int main(int arg, char **argv) {
int matrix[] = {4, 6, 1, 3, 2, 9, 5, 7, 8};
vector<int> matvec (matrix, matrix + sizeof(matrix) / sizeof(int));
sort(matvec.begin(), matvec.end());
return 0;
}
I made it like this given that you made an 2D array a[][] and the elements like me:
for(i=0;i<row;i++)
for(j=0;j<col;j++)
for(k=0;k<row;k++)
for(p=0;p<col;p++)
if(a[i][j]>a[k][p])
temp=a[i][j]; a[i][j]=a[k][p]; a[k][p]=temp;

Resources