how can I print the final matrix correctly? - c

Problem Statement
A matrix is a 2D array of numbers arranged in rows and columns. We give you a Matrix of N rows and M columns.
Now your task is to do this operation on this matrix:
If the value matches with the current row and column number then add 3 with the value.
If the value matches with only the current row number then add 2 with the value.
If the value matches with only the current column number then add 1 with the value.
Input Format
The first line contains N is the number of rows in this matrix and M is the number of columns in this matrix
The second line contains a 2D array Arr[i][j].
Constraints
1 <= N, M <= 10
0 <= Arr[i][j] <= 100
Output Format
Print the matrix after the operation is done.
Sample Input 0
3 3
1 1 1
1 1 1
1 1 1
Sample Output 0
4 3 3
2 1 1
2 1 1
#include <stdio.h> 
int main(){
//here taking the row and column from the users
int row;
int column, temp;
printf("enter row and column\n");
scanf("%d%d", &row, &column);
int arr[row][column];
//here taking the matrix input through the users
for(int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
scanf("%d", &arr[i][j]);
}
for (int i=0; i<row; i++){
for(int j=0; j<column; j++ ){
if (arr[i][j] == arr[i+1] && arr[i][j]== arr[j+1]){
temp= arr[i][j]+3;
printf("%d", temp);
}
else if (arr[i][j] == arr[i+1]){
temp= arr[i][j]+ 2;
printf("%d", temp);
}
else if (arr[i][j]== arr[j+1]){
temp= arr[i][j]+ 1;
printf("%d", temp);
}
else{
temp= arr[i][j];
printf("%d", temp);
}
}
}
}
return 0;
}
After I run the code, this doesn't work.

At least this issue:
if (arr[i][j] == arr[i+1] && arr[i][j]== arr[j+1]){ is undefined behavior (UB) as code attempts to access outside int arr[row][column]; with arr[i+1] and arr[j+1].
arr[i][j] == arr[i+1] is not sensible as it attempts to compare an int with a pointer.

In c, there are two types of memories. One of them is run-time memory, where your program dynamically allocates memory based on actions done in the program execution time.
In your answer, you are setting your matrix size based on the numbers inputed by the user, which is dynamic memory.
A static array(what you are using) is not dynamic and it is the reason that you can't add more elements and change the size of it.
https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/amp/

Related

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;
}

Why I am getting wrong values from accessing 2D array in C?

I have this following program which calculates the determinant of an NxN matrix, the program itself works, but when I try to calculate the 2nd order matrix determinant at the end of recursion, accessing the 2d 2x2 array elements gives me wrong values.
I am using recursion to be able to calculate the determinant of higher-order matrices, findDet() is the recursive function, that uses a loop to call itself for each element of the first row in a given matrix and sub-matrices if their order is greater than two.
/******************************************************************************
Program to find the determinant a matrix
*******************************************************************************/
#include <stdio.h>
#define N 3
long int findDet(int arr[][N], size_t order); // To find the determinant
void initNewArr(int newArr[][N-1], int prevArr[][N], size_t order, int exCol); // To create sub matrices
int main()
{
int order = N;
printf("This program is to find determinant of a given matrix.\n\
\rNumber of row and column is going to be equal.\n");
// printf("Enter the order of the matrix: ");
// scanf("%d", &order);
// Read the input matrix from the user
int matrix[order][order];
printf("Enter matrix elements...\n");
for(int i = 0; i < order; i++) {
for(int j = 0; j < order; j++) {
printf("Enter matrix[%d][%d]: ", i+1, j+1);
scanf("%d", &matrix[i][j]);
}
}
// Print the matrix
printf("New Matrix itself...\n");
for(int i = 0; i < order; i++) {
for(int j = 0; j < order; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
// Calling findDet() to calculate determinant and store it in "det"
long int det = findDet(matrix, order);
// Print the determinant
printf("\nDeterminant of the matrix = %li", det);
return 0;
}
long int findDet(int arr[][N], size_t order) {
// if order is 2 calculate the determinant of 2nd order matrix
if(order == 2) {
int detS = ((arr[0][0]) * (arr[1][1])) - ((arr[0][1]) * (arr[1][0]));
/*
This following expression shows that accessed values are not correct
for this reason, the calculated determinant of 2nd order matrix is
not correct.
The whole problem is in this block of code
*/
printf("=== arr[0][0] * arr[1][1] - arr[0][1] * arr[1][0] = %d * %d - %d * %d\n", arr[0][0], arr[1][1], arr[0][1], arr[1][0]);
printf("Result of above expression === %d\n", detS);
return detS;
} // if order is higher then continue to break down matrix to 2nd order step by step
long int det = 0;
/*
The following for loop is for multiplying each element of
first row by determinant of sub-matrix,
which in case of below 3x3 matrix:
2 -3 1
2 0 -1 its determinant = 2 * (det of sub-matrix1) - (-3) * (det of sub-matrix2) + 1 * (det of sub-matrix3)
1 4 5
sub-matrices are:
>>> sub-matrix1
0 -1
4 5 --> in the first iteration of the array inside findDet()
while accessing the
arr[0][0] gives value 0
arr[0][1] gives value -1
arr[1][0] gives value 5
arr[1][1] gives value 1
>>> sub-matrix2
2 -1
1 5 --> in the second iteration of the array inside findDet()
while accessing the
arr[0][0] gives value 2
arr[0][1] gives value -1
arr[1][0] gives value 5
arr[1][1] gives value 1
>>> sub-matrix3
2 0
1 4 --> in the third iteration of the array inside findDet()
while accessing the
arr[0][0] gives value 2
arr[0][1] gives value 0
arr[1][0] gives value 4
arr[1][1] gives value 1
But since we get wrong values for sub-matrices the final determinant is not correct
*/
for(int i = 0; i < order; i++) {
// New sub matrix in each iteration
int newArr[order-1][order-1];
initNewArr(newArr, arr, order, i);
// Print the sub matrix
printf("\nNewly Created Sub Matrix itself...\n");
for(int i = 0; i < order-1; i++) {
for(int j = 0; j < order-1; j++) {
printf("%d\t", newArr[i][j]);
}
printf("\n");
}
// Calculate Determinant
if(i % 2 == 0) { // if i is 0 or even which then becomes odd-th element of matrix add result to det
det += (arr[0][i] * findDet(newArr, order-1));
} else { // otherwise subtract the result from the det
det -= (arr[0][i] * findDet(newArr, order-1));
}
}
return det;
} // ================== findDet()
void initNewArr(int newArr[][N-1], int prevArr[][N], size_t order, int exCol) {
for(int i = 0; i < order; i++) {
for(int j = 0; j < order; j++) {
if(i != 0 && j != exCol) { // When element is not in first row and exCol(excluded column) assign it to sub matrix
newArr[i-1][j > exCol ? j-1 : j] = prevArr[i][j]; // When column is greater than exCol subtract 1 from it
}
}
}
}
The recursion works perfectly and the problem is in the expression denoted above.
edit
for example if I input
2 -3 1
2 0 -1
1 4 5
while accessing the arr[0][0], arr[0][1], arr[1][0] and arr[1][1] in following sub-matrices
0 -1
4 5 --> in the first iteration of the array inside findDet()
2 -1
1 5 --> in the second iteration of the array inside findDet()
2 0
1 4 --> in the third iteration of the array inside findDet()
don't give me all the original values, they give some random values and some values that exist in the matrix.
you can check code comments for more details, I know this question is long and a bit confusing but I wish some of you can help me?
Can you please help me find the problem?
Thanks

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.

C - Entering values for 2d Array using for loop produces different values than entered

I have this simple program I am working on in class, it initialized a 3x5 2d Array of integers whose values are inputted for each cell by the user. The program then calls a function which runs through the array with a for loop to display each value, then calls a function which again uses a for loop to double every value, and calls the previous display function to show the array again.
All of this seems to be working, however I am consistently getting odd outputs for certain areas when initializing the values for the 2dArray.
For example: Entering 5 rows of "1, 2, 3" and then calling the display function produces this as output:
1,1,2,
1,2,3,
1,2,3,
1,2,5,
1,2,3
Further more, the doubling function produces further strange results but only in the areas where the output was different from what the user had inputted.
Output of the double function on the array I just posted displays as:
2,4,8
2,4,6
2,4,6
2,4,10,
4,8,6
The only real mathematical operation in the entire program is in the doubling functions, where it runs through a for loop setting the value of "array[j][i] = (array[j][i] = array[j][i] * 2)"
I cannot for the life of me figure out which part of the program I've written would cause the user inputs to change to what has been displayed. Inputting values other than "1,2,3" produces similarly odd results. Anyone have any idea what is wrong here? I feel like it must be a very simple mistake I am missing. Here is my source code:
#include <stdio.h>
#include <stdlib.h>
void displayArray(int array[][4]);
void doubleArray(int array[][4]);
int main() {
int dArray[2][4];
int i, j, k;
for(i = 0; i <= 4; i++){
for(j = 0; j <= 2; j++){
printf("Enter a value for the array at position %d,%d.\n", j, i);
scanf("%d", &dArray[j][i]);
}
}
printf("Displaying your original array...\n");
displayArray(dArray);
printf("Doubling your array...\n");
doubleArray(dArray);
printf("Displaying your doubled array....\n");
displayArray(dArray);
system("pause");
}
void displayArray(int array[][4]){
int i, j;
for(i = 0; i <= 4; i++){
printf("\n");
for(j = 0; j <= 2; j++){
if(j == 2 && i == 4){
printf("%d", array[j][i]);
}
else{
printf("%d,", array[j][i]);
}
//system("pause");
}
}
printf("\n");
}
void doubleArray(int array [][4]){
int i, j;
for(i = 0; i <= 4; i++){
for(j = 0; j <= 2; j++){
array[j][i] = (array[j][i] * 2);
//printf("%d\n", array[j][i]);
}
}
}
It's all in one .c file, and I am using devc++ if that makes any difference.
To calculate the DIMENSIONS of your 2D C arrays you have to count how many columns and how many rows there are. In your examples, it is 3 columns and 5 rows, and those are the values you must enter in your array definition:
int array[3][5]
Then, because C starts indexing with 0 offset, you can referr to the elements of the array using the columns 0 to 2 (that is, 3 columns) and rows 0 to 4 (that is, 5 rows). As other people said, this can be achieved using "lower than the limit" (correct: <3 for the columns, <5 for the rows) instead of "lower or equal than the limit" (incorrect, out of bounds: <=3 for the columns, <=5 for the rows).

Resources