Skip to content

Instantly share code, notes, and snippets.

@not7cd
Last active May 30, 2018 13:39
Show Gist options
  • Save not7cd/2ab9439f7ca10872ca1549634d68da50 to your computer and use it in GitHub Desktop.
Save not7cd/2ab9439f7ca10872ca1549634d68da50 to your computer and use it in GitHub Desktop.
/* example10-3.c */
#include <stdlib.h>
#include <stdio.h>
/* https://www.eskimo.com/~scs/cclass/int/sx9b.html */
void print_matrix(float **M, int n, int m) {
int i,j;
for (i=0; i<n; i++)
{
for (j=0; j<m; j++)
{
printf(" %10.3f",M[i][j]);
}
printf("\n");
}
}
float** calloc_matrix(n, m) {
float **M = malloc(n * sizeof(float *));
if(M == NULL) return EXIT_FAILURE;
int i,j;
for (i=0; i<n; i++)
{
M[i] = calloc(m, sizeof(int));
if(M[i] == NULL) return EXIT_FAILURE;
}
return M;
}
void copy_to(float **A, float **B, int n, int m) {
int i,j;
for (i=0; i<n; i++)
for (j=0; j<m; j++)
A[i][j] = B[i][j];
}
void add_to(float **A, float **B, int n, int m) {
int i,j;
for (i=0; i<n; i++)
for (j=0; j<m; j++)
A[i][j] += B[i][j];
}
void subtract_to(float **A, float **B, int n, int m) {
int i,j;
for (i=0; i<n; i++)
for (j=0; j<m; j++)
A[i][j] -= B[i][j];
}
int main()
{
int n, m;
printf("Enter matrix dim: ");
scanf("%i %i", &n, &m);
float **A = calloc_matrix(n, m);
float **B = calloc_matrix(n, m);
float **C = calloc_matrix(n, m);
float **D = calloc_matrix(n, m);
int i,j;
for (i=0; i<n; i++)
{
for (j=0; j<m; j++)
{
printf("A[%d][%d]: ",i,j);
scanf("%f",&A[i][j]);
}
}
for (i=0; i<n; i++)
{
for (j=0; j<m; j++)
{
printf("B[%d][%d]: ",i,j);
scanf("%f",&B[i][j]);
}
}
copy_to(C, A, n, m);
add_to(C, B, n, m);
copy_to(D, A, n, m);
subtract_to(D, B, n, m);
printf("A:\n");
print_matrix(A, n, m);
printf("B:\n");
print_matrix(B, n, m);
printf("C:\n");
print_matrix(C, n, m);
printf("D:\n");
print_matrix(D, n, m);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment