8 Example 1 reads two marices from the user and add them includestdioh define

# 8 example 1 reads two marices from the user and add

This preview shows page 8 - 12 out of 12 pages.

8 Example 1 /*reads two marices from the user and add them */ #include<stdio.h> #define ROWS 10 #define COLS 10 int main (void) { int i, j, a[ROWS][COLS], b[ROWS][COLS], c[ROWS][COLS] = {0}, rows, cols; printf("Enter number of rows for Matrix 1: "); scanf("%d", &rows); printf("Enter number of columns for Matrix 1: "); scanf("%d", &cols); printf("Enter the %d elements of Matrix 1 row-wise: \n", rows * cols); for(i=0; i<rows; i++) { // reading matrix a for(j=0; j<cols; j++) scanf("%d", &a[i][j]); } printf("Enter the %d elements of Matrix 2 row wise: \n", rows * cols); for(i=0; i<rows; i++) { // reading matrix b for(j=0; j<cols; j++) scanf("%d", &b[i][j]); } 9 Example 1 … /* Addition of two matrices */ for(i=0; i<rows; i++) { for(j=0; j<cols; j++) c[i][j]=a[i][j] + b[i][j]; } /*Print sum of two matrices */ printf("The sum of two matrices is: \n"); for(i=0; i<rows; i++) { for (j=0; j<cols; j++) printf("%5d ", c[i][j]); printf("\n"); } system("pause"); return 0; } 10 2-D Arrays as parameters to functions As with 1-D arrays, it is possible to declare functions that take 2-D array as parameter. However, one problem here is that in declaring the prototype of the function, we must specify at least the number of columns of the array, thus making the function less flexible. One solution to this problem is to use a constant defining the maximum number of columns and use additional parameter to receive the actual size of the array: void print_2d_array(int a[][COLS], int rows, int cols); While this solution makes the function a little more flexible, it is not a perfect solution since the function is not self-contained – it depends on the pre-processor constant COLS. Calling functions that take 2-D array as argument is same as calling functions that take 1-D array. Just give the name of the array with no brackets. 11 Example 2 #include <stdio.h> #define ROWS 10 #define COLS 10 void read_2d_array(int [][COLS], int rows, int cols);  #### You've reached the end of your free preview.

Want to read all 12 pages?

• Spring '10
• baleh
• Array, #include, #define, The Elements, actual size, 2-d array
• • •  