Passing a two dimensional array by reference in C - 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

Related

Creating a Transposed Matrix in 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");

I need help please

This program gives me zero primes in the array after running it. This is a program that takes 2d array [n x m] then calculate how many prime numbers are there in the 2d array.
int isprime(int n)
{
int k;
if (n <= 1)
return 0;
for (k = 2; k <= (n / 2); k++){
if (n % k == 0)
return 0;
}
return 1;
}
}
int primecount(int x, int y, int a[x][y]){
int r, c, count = 0;
for(r = 0; r < x; r++) {
for(c = 0; c < y; c++) {
if(isprime(a[r][c]))
{
count++;
}
}
}
return count;
}
int main()
{
int n, m, i, j, z;
printf("Enter the Number of Rows: ");
scanf("%d", &n);
printf("\n");
printf("Enter the Number of Columns: ");
scanf("%d", &m);
printf("\n");
int a[n][m];
printf("Enter the elements of the array: \n");
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++)
scanf("%d", &a[i][j]);
}
z = primecount(n, m, a[n][m]);
printf("\n");
printf("The Number of Prime Numbers in the array is: %d", z);
printf("\n");
return 0;
}
For starters instead of this call
z = primecount(n, m, a[n][m]);
you need to write
z = primecount(n, m, a);
In this call of the function isprime as in the call shown above
if(isprime(r, c, a[r][c]))
the expression a[r][c] is a scalar object of the type int. However the function isprime expects a two-dimensional array instead of a scalar object of the type int.
int isprime(int p, int q, int a[p][q])
^^^^^^^^^^^
Just declare the function like
int isprime( int x );
and correspondingly change its definition.
The function will be called like
if( isprime( a[r][c] ) )
Pay attention to that the logic of the function isprime is incorrect. It returns logical true for values equal to 1 and 0 though such values are not prime numbers.
Also you need to deal with an array with elements of the type unsigned int. Otherwise the user can enter negative values.
Here is your updated program.
#include <stdio.h>
int isprime(int n)
{
int k;
if (n <= 1)
return 0;
for (k = 2; k <= (n / 2); k++)
{
if (n % k == 0)
return 0;
}
return 1;
}
int primecount(int x, int y, int a[x][y]) //function to count prime numbers
{
int r, c, count = 0;
for(r = 0; r < x; r++)
{
for(c = 0; c < y; c++)
{
if(isprime(a[r][c]))
{
count++;
}
}
}
return count;
}
int main()
{
int n, m, i, j, z;
printf("Enter the Number of Rows: ");
scanf("%d", &n);
printf("\n");
printf("Enter the Number of Columns: ");
scanf("%d", &m);
printf("\n");
int a[n][m];
printf("Enter the elements of the array: \n");
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++)
scanf("%d", &a[i][j]);
}
z = primecount(n, m, a);
printf("\n");
printf("The Number of Prime Numbers in the array is: %d", z);
printf("\n");
return 0;
}
Its output might look like
Enter the Number of Rows: 2
Enter the Number of Columns: 2
Enter the elements of the array: 1 2 3 4
The Number of Prime Numbers in the array is: 2

Multiplication of 2D arrays, using pointers to pointers

I've been trying to implement a program in C, where i have two 2D arrays (created with pointers) and i have to multiply them (like multiplying matrices) and store the results to a third array. The dimensions of the arrays are given by the user. I've done the code but i'm getting wrong results. Is there something wrong with my formula? I wanted to do the reading and printing with functions.
For example, when i input n = 2, m = 2 and k =2. For each element of the matrix i input
A(0)(0) = 1, A(0)(1) = 2, A(1)(0) = 3, A(1)(1) = 4
and
B(0)(0) = 1,> B(0)(1) = 2, B(1)(0) = 3, B(1)(1) = 4.
The output should've been
C(0)(0) = 7, C(0)(1) = 10, C(1)(0) = 15 and C(1)(1) = 22.
Instead the output is
C(0)(0) = 7, C(0)(1) = 10, C(1)(0) = 33, C(1)(1) = 46.
I hope it's not hard to understand, i'm not allowed to post an image yet :(
#include <stdio.h>
#include <stdlib.h>
int **read(int **x, int i, int j);
int **prod(int **x, int **y, int n, int m, int k);
void print(int **x, int r, int c);
int main()
{
int n, m, k, i, j;
printf("Give n, m and k: ");
scanf("%d%d%d", &n, &m, &k);
int **A, **B, **C;
A = (int **)malloc(n*sizeof(int *));
for (i = 0; i < n; i++)
*(A+i) = (int *)malloc(k*sizeof(int));
B = (int **)malloc(k*sizeof(int *));
for (i = 0; i < k; i++)
*(B+i) = (int *)malloc(m*sizeof(int));
C = (int **)malloc(n*sizeof(int *));
for (i = 0; i < n; i++)
*(C+i) = (int *)malloc(m*sizeof(int)
for (i = 0; i < n; i++)
for (j = 0; j < k; j++)
A = read(A, i, j);
for (i = 0; i < k; i++)
for (j = 0; j < m; j++)
B = read(B, i, j);
C = prod(A, B, n, m, k);
print(C, n, m);
}
int **read(int **x, int i, int j)
{
printf("Give value to store in cell [%d][%d]: ", i, j);
scanf("%d", &x[i][j]);
return x;
}
int **prod(int **x, int **y, int n, int m, int k)
{
int i, j, l, sum;
int **res;
for (i = 0; i < n; i++)
for (j = 0; j < k; j++)
{
sum = 0;
for (l = 0; l < m; l++)
sum = sum + (x[i][l]*y[l][j]);
res[i][j] = sum;
}
return res;
}
void print(int **x, int r, int c)
{
int i, j;
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j ++)
printf("C[%d][%d]: %d\t", i, j, x[i][j]);
printf("\n");
}
}
first understand the matrix without pointers
Matrix multiplication without pointers
int r1,r2,c1,c2;
int i,j,sum,k;
void matrixmul()
{
printf("Getting values for matrices");
printf("\n---------------------------");
printf("\n Enter the row for Matrix A: ");
scanf("%d",&r1);
printf("\n Enter the column for Matrix A: ");
scanf("%d",&c1);
printf("\n Enter the row for Matrix B: ");
scanf("%d",&r2);
printf("\n Enter the column for Matrix A: ");
scanf("%d",&c2);
int a[r1][c1];
int b[r2][c2];
int c[r1][c2];
if (!((c1==r2)&&(r1==c2)))
{
printf("Row column miss matching so cannot do matrix multiplication");
}
else
{
printf("\n A Matrix");
printf("\n ---------");
for (i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("\n Enter %d and %d value: ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("\n B Matrix");
printf("\n ---------");
for (i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("\n Enter %d and %d value: ",i,j);
scanf("%d",&b[i][j]);
}
}
}
for(i=0;i<c1;i++)
{
for(j=0;j<r2;j++)
{
for (k=0;k<r2;k++)
{
sum = sum + a[i][k]*b[k][j];
}
c[i][j] = sum;
sum = 0;
}
}
printf("\nResultant Matrix");
printf("\n----------------\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
void main()
{
matrixmul();
}
Output
Enter the row for Matrix A: 2
Enter the column for Matrix A: 3
Enter the row for Matrix B: 3
Enter the column for Matrix B: 2
A Matrix
Enter the 0 and 0 value:1
Enter the 0 and 1 value:2
Enter the 0 and 2 value:3
Enter the 1 and 0 value:3
Enter the 1 and 1 value:2
Enter the 1 and 2 value:11
B Matrix
Enter the 0 and 0 value:4
Enter the 0 and 1 value:5
Enter the 1 and 0 value:7
Enter the 1 and 1 value:8
Enter the 1 and 0 value:9
Enter the 1 and 1 value:10
Resultant Matrix
45 51
125 141
Matrix with pointers-in this program 2D is declared using pointer variable and get the values for the 2D array and display the values
void main()
{
int r = 2, c = 3, i, j, count;
int *a[r];//while declaring the array as pointer its number of rows are specified
for (i=0; i<r; i++)
{
a[i] = (int *)malloc(c * sizeof(int));//Allocate memory space for each row for 'c' columns
}
count = 0;
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
{
scanf("%d",&a[i][j] );
}
}
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
{
printf("%d\t ", a[i][j]);
}
printf("\n");
}
}
Output
3
2
1
1
2
3
3 2 1
1 2 3
The following is the final complete matrix multiplication using pointers
void input()
{
int r1, c1,r2,c2, i, j,k,sum;
printf("\n Enter the row for Matrix A: ");
scanf("%d",&r1);
printf("\n Enter the column for Matrix A: ");
scanf("%d",&c1);
printf("\n Enter the row for Matrix B: ");
scanf("%d",&r2);
printf("\n Enter the column for Matrix A: ");
scanf("%d",&c2);
if (!((c1==r2)&&(r1==c2)))
{
printf("Row column miss matching so cannot do matrix multiplication");
}
else
{
int *a[r1];
int *b[r2];
int *c[r1];
for (i=0; i<r1; i++)
{
a[i] = (int *)malloc(c1 * sizeof(int));
}
for (i=0; i<r2; i++)
{
b[i] = (int *)malloc(c2 * sizeof(int));
}
for (i=0; i<r1; i++)
{
c[i] = (int *)malloc(c2 * sizeof(int));
}
printf("\n A Matrix");
printf("\n ----------");
for (i = 0; i < r1; i++)
{
for (j = 0; j < c1; j++)
{
printf("\n Enter the %d and %d value:",i,j);
scanf("%d",&a[i][j] );
}
}
printf("\n B Matrix");
printf("\n ----------");
for (i = 0; i < r2; i++)
{
for (j = 0; j < c2; j++)
{
printf("\n Enter the %d and %d value:",i,j);
scanf("%d",&b[i][j]);
}
}
for(i=0;i<c1;i++)
{
for(j=0;j<r2;j++)
{
for (k=0;k<r2;k++)
{
sum = sum + a[i][k]*b[k][j];
}
c[i][j] = sum;
sum = 0;
}
}
printf("\n Resultant Matrix");
printf("\n------------------");
for (i = 0; i < r1; i++)
{
for (j = 0; j < c2; j++)
{
printf("%d\t ", c[i][j]);
}
printf("\n");
}
}
}
void main()
{
input();
}
Output
Enter the row for Matrix A: 2
Enter the column for Matrix A: 3
Enter the row for Matrix B: 3
Enter the column for Matrix B: 2
A Matrix
Enter the 0 and 0 value:1
Enter the 0 and 1 value:2
Enter the 0 and 2 value:3
Enter the 1 and 0 value:3
Enter the 1 and 1 value:2
Enter the 1 and 2 value:11
B Matrix
Enter the 0 and 0 value:4
Enter the 0 and 1 value:5
Enter the 1 and 0 value:7
Enter the 1 and 1 value:8
Enter the 2 and 0 value:9
Enter the 2 and 1 value:10
Resultant Matrix
45 51
125 141
run the above program one by one understand it then convert the final program into function as per your required,Thank you

Most of the program works, but my array isn't printing the way it should

My array isn't printing out all the data, just whatever was last inputted. The data should print something like this
For the student number, if not enough numbers are inputted, 0's are automaticaly put in.
/*
Name:
Date: 10/06/2016
Workshop 4
*/
#include <stdio.h>
int main(void)
{
int counter;
int marks [40];
float num_grades = 0;
int row = 1;
float sum = 0;
float average = 0;
int pass = 0;
int fail = 0;
float pass_sum = 0;
float fail_sum = 0;
float pass_average = 0;
float fail_average = 0;
float biggest = 0;
float smallest = 0;
//int grade[40];
int student_num[40];
printf(" ---=== IPC mark Analyser V2.0 ===---\n");
printf("Please enter the number of students(between 3 and 40): ");
scanf("%d", &counter);
while (counter >40 || counter <3)
{
printf("Invalid number, enter a number between 3 and 40 inclusive: ");
scanf("%d", &counter);
}
printf("Row Std No Mrk\n");
printf("--- --------- ---\n");
num_grades = counter;
while (counter > 0)
{
printf("%d ", row);
printf("_____________ ___\r%3d ", row);
scanf("%d", &student_num[40]);
scanf("%d", &marks[40]);
row++;
counter--;
sum += marks[40];
}
for (int i = 0; i < num_grades; i++)
{
printf("%03d %09d %3d\n", row, student_num[40], marks[40]);
}
average = sum / num_grades;
printf("-----------------\n");
printf("-----------------\n");
printf("Marks Entered, printing results:\n");
printf("Row Std No Mrk\n");
printf("--- --------- ---\n");
printf("The average of all marks in this group is %.1f.\n", average);
printf("Program Ended.\n");
return 0;
}
You're always reading/writing index 40 in the student_num and marks arrays, so everything goes to the same place.
Actually, the valid indexes of an array of size 40 are 0 to 39, so you're actually reading/writing off the end of the array, causing undefined behavior.
You need to use the proper index in each place. In the printing loop, use i. In the reading loop, use a variable that starts at 0 goes up to counter.
num_grades = counter;
for (int i = 0; i < num_grades; i++)
{
printf("%d ", i + 1);
printf("_____________ ___\r%3d ", i + 1);
scanf("%d", &student_num[i]);
scanf("%d", &marks[i]);
sum += marks[i];
}
for (int i = 0; i < num_grades; i++)
{
printf("%03d %09d %3d\n", row, student_num[i], marks[i]);
}

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