How do i select a number in a matrix in c? - c

So I have made a matrix, that's formed by (NxN). And the numbers for the matrix are put in through user input into a multidimensional array. I'm using pointers and malloc. So I have to select a number in the array to then get the sum of adjacent numbers, the number is selected just by saying the position. So just saying the 3rd number in the matrix. I am a little confused on how to just select a number, I have a general idea of incrementing to get to the right position? Would this be right? And will this then make it harder or easier to then get the sum of the adjacent numbers?
Just a little confused on how to then do this with a multidimensional array, would i just turn it back into a single array?
This is how i create the matrix:
for(i = 0; i< matrixSize; i++)
{
for(j=0; j < matrixSize; j++)
{
scanf("%d", &matrixValues[i][j]);
}
}

If you mean number in a matrix as follows (example for matrixSize == 4):
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
you can just calculate indexes from number
matrixValues[number/matrixSize][number%matrixSize]
EDIT:
For case when your 2D arreay defined as
int matrixValues[matrixSize][matrixSize];
All elements allocated in memory sequentially, i.e. element matrixValues[1][0] is exact after matrixValues[0][matrixSize-1], so you can use number as shift from adress of element matrixValues[0][0], e.g.:
*(((int*)matrixValues) + number)
For your example it can be
int matrixValues[matrixSize][matrixSize];
// input as 2D array
int i, j;
for(i = 0; i< matrixSize; i++)
{
for(j=0; j < matrixSize; j++)
{
scanf("%d", &matrixValues[i][j]);
}
}
// using address of matrix as begining of array
int* fakeArray = (int*)matrixValues;
// output as 1D arrray
int n;
for(n = 0; n < matrixSize * matrixSize ; n++)
{
printf("%d ", fakeArray[n]);
}

Related

Trying to find smallest array elements from 2 arrays returns 0 (doesn't work) and the other works. (C lang)

I'm trying to accomplish a simple task in C which is to print out the smallest number from array 1 and smallest number from array 2. Both array elements are imputed by the user.
First one just returns 0 (which in my testing case its supposed to be 1) and the other one returns the correct one (11). I seriously can't understand why and I also tried to google this with no result so that's when I once again decided to seek help here!
int main () {
int masyvas1[10] = {0};
int masyvas2[10] = {0};
for(int i = 0; i < 10; i++){
int x;
printf("Ivesk pirmo masyvo 10 sk: ");
scanf("%d", &x);
masyvas1[i] = x;
}
for(int i = 0; i < 10; i++){
int x;
printf("Ivesk antro masyvo 10 sk: ");
scanf("%d", &x);
masyvas2[i] = x;
}
int mas1maz[2] = {0, 0};
for(int i = 0; i < 10; i++){
if(masyvas1[i] < mas1maz[1]){
mas1maz[1] = masyvas1[i];
}
if(masyvas2[i] < mas1maz[2]){
mas1maz[2] = masyvas2[i];
}
}
printf("testas: %d %d", mas1maz[1], mas1maz[2]);
}
If I enter numbers say from 1 to 10 for the first array and 11 to 20 for the second the program output is: testas: 0 11 which I was expecting it to be testas: 1 11
Thank you in advance!
I would like you to go over your program by trying what is below
int mas1maz[2] = {0, 0};
The Array has 2 elements, try to print each element.
Note: there are only 2 elements but I am printing 3 as you have used mas1maz[2] ( this is grabage= 11)
printf("%d,%d,%d",mas1maz[0],mas1maz[1],mas1maz[2]);
Then you are trying to compare with mas1maz[1]=0, this will result in a minimum always equal to zero.
for(int i = 0; i < 10; i++) {
/*
*/
if(masyvas1[i] < mas1maz[1]) {
mas1maz[1] = masyvas1[i];
}
Here you are tyring to compare mas1maz[2] with garbage=11, this is the reason why you see 11.
if(masyvas2[i] < mas1maz[2]) {
mas1maz[2] = masyvas2[i];
}
What you should try is the following :
for(int i = 0; i<9; i++) {
if(masyvas1[i]>masyvas1[i+1])
{
/*copy to your array*/
mas1maz[0]=masyvas1[i]
}
/* similarly for masyvas2*/
}
see that for an array of length len, indices of the array ranges from 0 to len-1
if(masyvas2[i] < masyvas2[i]){
mas1maz[2] = masyvas2[i];
}
Change your second if as follow. You was checking for smaller number in masmaz1 array and was passing 2 in array parameters which is not compatible. As you have initialized an array for 2 locations 0 and 1 as array locations are started from 0. So change that Second if to compare it with itself for smallest number.
int min;
int max;
int i;
min=max=mas1maz[0];
for(i=1; i<10; i++)
{
if(min>mas1maz[i])
min=mas1maz[i];
}
You should use this after you fill your tables with scanf to find the minimum value
then compare the two different minimums

Remove unnecessary value entries from multidimensional array in c?

Hi I am working with a scenario where user input multiple contiguous arrays of different lengths and I want to store these array for further use.
I am using multidimensional array for this purpose.
Here is the code :
#include <stdio.h>
int main()
{
int rows,cols;
printf("Enter the number of user input arrays ? ");
scanf("%d",&rows);
printf("Enter the maximum number of inputs in a single array ?"); //Need to remove these lines
scanf("%d", &cols); //Need to remove these lines if possible
int array[rows][cols];
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
array[i][j]=0;
}
}
for(int i=0;i<rows;i++)
{
int count;
printf("Enter the number of inputs for array %d - ", i);
scanf("%d",&count);
for(int j=0;j<count;j++)
{
scanf("%d",&array[i][j]);
}
}
//// Use array for other purpose
////printf("\n\nArray --> \n");
////for(int i=0;i<rows;i++)
////{
////for(int j=0;j<cols;j++)
////{
////printf("%d ",array[i][j]);
////}
////printf("\n");
////}
return 0;
}
Example input :
Enter the number of user input arrays ? 5
Enter the maximum number of inputs in a single array ?5
Enter the number of inputs for array 0 - 5
1 2 6 3 5
Enter the number of inputs for array 1 - 1
3
Enter the number of inputs for array 2 - 2
6 5
Enter the number of inputs for array 3 - 1
3
Enter the number of inputs for array 4 - 1
9
Array created in this case :
1 2 6 3 5
3 0 0 0 0
6 5 0 0 0
3 0 0 0 0
9 0 0 0 0
Now I have number of issues in this case :
I want to reduce the space being used by removing the unnecessary entries in the array.
I would not like to use '0' or any other integer to define an unnecessary entry as it is a valid input.
I would like to remove the line
printf("Enter the maximum number of inputs in a single array ?");
scanf("%d", &cols);
Can anyone provide me help to overcome these issues.
From the design criteria you have described:
Array with user determined number of rows.
Rows have differing lengths, also user determined.
Reduce the space being used. (space only for real inputs, no padding, or filler values.)
Array definition is created at run-time per user inputs, but is not required to change during same run-time session.
Note: One design criteria: //Need to remove these lines if possible is not included in this solution. Without a description of the desired method to instruct user, I do not know how to improve on the the user prompt method.
Jagged arrays may be what you are looking for. Following is a simple example directly from the link that incorporates dynamic memory allocation that can be adapted to the code you have already discussed:
int main()
{
int rows;
//Place you user input prompts and scans here
// User input number of Rows
int* jagged[2];//
// Allocate memory for elements in row 0
jagged[0] = malloc(sizeof(int) * 1);
// Allocate memory for elements in row 1
jagged[1] = malloc(sizeof(int) * 3);
// Array to hold the size of each row
int Size[2] = { 1, 3 }, k = 0, number = 100;
// User enters the numbers
for (int i = 0; i < 2; i++) {
int* p = jagged[i];
for (int j = 0; j < Size[k]; j++) {
*p = number++;
// move the pointer
p++;
}
k++;
}
k = 0;
// Display elements in Jagged array
for (int i = 0; i < 2; i++) {
int* p = jagged[i];
for (int j = 0; j < Size[k]; j++) {
printf("%d ", *p);
// move the pointer to the next element
p++;
}
printf("\n");
k++;
// move the pointer to the next row
jagged[i]++;
}
return 0;
}
This is the concept moved a little closer to what I think you want, adapted from the code above to accept user input similar to what your code does...
int main(int argc, char *argv[])
{
int rows = 0;
int cols = 0;
int i, j;
int number = 100;
printf("Enter the number of user input arrays ? ");
scanf("%d",&rows);
// n Rows
int* jagged[rows];
int Size[rows];//array to keep size if each array
for(i=0;i<rows;i++)
{
printf("Enter the maximum number of inputs for array[%d]: ", i);
scanf("%d", &cols); //Need to remove these lines if possible
// Allocate memory for elements in row 0
jagged[i] = malloc(sizeof(jagged[i]) * cols);
Size[i] = cols;//set size of nth array
}
// User enters the numbers (This is spoofed. You will need to code per comment below.
for (i = 0; i < rows; i++) {
int* p = jagged[i];
for (j = 0; j < Size[i]; j++) {
*p = number++; //Note, this is spoofing user input .
//actual user input would be done exactly as above
//with printf prompts and scans for value
// move the pointer
p++;
}
}
// Display elements in Jagged array
for (i = 0; i < rows; i++) {
int* p = jagged[i];
for (int j = 0; j < Size[i]; j++) {
printf("%d ", *p);
// move the pointer to the next element
p++;
}
printf("\n");
// move the pointer to the next row
jagged[i]++;
}
return 0;
}

Rearranging rows in dynamically allocated 2D array in C

I'm currently working on a program in C where I input matrix dimensions and elements of a matrix, which is represented in memory as dynamic 2D array. Program later finds maximum of each row. Then it finds minimal maximum out of maximums of all rows.
For example,
if we have 3x3 matrix:
1 2 3
7 8 9
4 5 6
maximums are 3, 9, 6 and minimal maximum is 3. If minimal maximum is positive, program should proceed with rearranging order of rows so they follow ascending order of maximums, so the final output should be:
1 2 3
4 5 6
7 8 9
I made a dynamic array which contains values of maximums followed by row in which they were found, for example: 3 0 6 1 9 2. But I have no idea what should I do next. It crossed my mind if I somehow figure out a way to use this array with indices I made that I would be in problem if I have same maximum values in different rows, for example if matrix was:
1 2 3
4 5 6
7 8 9
1 1 6
my array would be 3 0 6 1 9 2 6 3. I would then need additional array for positions and it becomes like an inception. Maybe I could use some flag to see if I've already encountered the same number, but I generally, like algorithmically, don't know what to do. It crossed my mind to make an array and transfer values to it, but it would waste additional space... If I found a way to find order in which I would like to print rows, would I need an adress function different than one I already have? (which is, in double for loop, for current element - *(matrix+i * numOfCols+currentCol) ) I would appreciate if somebody told me am I thinking correctly about problem solution and give me some advice about this problem. Thanks in advance!
I don't know if I have understood it correctly, but what you want to do is to rearrange the matrix, arranging the rows by the greatest maximum to the least...
First, I don't think you need the dynamic array, because the maximums are already ordered, and their position on the array is enough to describe the row in which they are.
To order from maximum to minimum, I would make a loop which saved the position of the maximum and then, use it to store the correspondent row in the input matrix into the output matrix. Then, change the value of that maximum to 0 (if you include 0 in positives, then change to -1), and repeat the process until all rows have been passed to the output matrix. Here is a sketch of what it would look like:
for(k = 0; k < n_rows; ++k)
for(i = 0; i < n_rows; ++i)
if (max[i] > current_max)
current_max = max[i];
max_row = i;
for(c = 0; c < n_columns; ++c)
output_matrix[row][c] = inputmatrix[max_row][c];
max[max_row] = 0;
Array is not dynamic because we can not change the size of array, so in this case you can use double pointer, for example, int **matrix to store the value of 2D array.
The function for searching the max value of each row and the row index of each max value:
int * max_of_row(int n, int m, int **mat) {
// allocate for n row and the row index of max value
int *matrix = malloc (sizeof(int) * n*2);
for(int i = 0; i < 2*n; i++) {
matrix[i] = 0;
}
int k = 0;
for(int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if(matrix[k] < mat[i][j]) {
matrix[k] = mat[i][j];
}
}
matrix[k+1] = i;
k += 2;
}
return matrix;
}
The main function for test:
int main(int argc, char const *argv[])
{
// allocate for 4 rows
int **matrix = malloc (sizeof (int) * 4);
for (int i = 0; i < 4; i++) {
// allocate for 3 cols
matrix[i] = malloc(sizeof(int) * 3);
for(int j = 0; j < 3; j++){
matrix[i][j] = i+j;
}
}
int * mat = max_of_row(4, 3,matrix);
printf("matrix:\n");
for (int i = 0; i < 4; i++) {
for(int j = 0; j < 3; j++){
printf("%d ",matrix[i][j]);
}
printf("\n");
}
printf("max of row and positon\n");
for (int i = 0; i < 8; i++) {
printf("%d ", mat[i]);
}
printf("\nmax of row\n");
for (int i = 0; i < 8; i += 2) {
printf("%d ", mat[i]);
}
printf("\n");
return 0;
}
Output:
matrix:
0 1 2
1 2 3
2 3 4
3 4 5
max of row and positon
2 0 3 1 4 2 5 3
max of row
2 3 4 5

C - Access a certain row or column in a matrix

I want to know how I can print a certain row, certain column and the anti diagonal in an NxN matrix. So far I know how to print the matrix itself and the main diagonal. As you can see in the code I'm printing the main diagonal.
#include <stdio.h>
int main() {
int r1, c1;
printf("\n Enter number of rows for M1");
scanf("%d", &r1);
printf("\n Enter number of columns for M1");
scanf("%d", &c1);
int m1[r1][c1];
// int m2[][];
int i, j;
printf("\n Enter first Matrix: \n");
for(i = 0; i < r1; i++){
for(j = 0; j < c1; j++){
scanf("%d", &m1[i][j]);
}
}
for(i = 0; i < r1; i++){
for(j = 0; j < c1; j++){
if(i == j){
printf("%d", m1[i][j]);
}
}
printf("\n");
}
return 0;
}
This exercise is supposed to teach you how to translate a task into the correct loop.
In order to understand how to do that, I'd suggest this way:
Take a specific example (matrix), and write down the expected result. Then try to reverse-engineer it to the right loop code by understanding the indices pattern:
Let's take this matrix:
1 6 4 3
9 3 5 2
3 3 8 0
1 5 4 4
Example 1 - Main diagonal
Expected result would be 1384
which is practically cells (0,0) (1,1) (2,2) (3,3). Now, look at this list of indices and figure out the pattern - it's one index that increments in every iteration ==> one index (one loop) is enough:
for(i = 0; i < r1; i++) {
printf("%d", m1[i][i]);
}
Example 2 - Anti diagonal
Expected result would be 3531 which is practically cells (0,3) (1,2) (2,1) (3,0). Again, look at this list of indices and figure out the pattern - it's one index that increments in every iteration and the other one decrements. But if you think about it, the second index is a function of the first one. That means that also this one can be done with one index only:
for(i = 0; i < r1; i++) {
printf("%d", m1[i][r1 - i + 1]);
}
Because second-index = r1 - first-index + 1, always.
I tried to explain here how you should go about thinking and writing the correct loop given a task. Now try to use this method for the rest of your tasks - a certain row and a certain column (it's even easier than the diagonals).
For row 2 the indices will be (2,0) (2,1) (2,2) (2,3) - so what's the pattern?
Good luck.

Find location of numbers in 2d array

I have two arrays. Array A and Array B. Now I need to get where in array B is sequence from array A located. I need to get location of last number and I don't know how.
A[4]={6,3,3,2};
B[10][18]={
{5,3,6,5,6,1,6,1,4,4,5,4,4,6,3,3,1,3},
{6,2,3,6,3,3,2,4,3,1,5,5,3,4,4,1,6,5},
{6,4,3,1,6,2,2,5,3,4,3,2,6,4,5,5,1,4},
{5,3,5,6,6,4,3,2,6,5,1,2,5,6,5,2,3,1},
{1,2,5,2,6,3,1,5,4,6,4,4,4,2,2,2,3,3},
{4,1,4,2,3,2,3,6,4,1,6,2,3,4,4,1,1,4},
{5,3,3,2,6,2,5,2,3,1,2,6,5,1,6,4,1,3},
{4,5,2,1,2,5,2,6,4,3,3,2,3,3,3,1,5,1},
{1,3,5,5,2,1,3,3,3,1,3,3,6,3,3,3,6,5},
{4,5,2,4,2,3,4,2,5,6,5,2,6,3,5,4,5,2}
};
For example: Sequence 6,3,3,2 start in second row and in forth column and ends in seventh column. I need to get location of number 2. My result should be:
Row = 2,
Column= 7
Sequence isn't always in row. It can be in column to. For example:
3,2,4,3 and I ned to know location of number 4.
I know how to search one number in one dimensional array but in this case I don't have solution.
Language is C.
You can compare blocks using memcmp:
for (i = 0; i < rows; i++) { /* For each row */
for (j = 0; j < cols - size; j++) { /* For each col until cols - 4 */
if (memcmp(A, &B[i][j], sizeof(A)) == 0) { /* Compare entire block */
#include <stdio.h>
#include <string.h>
int main(void)
{
int A[4] = {6,3,3,2};
int B[10][18] = {
{5,3,6,5,6,1,6,1,4,4,5,4,4,6,3,3,1,3},
{6,2,3,6,3,3,2,4,3,1,5,5,3,4,4,1,6,5},
{6,4,3,1,6,2,2,5,3,4,3,2,6,4,5,5,1,4},
{5,3,5,6,6,4,3,2,6,5,1,2,5,6,5,2,3,1},
{1,2,5,2,6,3,1,5,4,6,4,4,4,2,2,2,3,3},
{4,1,4,2,3,2,3,6,4,1,6,2,3,4,4,1,1,4},
{5,3,3,2,6,2,5,2,3,1,2,6,5,1,6,4,1,3},
{4,5,2,1,2,5,2,6,4,3,3,2,3,3,3,1,5,1},
{1,3,5,5,2,1,3,3,3,1,3,3,6,3,3,3,6,5},
{4,5,2,4,2,3,4,2,5,6,5,2,6,3,5,4,5,2}
};
size_t i, j, size, rows, cols;
int founded = 0;
size = sizeof(A) / sizeof(A[0]);
rows = sizeof(B) / sizeof(B[0]);
cols = sizeof(B[0]) / sizeof(B[0][0]);
for (i = 0; i < rows; i++) {
for (j = 0; j < cols - size; j++) {
if (memcmp(A, &B[i][j], sizeof(A)) == 0) {
founded = 1;
break;
}
}
if (founded) break;
}
if (founded) printf("Row: %zu Col: %zu\n", i + 1, j + size);
return 0;
}
The problem is not the language. The problem you face is you need to come out with the algorithm first.
Actually this can be easily done by just looking at the first number of the 1D array. In your example it is 6 from (6,3,3,2).
Look for 6 in your 2D array.
Once 6 is found use a loop which loop 4 times (because there are 4 numbers to look for - (6,3,3,2).
In the loop, check whether the subsequent numbers are 3,3,2.
If it is, return the location
Else continue the process to look for 6.
Done!
It will look like this:
for(x=0; x<rows; x++)
for(y=0; y<cols; y++)
{
if(matrix[x][y] == array1D[0])
for(z=1; z<array1DSize; z++){
if(matrix[x][y] != array1D[z])
break;
location = y;
}
}
If you know how to do it with a one dimensional array, you can do it like that in C with multidimensional arrays too!
For instance, say you have a two dimensional array like so:
int array[5][5]; // 5x5 array of ints
You can actually access it in linear fashion, by doing:
(*array)[linear offset]
So that means if you want to access the 2nd column of the 2nd row, you can do:
(*array)[6]
Because the 2nd row starts at index 5, and the second column is at index 1, so you would do (5+1) to get 6. Likewise, the 3rd row would start at index 10, so if you wanted the 2nd column in the third row, you can do (10+1).
Knowing that, you can take your original algorithm and adapt it to access the multidimensional array in a linear fashion. This takes place of the "wrap around" possibility as well.

Resources