A function that prints a matrix row - arrays

I'm trying to write a function that prints a matrix row chosen by user. It works for the first row of the matrix but it doesn't work for other rows.
Here's my code.
row: the row we want to print
n: number of the rows/columns in matrix
Matrix (nxn)
Code:
#include <stdio.h>
#define SIZE 50
void prow(float *arr, int row, int n){
int i;
for(i = row * n; i < (row * n) + n; i++){
printf("%f ", *(arr+i));
}
}
int main(){
int n, i, j;
float matrix[SIZE][SIZE];
printf("Row / column number: ");
scanf("%d", &n);
for(i = 0; i < n; i++){
for(j = 0; j < n; j++){
printf("[%d][%d] element: ", i, j);
scanf("%f", &matrix[i][j]);
}
}
prow(&matrix[0][0], 2, n);
return 0;
}

The compiler already knows your array is 50 x 50 and nothing else
#define SIZE 50
float matrix[SIZE][SIZE];
but you are (probably?) using the array as if it had a different size, because you input n as size. So when you assign the entries,
scanf("%f", &matrix[i][j]);
they aren't being put in the right places (each row is still 50 entries according to the compiler, despite n being something else).
Make sure n and SIZE match.

Related

Converting matrix to an array in C

How can I copy the elements from a matrix,entered by user,to an array? I tried this, but it didn't work:
#include<stdio.h>
int main(){
int m[20][20],a[400],c=0;//max dimensions;
scanf("%d %d",&M,&N);//dimensions of matrix;
for(i=0;i<M;i++{
for(j=0;j<N;j++{
scanf("%d", &m[i][j]);
for(c=0;c<M*N;c++)
a[c]=m[i][j];
}}}
Don't know why you want to store both the matrix format and the array format, but anyway here is a code that should do the trick with also the data output to show the result:
#include <stdio.h>
#include <stdlib.h>
#define R 20 //max rows
#define C 20 //max columns
int main() {
int m[R][C]; //matrix
int a[R*C]; //array
int r, c; //user matrix size
int i, j; //iterators
printf("insert row size: ");
scanf("%d", &r);
printf("insert column size: ");
scanf("%d", &c);
if(r > R || c > C) {
printf("Invalid sizes");
return -1;
}
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
printf("insert value for row %d column %d: ", i + 1, j + 1);
scanf("%d", &m[i][j]);
a[(c * i) + j] = m[i][j];
}
}
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
printf("%d ", m[i][j]);
}
printf("\n");
}
for(i = 0; i < r * c; i++) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
Note that I also added some checks for the user data, avoiding to generate a matrix bigger that the maximum size. Also you don't need separate loops but it can be done all together.
Also please post a code that is compilable and can be run, as explained here: https://stackoverflow.com/help/how-to-ask

Filling a 2D Array in C with random numbers from 0 - 99, then sorting in descending order

This is a problem for my homework assignment but I am stuck trying to print out the array. The program will prompt the user for the "number of rows" and the "number of columns" but will terminate immediately without printing anything and I am not sure why this is happening.
Also my sorting function doesn't work. The code gives me errors about pointers but am not too familiar with them at this point. If there is a way to do without pointers, I guess that would be better. But if the best method is to use pointers, please include that. The help would be much appreictaed
warning: assignment makes integer from pointer without a cast [-Wint-conversion]
temp = A[i];
error: assignment to expression with array type
A[i] = A[j];
error: assignment to expression with array type
A[j] = temp;
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N1 100
#define M1 100
void fillMatrix(int A[][M1], int N, int M);
int sortMatrix(int A[][M1],int rowsize, int colsize);
void displayArray(int A[][M1], int N, int M);
int main(void)
{
int array[N1][M1] = {0};
fillMatrix(array, N1, M1);
displayArray(array, N1, M1);
//sortMatrix(array, N1, M1);
return 0;
}
void fillMatrix(int A[][M1], int N, int M)
{
int rows = 0, columns = 0;
//ASK FOR ROWS
printf("Enter a number of rows: ");
scanf("%i", &rows);
if(rows < 0 && rows >= 100)
{
printf("Invalid Input.\n");
printf("Enter a number of rows: ");
scanf("%i", &rows);
}
//ASK FOR COLUMNS
printf("Enter a number of columns: ");
scanf("%i", &columns);
if(columns < 0 && columns >= 100)
{
printf("Invalid Input.\n");
printf("Enter a number of columns: ");
scanf("%i", &columns);
}
//FILLS ARRAY W/ RANDOM INT VALUES BETWEEN 0 AND 100
srand(time(NULL));
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
A[i][j] = 0 + rand() % 100;
}
}
}
/*int sortMatrix(int A[][M1],int rowsize, int colsize)
{
int temp = 0;
for(int i = 0; i < rowsize; i++)
{
for (int j = 0 ; j < colsize; j++)
{
if(A[i] > A[j])
{
temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
}
return 0;
}*/
void displayArray(int A[][M1], int N, int M)
{
for(int i = 0; i < N; i++)
{
for(int j = 0; j < M; j++)
{
printf("%i ", A[i][j]);
}
}
}
Yeah, well. First of all sortMatrix(int A[][M1].... In that case, you are passing a pointer to the array row. In C++ there is no other way to pass the array to function, only via pointers.
Look over there.
Secondly, when you do something like this A[i] > A[j], you are comparing pointers of rows (In general, comparing pointers is UB, by the way. But, in your case, that is just comparing rows addresses, which is still, not what you should do when you want to sort array).
I propose this A[i][M1] > A[j][M1]. That way, you will compare elements.
Last, but not least.
but will terminate immediately without printing anything
Are you mean that console window is closing immediately? In that case, you may need to add cin.get(); to your code, after printing array, or system("pause");, in case you are using clear C, or something like this, if not.
UPD.
If you are using clean C, then instead cin.get(); you should use getchar();.
And system("pause"); truly only Windows thing.
p.s. Also, read other notes from Paul Ogilvie and Mike Housky. They are writing good things.
p.p.s. Pardon, if there is any mistake. English, not my first language, so feel free to edit the answer.
If you have any questions, please do not hesitate to contact me. I will try to answer.
The function fillMatrix retrieves two important values from the user, rows and columns, which are needed throughout the program, but these values are lost when the function exits. You then proceed to use fixed values N1 and M1
You should change the function to void fillMatrix(int A[][M1], int *set_rows, int *set_columns) and pass rows and columns by reference so that their values are saved.
if(rows < 0 && rows >= 100)
{
printf("Invalid Input.\n");
printf("Enter a number of rows: ");
scanf("%i", &rows);
}
The valid range for rows should be from 1 to M1. You should also be prepared in case the user enters the wrong value a second time.
There is no standard method to sort the values in a matrix. Do you want to sort each row? You can use qsort to sort a 1-D array.
#define TOTAL_ROWS 100
#define TOTAL_COLUMNS 100
void fillMatrix(int A[][TOTAL_COLUMNS], int *set_rows, int *set_columns)
{
int rows = 0, columns = 0;
//ASK FOR ROWS
while(1)
{
printf("Enter a number of rows: ");
scanf("%i", &rows);
if(rows > 0 && rows < TOTAL_ROWS)
break;
printf("Invalid Input.\n");
}
//ASK FOR COLUMNS
while(1)
{
printf("Enter a number of columns: ");
scanf("%i", &columns);
if(columns > 0 && columns < TOTAL_COLUMNS)
break;
printf("Invalid Input.\n");
}
for(int i = 0; i < rows; i++)
for(int j = 0; j < columns; j++)
A[i][j] = rand() % 100;
*set_rows = rows;
*set_columns = columns;
}
int compare(const void *a, const void *b)
{
return (*(int*)a - *(int*)b);
}
void sortMatrix(int A[][TOTAL_COLUMNS], int rowsize, int colsize)
{
for(int r = 0; r < rowsize; r++)
qsort(A[r], colsize, sizeof(int), compare);
}
void displayArray(int A[][TOTAL_COLUMNS], int rows, int columns)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
printf("%3i ", A[i][j]);
printf("\n");
}
}
int main(void)
{
srand((unsigned int)time(NULL));
int array[TOTAL_ROWS][TOTAL_COLUMNS] = { 0 };
int rows, columns;
fillMatrix(array, &rows, &columns);
sortMatrix(array, rows, columns);
displayArray(array, rows, columns);
return 0;
}
If you are to use your own sort, or bubble sort specifically, write a simple bubble sort function for a 1-D array, then sort the matrix 1 row at a time:
void bubble_sort(int *arr, int count)
{
for(int i = 0; i < count - 1; i++)
{
for(int j = 0; j < count - i - 1; j++)
{
if(arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void sortMatrix(int A[][TOTAL_COLUMNS], int rowsize, int colsize)
{
for(int r = 0; r < rowsize; r++)
bubble_sort(A[r], colsize, sizeof(int), compare);
}
Lastly, if rows and columns are not known ahead of time, declaring int array[100][100] is not best way. In gcc compiler you can use variable array. In Visual Studio you have to use malloc in order to dynamically allocate the array based on what the user chooses for rows and columns.

sum elements of matrix and calculate the average of the i-th line

Hi all i have a problem with this exercise in Language C.
The exercise is:
Given a matrix write a function that:
A) Calculate and return the sum of the elements.
B) Calculate and return the average of the i-th line
I did my own procedure but i have a lot errors.
My procedure is:
#include <stdio.h>
#include <stdlib.h>
void main(){
int n=10;
int m=10;
int i;
int j;
int mat [i][j];
int sum=0;
for (i=0;i<n;i++){
for (j=0; j<m;j++)
sum=sum+mat[i][j];}
printf("The sum of all elements of matrix is:%d",sum);
somma=0;
for (j=0;j<m;i++){
sum=sum+mat[i][j];
sum=sum/m
printf("The average of i-th line is:%d",sum);
}
}
i think that i have to put scanf somewhere but i don't know where.
I hope that you can help me
thank you!
You declare a matrix with undefined sizes
int mat [i][j];
where i and j are uninitizlized.
You probably want
int mat [n][m];
Moreover your matrix should be inizialized with values, otherwise you'll get the sum of stack garbage.
At the end, a possible solution is
#include <stdio.h>
int main(void)
{
int n = 2;
int m = 2;
int i;
int j;
int mat[n][m];
int sum = 0;
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
printf("Insert value of mat[%d][%d]: ", i, j);
scanf("%d", &mat[i][j]);
}
}
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
sum = sum + mat[i][j];
}
}
printf("The sum of all elements of matrix is: %d\n", sum);
for (i = 0; i < n; i++)
{
sum = 0;
for (j = 0; j < m; j++)
{
sum = sum + mat[i][j];
}
sum = sum / m;
printf("The average of line %d is: %d\n", i, sum);
}
}
As you can see I changed the average calculation:
First of all you wrote a j loop incrementing i
You must loop for all lines, so you must add a for loop that inc rows
sum must be reset each time you calculate the row average
take notes that the average is calculated using integers, so no decimals will be available.

matrix product c, core dump error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I've tried to create two matrices and do the product in another matrix, but the compiler gives an error of core dump. The creation of the first two matrices is right; something is wrong with the third matrix.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m;
int n;
int t;
int i;
int **A;
int **B;
int k;
int j;
scanf("%d",&n);
scanf("%d",&m);
scanf("%d",&t);
A=malloc(n*sizeof(int*));
for(i=0;i<n;i++){
A[i]=malloc(m*sizeof(int));
}
for(i=0;i<n;i++){ // A[n][m]
for(j=0;j<m;j++)
{
scanf("%d",&(A[i][j]));
}
}
B=malloc(t*sizeof(int*));
for(i=0;i<t;i++) //B[m][t]
{
B[i]=malloc(n*sizeof(int));
}
for(i=0;i<t;i++){
for(j=0;j<n;j++)
{
scanf("%d",&(B[i][j]));
}
}
int **C;
C=malloc(t*sizeof(int*));
for(i=0;i<t;i++){{A[i]=malloc(m*sizeof(int));}
for(i=0;i<t;i++){
for(j=0;j<m;j++){
C[i][j]=0;
for(k=0;k<n;k++)
{
(C[i][j])=(C[i][j])+((A[k][j])*(B[i][k]));
}
}
}
}
return 0;
}
You must separate memory for C, not for A. That is why when you try to access C[i][j] it generates this error. Change:
for(i=0;i<t;i++){{A[i]=malloc(m*sizeof(int));}
to
for(i=0;i<t;i++){ C[i]=malloc(m*sizeof(int));}
Complete code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m;
int n;
int t;
int i;
int **A;
int **B;
int k;
int j;
scanf("%d",&n);
scanf("%d",&m);
scanf("%d",&t);
A=malloc(n*sizeof(int*));
for(i=0;i<n;i++){
A[i]=malloc(m*sizeof(int));
}
for(i=0;i<n;i++){ // A[n][m]
for(j=0;j<m;j++){
scanf("%d", &(A[i][j]));
}
}
B=malloc(t*sizeof(int*));
for(i=0;i<t;i++) //B[m][t]
{
B[i]=malloc(n*sizeof(int));
}
printf("B\n");
for(i=0;i<t;i++){
for(j=0;j<n;j++)
{
scanf("%d",&(B[i][j]));
}
}
int **C;
C=malloc(t*sizeof(int*));
for(i=0;i<t;i++){
C[i]=malloc(m*sizeof(int));
}
for(i=0;i<t;i++){
for(j=0;j<m;j++){
C[i][j]=0;
for(k=0;k<n;k++)
{
(C[i][j])=(C[i][j])+((A[k][j])*(B[i][k]));
}
}
}
return 0;
}
Previous answers may have fixed the problem that caused the crash, but the code is still broken. It would be nice if the variables had more descriptive names. Since each variable is declared on a separate line, you could make use of the space to provide descriptive comments about the variables.
It is conventional to reference the rows of a matrix first, and then the columns. So, I will diverge from your usage, and say that matrix A has m rows and n columns. B must then have n rows, and it looks like you intend for t to hold the number of columns in B. Then the product C will be a m X t matrix.
Your code started to go wrong when you allocated space for B. You allocated for t rows of n elements, when you should have allocated for m rows of t elements (by your own notation). In my code below, because I have changed the order of m and n, I allocate for n rows of t elements.
Then, for the product matrix, I have allocated for m rows of t elements, where you had allocated for t rows of m elements. The calculation of the elements of the product matrix was also wrong in your code. The [i][j] element of C is the vector dot-product of the ith row of A and the jth column of B. The way you have calculated this element, C[i][j] is the dot-product of the jth column of A and the ith row of B.
Here is the code with corrections. I included some input prompts, and some code to display the entered matrices and the resulting product.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int m; // rows in A
int n; // cols in A
int t; // cols in B
int i;
int **A; // points to first row of A
int **B; // points to first row of B
int **C; // points to first row of C
int k;
int j;
printf("Enter number of rows in A: ");
scanf("%d", &m);
printf("Enter number of columns in A: ");
scanf("%d", &n);
printf("Enter number columns in B: ");
scanf("%d", &t);
A = malloc(sizeof(int*) * m); // A[m][n]
for(i = 0;i < m; i++){
A[i] = malloc(sizeof(int) * n);
}
for(i = 0; i < m; i++){
for(j = 0; j < n; j++)
{
scanf("%d", &(A[i][j]));
}
}
B = malloc(sizeof(int*) * n); // B[n][t]
for(i = 0; i < n; i++)
{
B[i] = malloc(sizeof(int) * t);
}
for(i = 0; i < n; i++){
for(j = 0; j < t; j++)
{
scanf("%d", &(B[i][j]));
}
}
C = malloc(sizeof(int*) * m); // C[m][t]
for(i = 0; i < m; i++){
C[i] = malloc(sizeof(int) * t);
}
for(i = 0; i < m; i++){
for(j = 0; j < t; j++){
C[i][j] = 0;
for(k = 0; k < n; k++)
{
C[i][j] = C[i][j] + A[i][k] * B[k][j];
}
}
}
printf("Matrix A:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%-5d", A[i][j]);
}
putchar('\n');
}
printf("Matrix B:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < t; j++) {
printf("%-5d", B[i][j]);
}
putchar('\n');
}
printf("Matrix product:\n");
for (i = 0; i < t; i++) {
for (j = 0; j < m; j++) {
printf("%-5d", C[i][j]);
}
putchar('\n');
}
return 0;
}
Here is the result of a test run:
λ> ./a.out
Enter number of rows in A: 2
Enter number of columns in A: 3
Enter number columns in B: 2
2 3 4
1 3 5
3 4
5 6
7 8
Matrix A:
2 3 4
1 3 5
Matrix B:
3 4
5 6
7 8
Matrix product:
49 58
53 62

Converting 2d array C code to malloc

I made a program that adds two matrices and displays their sum with a max dimension of 100.
/* This program asks the user for 2 matrices called A and B, as integers,
and displays their sum, C. The max dimension of each matrix is 100. */
#include <stdio.h>
// Construct function
void construct()
{
int m, n, i, j; // Variables
int first[100][100], second[100][100], sum[100][100]; // Matrices variables
printf("Please enter the number of rows: ");
scanf("%d", &m);
printf("Please enter the number of columns: ");
scanf("%d", &n);
// User enters m x n amount whole numbers for the Matrix A
printf("Enter Matrix A\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &first[i][j]);
// User enters m x n amount whole numbers for the Matrix B
printf("Enter Matrix B\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &second[i][j]);
// Adds the sum of Matrix A and Matrix B
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
sum[i][j] = first[i][j] + second[i][j];
// Display the sum of Matrix A and Matrix B
printf("A + B =\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
printf("%d ", sum[i][j]);
printf("\n"); // Prints new line
}
return ;
}
// Main Function
int main()
{
construct(); // Calls construct function
return 0;
}
Now I need to change it so there is no max size for each matrix.
So I need to use malloc to create my arrays.
So I cant use int A[rows][cols].
This is what I did to covert arrays to malloc. It compiles but it crashes after I entered all the integers. Need help.
/* This program asks the user for 2 matrices called A and B, as integers,
and displays their sum, C. The max dimension of each matrix is 100. */
#include <stdio.h>
#include <stdlib.h>
// Construct function
void construct()
{
int m, n, i, j; // Variables
int *first = NULL;
int *second = NULL;
int *sum = NULL; // Matrices variables
printf("Please enter the number of rows: ");
scanf("%d", &m);
printf("Please enter the number of columns: ");
scanf("%d", &n);
first = (int*)malloc(m * sizeof(int));
second = (int*)malloc(n * sizeof(int));
sum = (int*)malloc(m * n * sizeof(int));
// User enters m x n amount whole numbers for the Matrix A
printf("Enter Matrix A\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &first);
// User enters m x n amount whole numbers for the Matrix B
printf("Enter Matrix B\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &second);
// Adds the sum of Matrix A and Matrix B
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
sum = *first + *second;
// Display the sum of Matrix A and Matrix B
printf("A + B =\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
printf("%d ", sum);
printf("\n");
}
return ;
}
// Main Function
int main()
{
construct(); // Calls construct function
return 0;
}
First of all, you don't need to use malloc. Just move the array definitions to be after you have inputted m and n:
int first[m][n];
printf("Enter Matrix A\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &first[i][j]);
and similarly for second and sum.
If the matrices might be larger than 100x100 then it might be good to use malloc to avoid the risk of a stack overflow; the way to do that is:
int (*first)[n] = malloc(m * sizeof *first);
printf("Enter Matrix A\n");
// etc.
and at the end, free(first);. No other changes are required.
In your attempt to use malloc, you didn't allocate enough space, and you didn't scanf into the space you allocated either (instead you overwrote the pointer to the allocated space).

Resources