1. Write a C program to find the frequency of even numbers in matrix using functions & dynamic memory allocation.
2. Write a C program to find the trace of (sum of diagonal element) matrix using
functions & dynamic memory allocation.
//Question 1
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
//Implement function Input Matrix
void InpMat(int** mat, int rows, int cols)//
{
printf("Please enter elements matrix:\n");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
scanf("%i", &mat[i][j]);
}
}
//Implement function Out matrix
void OutMat(int** mat, int rows, int cols)//
{
printf("===============================================================\n");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
printf("%3d", mat[i][j]);
printf("\n");
}
}
//Function CntEven which return frequency even numbers
int CntEven(int** mat, int rows, int cols)
{
int ans = 0;//count even numbers
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
if (mat[i][j] % 2 == 0)
ans++;
}
return ans;
}
int main()
{
//Alloc dynamic memory
int rows, cols;
printf("Please enter rows and columns of matrix:\n");
scanf("%i%i", &rows, &cols);
int** mat = (int**)malloc(sizeof(int*) * (size_t)rows);//size_t=unsigned int
for (int i = 0; i < rows; i++)
mat[i] = (int*)malloc(sizeof(int) * (size_t)cols);
InpMat(mat, rows, cols);
int frEven = CntEven(mat, rows, cols);
printf("Frequency of even numbers: %i", frEven);
free(mat);
return 0;
}
//Question 2
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
//Implement function Input Matrix
void InpMat(int** mat, int n)//n-size of matrix
{
printf("Please enter elements matrix:\n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
scanf("%i", &mat[i][j]);
}
}
//Function findTrace
long long findTrace(int** mat, int n)
{
long long sum = 0;
for (int i = 0; i < n; i++)
sum += (int)mat[i][i];
return sum;
}
int main()
{
//Alloc dynamic memory
int n;
printf("Please enter size:\n");
scanf("%i", &n);
int** mat = (int**)malloc(sizeof(int*) * (size_t)n);//size_t=unsigned int
for (int i = 0; i < n; i++)
mat[i] = (int*)malloc(sizeof(int) * (size_t)n);
InpMat(mat,n);
long long sum = findTrace(mat, n);
printf("Trace: %lld\n", sum);
free(mat);
return 0;
}
Comments
Thanks a lot !!
Leave a comment