Matrix

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

#include <stdio.

h>

// Function to initialize the matrix with user input


void initializeMatrix(int matrix[3][3]) {
printf("Enter the elements of the matrix (3x3):\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &matrix[i][j]);
}
}
}

// Function to display the matrix


void displayMatrix(int matrix[3][3]) {
printf("Matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}

// Function to calculate and display the sum of each row


void sumOfRows(int matrix[3][3]) {
printf("Sum of each row:\n");
for (int i = 0; i < 3; i++) {
int rowSum = 0;
for (int j = 0; j < 3; j++) {
rowSum += matrix[i][j];
}
printf("Row %d: %d\n", i + 1, rowSum);
}
}

// Function to calculate and display the sum of each column


void sumOfColumns(int matrix[3][3]) {
printf("Sum of each column:\n");
for (int j = 0; j < 3; j++) {
int colSum = 0;
for (int i = 0; i < 3; i++) {
colSum += matrix[i][j];
}
printf("Column %d: %d\n", j + 1, colSum);
}
}

// Function to find and display the maximum element in the matrix


void findMaxElement(int matrix[3][3]) {
int maxElement = matrix[0][0];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (matrix[i][j] > maxElement) {
maxElement = matrix[i][j];
}
}
}
printf("Maximum element in the matrix: %d\n", maxElement);
}
// Function to transpose the matrix and display the result
void transposeMatrix(int matrix[3][3]) {
printf("Transposed Matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[j][i]);
}
printf("\n");
}
}

int main() {
int matrix[3][3];

// Initialize the matrix with user input


initializeMatrix(matrix);

// Display the original matrix


displayMatrix(matrix);

// Calculate and display the sum of each row


sumOfRows(matrix);

// Calculate and display the sum of each column


sumOfColumns(matrix);

// Find and display the maximum element in the matrix


findMaxElement(matrix);

// Transpose the matrix and display the result


transposeMatrix(matrix);

return 0;
}

You might also like