Creating a Transposed Matrix in C - c

Creating a Program to print a Transposed Matrix
I'm creating a program in C where the user must define the number of rows and columns of a matrix, then the program must create random numbers and print the Transposed Matrix. I've achieved the first part, but my code isn't working for creating the Transposed Matrix. If it's a squared matrix, it must calculate also the D(mxn) * I(mxn), where D is the matrix and I the Identity matrix. Here`s the code:
#include <stdio.h>
#include <stdlib.h>
int main() {
unsigned short i, j, m, n;
int matriz[m][n], mTransposta[m][n], random;
printf("Entre a dimensao m da matriz: ");
scanf("%hu", &m);
printf("Entre a dimensao n da matriz: ");
scanf("%hu", &n);
printf("A matriz randomizada e:\n");
for(i = 0; i < m;i++) {
for(j = 0; j < n;j++) {
random= rand()%100;
matriz[m][n]= random;
printf("%i ", matriz[m][n]);
}
printf("\n");
}
printf("A matriz Transposta e:\n");
for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
mTransposta[m][n]= matriz[n][m];
}
printf("%i ", matriz[m][n]);
}
printf("\n");
}

At least these problems
Declared too early
When int matriz[m][n] is declared, m, n do not have assigned values. Declare int matriz[m][n] after assigning m, n.
// int matriz[m][n], mTransposta[m][n], random;
printf("Entre a dimensao m da matriz: ");
scanf("%hu", &m);
printf("Entre a dimensao n da matriz: ");
scanf("%hu", &n);
int matriz[m][n], mTransposta[m][n], random;
Transposed array
This implies mTransposta[m][n] should be mTransposta[n][m]
Print more often
printf("%i ", matriz[m][n]); only prints in an outer loop. Expect that in an inner loop.
Unused mTransposta[m][n]
Code never reads the values in mTransposta[m][n]=.
Other
scanf() return values not checked.
D(mxn) * I(mxn) code missing.
Identity matrix never formed.
Printing a space after the last number is poor form. Alternative:
const char *sep = "";
for(unsigned j = 0; j < n;j++) {
matriz[m][n] = rand()%100;
printf("%s%i", sep, matriz[m][n]);
sep = " ";
}
printf("\n");

Related

To printf a matrix

When i want to print a matrix which i input,i can use code:
#include <stdio.h>
int main(void)
{
int n, m; //row and column
printf("Enter row and column:\n");
scanf("%d %d", &n, &m);
int x[n][m];
printf("Enter your matrix:\n");
for (int i = 0; i < n; i++) //input my matrix
{
for (int j = 0; j < m; j++)
{
scanf("%d", &x[i][j]);
}
}
printf("print it:\n");
for (int i = 0; i < n; i++) //print it
{
for (int j = 0; j < m; j++)
{
printf("%d ", x[i][j]);
}
putchar('\n');
}
}
enter image description here(a possible case)
In code above, I have to assign values to the rows and columns of the matrix,which named "n" and "m".
int n, m;
scanf("%d %d", &n, &m);
But now I am asking a way to automatic tally .
Can I get this one directly?
enter image description here
You can simulate a two-dimensional array with a one-dimensional array, if that's what you mean:
#include <stdio.h>
#include <stdlib.h>
#define DIGITS 3
int main(void) { // It's good practice to fill function arguments with void if not planning on using them
/* scanf("%d %d", &n, &m); Using scanf with uninitialised variables will result in
* undefined behaviour if it is unable to convert the input. Using fgets
* is easier to debug, safer, and cleaner.
* I highly recommend this: http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
*/
char buf[DIGITS+1];
printf("%s", "Enter array rows:");
fgets(buf, DIGITS+1, stdin);
const int n = atoi(buf);
printf("%s", "Enter array columns:");
fgets(buf, DIGITS+1, stdin);
const int m = atoi(buf);
int x[n*m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("Enter array value at %d, %d: ", i, j);
fgets(buf, DIGITS+1, stdin);
x[i+j] = atoi(buf);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("%d ", x[i+j]);
}
printf("\n");
}
}
I'm not really sure as to why you would do this when C supports your two-dimensional array answer equally.
But now I am asking a way to automatic tally. Can I get this one directly?
Yes.
Form a linked-list of lines. Initially the list is empty.
Read the first line of input, the "1 2 3" into a string. Use fgets().
Parse the line to detect the number of values in it.
Append the line to the linked list of lines.
Continue doing so until 1) end-of-file, 2) a blank line or 3) number of integer is not the same as the first (error condition).
Now code has the m (number of values per line) and n, the number of lines.
Form int x[n][m];
Parse the lines for values and save in x.

Check if the first and last row of a matrix has only negative values

i have some problem making this program
I have created two arrays where I go to insert the first and the last line, then I check if every element is > 0 but it doesn't seem to work..
That's my code:
int main()
{
int i, j, n, m;
int matrix[10][20];
int first_row[m];
int last_row[m];
printf("Enter number of rows : ");
scanf("%d", &n);
printf("Enter number of columns : ");
scanf("%d", &m);
/* Input data in matrix */
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
printf("Enter data in [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
if(matrix[i=0][j]) // First row
first_row[i] = matrix[i=0][j];
if(matrix[i=n-1][j]) // second row
last_row[i] = matrix[i=n-1][j];
}
}
for(i=0;i<n;i++)
{
for (j=j+1;j<n;j++)
{
if(last_row[i] < 0)
printf("Negative element");
}
}
}
I assume in the if conditions matrix[i=0][j] and matrix[i=n-1][j] was to check if the current row being input is the first or last row respectively. If that was the case then you just need to simply check if i is 0 (i == 0) or n - 1 (i == n-1) instead of using matrix[i=0][j] and matrix[i=n-1][j].
Also the line first_row[i] = matrix[i=0][j]; and last_row[i] = matrix[i=n-1][j]; will update i which is what you should avoid in a for loop where i is index. If you intended to assign values to first_row and last_row, you should change them to first_row[j] = matrix[0][j]; and last_row[j] = matrix[n-1][j]; to a get the desire result (note that j should be used for indexing first_row and last_row instead of i because j represents matrix column).
If you want to check every element in the matrix for negative values, then the for loop for (j=j+1;j<n;j++) should be changed to for (j=0;j<m;j++) and matrix[i][j] should be used instead of last_row[i].
Edit: Also as #chux suggested, you should consider initializing matrix, first_row and last_row arrays after you input n and m in order to avoid segmentation fault for any n and m values that are larger than 10 and 20 respectively.
#include <stdio.h>
int main()
{
int i, j, n, m;
printf("Enter number of rows : ");
scanf("%d", &n);
printf("Enter number of columns : ");
scanf("%d", &m);
int matrix[n][m];
int first_row[m];
int last_row[m];
/* Input data in matrix */
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
printf("Enter data in [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
if(i == 0) // First row
first_row[j] = matrix[0][j];
if(i == n-1) // second row
last_row[j] = matrix[n-1][j];
}
}
for(i=0;i<n;i++)
{
for (j=0;j<m;j++)
{
if(matrix[i][j] < 0)
printf("Negative element %d\n", matrix[i][j]);
}
}
}

Addition of number of polynomials without using structure

#include <stdio.h>
#include <stdlib.h>
int main() {
int i, j, n, m, c[20], s = 0;
int *p[100];
I ask the user to enter the number of polynomial equations to add:
printf("Enter the number of equations to add:\n");
scanf("%d", &m);
and ask the user to enter number of coefficients he is planning to use
printf("Enter the maximum coefficient size of largest equation:\n");
scanf("%d", &n);
for (j = 1; j <= m; j++) {
printf("Enter the coefficients of equation number %d:\n", j);
p[j] = (int*)malloc(n * sizeof(int));
for (i = n; i > 0; i--)
scanf("%d", p[j] + i);
printf("The equation %d becomes as follows:\n", j);
i = n;
printf("%dx^%d", *(p[j] + i), i - 1);
for (i = n - 1; i > 0; i--)
printf("+%dx^%d", *(p[j] + i), i - 1);
printf("\n");
}
the code works ok up to here but I am having problem to add polynomials
printf("On adding all equations we get:\n");
for (i = n; i > 0; i--) {
for (j = 1; j <= m; j++) {
s = s + (*(p[j] + i));
c[i] = s;
}
}
i = n;
printf("%dx^%d", c[i], i - 1);
for (i = n - 1; i > 0; i--)
printf("+%dx^%d", c[i], i - 1);
printf("\n");
return 0;
}
also I dont want to use any kind of other methods if possible... and can we multiply polynomials similarly?
If you change
for(j=1;j<=m;j++){
to
for(s=0,j=1;j<=m;j++){
your code gives correct output if dynamic memory allocated in differenet locations and garbage values are zeros.
You are allocating n*sizeof(int) memory for p[j]th pointer
p[j]=(int*)malloc(n*sizeof(int));
for(i=n;i>0;i--)
scanf("%d",p[j]+i);
That means you can access from p[j]+0 to p[j]+n-1. If read some element to p[j]+n that means you are accessing memory which doesn't belong to you.
I modified code a bit which is working fine
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,j,n,m,c[20] = {0},s=0;
int *p[100];
printf("Enter the number of equations to add:\n");
scanf("%d",&m);
printf("Enter the maximum coefficient size of largest equation:\n");
scanf("%d",&n);
for(j=1;j<=m;j++){
printf("Enter the coefficients of equation number %d:\n",j);
p[j]=(int*)malloc(n*sizeof(int));
for(i=n-1;i>=0;i--)
scanf("%d",p[j]+i);
printf("The equation %d becomes as follows:\n",j);
i=n-1;
printf("%dx^%d",*(p[j]+i),i);
for(i=n-2;i>=0;i--)
printf("+%dx^%d",*(p[j]+i),i);
printf("\n");
}
printf("On adding all equations we get:\n");
for(i=n-1;i>=0;i--){
for(s=0,j=1;j<=m;j++){
s=s+(*(p[j]+i));
c[i]=s;
}
}
i=n-1;
printf("%dx^%d",c[i],i);
for(i=n-2;i>=0;i--)
printf("+%dx^%d",c[i],i);
printf("\n");
return 0;
}
Note: Don't forgot to add check for scanf and malloc.

Passing a two dimensional array by reference in C

I need help with a homework problem.
The description of the homework is:
Design a program in C, using the method of call by reference, which
generates statistics on the grades in a class consisting of M students
and N quizzes given during the course of a semester. The quizzes all
carry equal weighting, with the grade in each quiz being out of 10
points. The program is to do the following in the indicated sequence
when the program is executed:
Ask the user to type on the keyboard the number of number of students M and the number of quizzes N, with M representing the number
of rows and N representing the number of columns in a two-dimensional
array x[M][N] of floating-point numbers.
Ask the user to type on the keyboard the values of all the elements of the array x[M][N].
Display on the console the M rows and N columns of inputted array element values.
Generate and display on the console the elements of a one-dimensional array p[M] where each element of this array p[M]
represents the average grade over the semester of each of the M
students.
Generate and display on the console the elements of a one-dimensional array q[N] where each element of q[N] represents the
average grade in the class in each of the N quizzes .
Generate and display on the console the average grade z for the entire class over the entire semester.
This is the code that I've done so far:
#include <stdio.h>
#define students 300
#define quizzes 20
void averageGradeOfStudents(int M, int N, float p[], float *xPtr);
float averageGradeOfClass();
float averageGradeOfWholeClass();
int main() {
int M, N;
float x[students][quizzes];
printf("Enter the number students (Maximum: 300): ");
scanf_s("%d", &M);
printf("\nEnter the number of Quizzes (Maximum: 20): ");
scanf_s("%d", &N);
for (int i = 0; i < M; i++) {
for (int k = 0; k < N; k++) {
printf("Enter the grade for student %d, Quiz %d: ", i, k);
scanf_s("%f", &x[i][k]);
}
}
printf("\n--------------------------------------------------------------------------------\n\n");
for (int k = 1; k <= N; k++) {
printf("\t\tQuiz%d", k);
}
for (int i = 0; i < M; i++) {
printf("\nStudent%d Grades: ", i);
for (int k = 0; k < N; k++) {
printf("%.2f\t\t", x[i][k]);
}
}
printf("\n\n\n--------------------------------------------------------------------------------\n\n");
float p[students];
averageGradeOfStudents(M, N, p, &x[0][0]);
float q[quizzes];
float z;
getchar();
return 0;
}
void averageGradeOfStudents(int M, int N, float p[], float *xPtr) {
float grade[students];
for (int i = 0; i < M; i++) {
for (int k = 0; k < N; k++) {
grade[i] += *(xPtr + i);
}
}
for (int k = 0; k < M; k++) {
p[k] = grade[k] / N;
printf("The average grade of student%d is: %.2f\n\n", k, p[k]);
}
}
float averageGradeOfClass() {
}
float averageGradeOfWholeClass() {
}
The problem I'm having is that I can't figure out a way to sum each row of the array individually.
Very good progress on your assignment. It is refreshing to get full code and effort. There are a couple of things that will help before we get to an average. First, and always good practice, initialize your variables. This is especially true with arrays as it prevents an accidental attempt to read from an uninitialized value, and in the case of character arrays can provide automatic null-termination for the first copy to the array (as long as you only copy size-1 chars).
int M = 0, N = 0;
float x[students][quizzes] = {{ 0 }};
float p[students] = {0};
float q[quizzes] = {0};
float z = 0;
Passing arrays is always a problem area. When passing an array declared as a 2D array, you must pass the width of the array as part of the function argument:
void averageGradeOfStudents (int M, int N, float p[], float xPtr[][quizzes]);
and then you can simply call the function by passing the array itself.
averageGradeOfStudents (M, N, p, x);
(note: the first level of indirection of any array is converted to a pointer when passed as a function argument, but that is a topic for a later question. However, for your reference, your function declaration could also be properly written as):
void averageGradeOfStudents (int M, int N, float p[], float (*xPtr)[quizzes]);
Now on to your average, you were close, you only needed to sum the elements per-student by changing the way you were indexing xPtr (and initialize the values of grade):
void averageGradeOfStudents (int M, int N, float p[], float xPtr[][quizzes])
{
float grade[M];
/* initialize variable length array to 0 */
for (int i = 0; i < M; i++) grade[i] = 0;
/* sum of grades for each student */
for (int i = 0; i < M; i++) {
for (int k = 0; k < N; k++) {
grade[i] += xPtr[i][k];
}
}
printf ("The average grades for the students are:\n\n");
for (int k = 0; k < M; k++) {
p[k] = grade[k] / N;
printf(" student[%3d] is: %6.2f\n", k, p[k]);
}
}
A quick example of its use in the full-code could be:
#include <stdio.h>
#define students 300
#define quizzes 20
void averageGradeOfStudents (int M, int N, float p[], float (*xPtr)[quizzes]);
int main (void) {
/* good habit -- always initialize your variables */
int M = 0, N = 0;
float x[students][quizzes] = {{ 0 }};
float p[students] = {0};
printf("Enter the number students (Maximum: 300): ");
scanf ("%d", &M);
printf("\nEnter the number of Quizzes (Maximum: 20): ");
scanf ("%d", &N);
for (int i = 0; i < M; i++) {
for (int k = 0; k < N; k++) {
printf("Enter the grade for student %d, Quiz %d: ", i, k);
scanf("%f", &x[i][k]);
}
}
printf("\n--------------------------------------------------------------------------------\n\n");
printf (" ");
for (int k = 1; k <= N; k++) {
printf(" Quiz%-2d", k);
}
putchar ('\n');
for (int i = 0; i < M; i++) {
printf("\n Student[%3d] Grades: ", i);
for (int k = 0; k < N; k++) {
printf(" %6.2f", x[i][k]);
}
}
printf("\n\n--------------------------------------------------------------------------------\n\n");
averageGradeOfStudents (M, N, p, x);
/* getchar(); */
return 0;
}
void averageGradeOfStudents (int M, int N, float p[], float (*xPtr)[quizzes])
{
float grade[M];
/* initialize variable length array to 0 */
for (int i = 0; i < M; i++) grade[i] = 0;
/* sum of grades for each student */
for (int i = 0; i < M; i++) {
for (int k = 0; k < N; k++) {
grade[i] += xPtr[i][k];
}
}
printf ("The average grades for the students are:\n\n");
for (int k = 0; k < M; k++) {
p[k] = grade[k] / N;
printf(" student[%3d] is: %6.2f\n", k, p[k]);
}
putchar ('\n');
}
Use/Output
$ ./bin/studentavg
Enter the number students (Maximum: 300): 3
Enter the number of Quizzes (Maximum: 20): 3
Enter the grade for student 0, Quiz 0: 8
Enter the grade for student 0, Quiz 1: 9
Enter the grade for student 0, Quiz 2: 8
Enter the grade for student 1, Quiz 0: 9
Enter the grade for student 1, Quiz 1: 9
Enter the grade for student 1, Quiz 2: 10
Enter the grade for student 2, Quiz 0: 7
Enter the grade for student 2, Quiz 1: 8
Enter the grade for student 2, Quiz 2: 9
--------------------------------------------------------------------------------
Quiz1 Quiz2 Quiz3
Student[ 0] Grades: 8.00 9.00 8.00
Student[ 1] Grades: 9.00 9.00 10.00
Student[ 2] Grades: 7.00 8.00 9.00
--------------------------------------------------------------------------------
The average grades for the students are:
student[ 0] is: 8.33
student[ 1] is: 9.33
student[ 2] is: 8.00
Note: I've changed scanf_s to scanf for my system, you will need to change it back. Let me know if you have further questions.
I would not declare the array until you know the values of M and N. So the first part of main would be as shown below. (This also allows you to dump the students and quizzes constants.) And always check the return values from library functions.
int main( void )
{
int M, N;
printf("Enter the number students (Maximum: 300): ");
if ( scanf_s("%d", &M) != 1 || M > 300 ) {
printf( "Whatever\n" );
exit( 1 );
}
printf("\nEnter the number of Quizzes (Maximum: 20): ");
if ( scanf_s("%d", &N) != 1 || N > 20 ) {
printf( "Sigh...\n" );
exit( 1 );
}
float x[M][N];
// ...
}
When passing an array to a function, you can use array notation. And you're allowed to omit the first dimension of the array. So the following two function declarations are both valid
void averageGradeOfStudents(int M, int N, float p[M], float x[M][N]);
void averageGradeOfStudents(int M, int N, float p[], float x[][N]);
Inside the function, there are some problems
grade[i] is not initialized before being used (this should have resulted in a compiler warning)
Each grade[i] should be the averages of N grades (indexed by k not i)
You don't really need the grade array since you already have the p array
Here's how I would write the function (I changed the index names to keep my rows and columns clear)
void averageGradeOfStudents(int M, int N, float p[], float x[][N])
{
for (int row = 0; row < M; row++) {
p[row] = 0; // initialize the sum to zero
for (int col = 0; col < N; col++) {
p[row] += x[row][col]; // update the sum with each test result
}
p[row] /= N; // convert the sum to the average
}
for (int row = 0; row < M; row++) {
printf("The average grade of student%d is: %.2f\n\n", row, p[row]);
}
}
And the function should be called with
averageGradeOfStudents(M, N, p, x);
Summing an array is a fairly common idiom:
double sumArray(double arr[], int arrLen)
{
int i;
double sum = 0.0;
for (i = 0; i < arrLen; i++)
sum += arr[i];
return sum;
}
This sums a one-dimension array, but keep in mind that each row of your array x is a one-dimension array.
int avg=0;
int sum=0;
for (int i = 0; i < M; i++) {
for (int k = 0; k < N; k++) {
printf("Enter the grade for student %d, Quiz %d: ", i, k);
scanf("%f", &x[i][k]);
sum=sum+x[i][k]
}
}avg=sum/M;
as to get avg you have to sum...try this may help you

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