C Online Compiler
Example: Matrix Addition using Functions in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Matrix Addition using Functions #include <stdio.h> // Function to add two matrices and store the result in a third matrix // Note: For simplicity, matrices are assumed to have a maximum size of 10x10. // In real-world scenarios, dynamic memory allocation or VLAs might be used. void addMatrices(int mat1[10][10], int mat2[10][10], int result[10][10], int rows, int cols) { // Step 1: Iterate through each row of the matrices for (int i = 0; i < rows; i++) { // Step 2: Iterate through each column in the current row for (int j = 0; j < cols; j++) { // Step 3: Add corresponding elements from mat1 and mat2 // Store the sum in the result matrix at the same position result[i][j] = mat1[i][j] + mat2[i][j]; } } } // Function to display a matrix void displayMatrix(int matrix[10][10], int rows, int cols) { // Step 1: Print a header for the matrix printf("Matrix:\n"); // Step 2: Iterate through each row to print its elements for (int i = 0; i < rows; i++) { // Step 3: Iterate through each column to print the element for (int j = 0; j < cols; j++) { // Print the element followed by a tab for spacing printf("%d\t", matrix[i][j]); } // Move to the next line after printing all elements in a row printf("\n"); } } int main() { // Step 1: Declare variables for matrix dimensions and the matrices themselves int rows, cols; int matrix1[10][10], matrix2[10][10], sumMatrix[10][10]; // Assuming max 10x10 // Step 2: Get dimensions from the user printf("Enter number of rows (max 10): "); scanf("%d", &rows); printf("Enter number of columns (max 10): "); scanf("%d", &cols); // Basic validation for dimensions if (rows <= 0 || rows > 10 || cols <= 0 || cols > 10) { printf("Invalid dimensions. Please enter rows/cols between 1 and 10.\n"); return 1; // Indicate an error } // Step 3: Get elements of the first matrix from the user printf("Enter elements of the first matrix:\n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("Enter element a%d%d: ", i + 1, j + 1); scanf("%d", &matrix1[i][j]); } } // Step 4: Get elements of the second matrix from the user printf("Enter elements of the second matrix:\n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("Enter element b%d%d: ", i + 1, j + 1); scanf("%d", &matrix2[i][j]); } } // Step 5: Display the input matrices for verification printf("\n--- Input Matrices ---\n"); printf("First "); displayMatrix(matrix1, rows, cols); printf("\nSecond "); displayMatrix(matrix2, rows, cols); // Step 6: Call the addMatrices function to perform the addition addMatrices(matrix1, matrix2, sumMatrix, rows, cols); // Step 7: Display the resulting sum matrix printf("\n--- Result ---\n"); printf("Sum of the two matrices:\n"); displayMatrix(sumMatrix, rows, cols); return 0; // Indicate successful execution }
Output
Clear
ADVERTISEMENTS