c code for dynamic square matrix

  • cmatrix
  • write a c program for dynamic square matrix

    Let A be nXn square dynamic matrix. WAP by using appropriate user-defined functions for the following: a) Find the number of nonzero elements in A b) Find the sum of the elements above the leading diagonal. c) Display the elements below the minor diagonal. d) Find the product of the diagonal elements.

    Code

    #include <stdio.h> #include <stdlib.h> #include <time.h> void setvalue(int **arr, int r, int c) { int n; for (int i = 0; i < r; i++) { printf("enter the values for row %d\n", i + 1); for (int j = 0; j < c; j++) { printf("enter the element\n"); scanf("%d", (*(arr + i) + j)); } } } void display(int **arr, int r, int c) { printf("\n"); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { printf("%d ", *(*(arr + i) + j)); } printf("\n"); } } void non_zero(int **arr, int r, int c) { // counting int k = 0, count = 0; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (*(*(arr + i) + j) != 0) { count++; } } } // storing int nz[count]; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (*(*(arr + i) + j) != 0) { nz[k] = *(*(arr + i) + j); k++; } } } printf("number of non_zero elements are %d \n", count); for (int j = 0; j < count; j++) { printf("%d ", nz[j]); } printf("\n"); } void sum__of_elements_above_leading_diagonal(int **arr, int r, int c) { int sum = 0; for (int i = 0; i < r; i++) { int k = 1; for (int j = i + k; j < c; j++) { sum += *(*(arr + i) + j); } k++; } printf("The sum of elements above leading diagonal is %d", sum); } void display_below_minor(int **arr, int r, int c) { int k = c; for (int i = 0; i < r; i++) { for (int j = 0; j < k; j++) { printf("\t"); } for (int j = k; j < c; j++) { printf("%d\t", *(*(arr + i) + j)); } k--; printf("\n"); } } void product_diagonal(int **arr, int r, int c) { int prd = 1, j; for (int i = 0; i < r; i++) { j = i; prd *= *(*(arr + i) + j); } printf("The product of elements diagonal is %d", prd); } int main() { clock_t t; t = clock(); int r, c; printf("enter the number of rows followed by coulum\n"); scanf("%d%d", &r, &c); // dynamic initialization int **arr = (int **)malloc(r * sizeof(int *)); for (int i = 0; i < r; i++) { arr[i] = (int *)malloc(c * sizeof(int)); } // functions setvalue(arr, r, c); printf("\n"); display(arr, r, c); printf("\n"); non_zero(arr, r, c); printf("\n"); sum__of_elements_above_leading_diagonal(arr, r, c); printf("\n"); display_below_minor(arr, r, c); printf("\n"); product_diagonal(arr, r, c); t = clock() - t; double time_taken = ((double)t) / CLOCKS_PER_SEC; printf("\nfun() took %f seconds to execute \n", time_taken); return 0; }