SCHOOL OF CODE BUILDERS
Learn To CODE. Become A DEVELOPER.
Pages
HOME
DATA STRUCTURES
STRINGS
ARRAYS
MATRIX
BINARY TREES
LINKED LIST
STACK
QUEUE
SORTING
SEARCHING
C
PYTHON
PSEUDOCODE
CONTEST PROBLEMS
ALGORITHMS
PATTERNS
PHP
C PUZZLES
C INTERVIEW QUESTIONS
JAVA
C++
HASHING
RECURSION
BASIC C PROGRAMS
TCS-CODEVITA
FACEBOOK
CONTACT US
Print square of each element of r x c matrix
Print square of each element of r x c matrix
Implementation:
Input:
1 2
3 4
Output:
1 4
9 16
/* getting the input from the user */ #include <stdio.h> #include <stdlib.h> #define r 2 //change the size of the row here #define c 2 //change the size of the column here int main(void) { int a[r][c]; int i,j; printf("enter the matrix elements:\n"); /* get the input 2-D (r x c) matrix from the user */ for(i=0;i<r;i++) { for(j=0;j<c;j++) { scanf("%d",&a[i][j]); } } /* making each element as its own square value */ for(i=0;i<r;i++) { for(j=0;j<c;j++) { a[i][j]=a[i][j]*a[i][j]; } } /* printing the result to the user */ for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("%d ",a[i][j]); } printf("\n"); } return 0; }
/* static initialization of the input array */ #include <stdio.h> #include <stdlib.h> #define r 2 #define c 2 int main(void) { /* give the input array while writing the code (static initialization) */ int a[r][c]={{1,2}, {3,4}}; int i,j; /* making each element as its own square value */ for(i=0;i<r;i++) { for(j=0;j<c;j++) { a[i][j]=a[i][j]*a[i][j]; } } /* printing the result to the user */ for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("%d ",a[i][j]); } printf("\n"); } return 0; }
/* 2-D array using pointers of 1-D array to 1-D array of elements & memory allocation using malloc() for 2-D array */ #include <stdio.h> #include <stdlib.h> #define r 2 #define c 2 int main(void) { /* give the input array while writing the code (static initialization) */ int *a[r]; int i,j; /* memory allocation for 2-D array using malloc() function */ for(i=0;i<r;i++) *(a+i)=(int*)malloc(sizeof(int)*c); /* get the input array elements from the user */ for(i=0;i<r;i++) { for(j=0;j<c;j++) { scanf("%d",(*(a+i)+j)); //same as that of &a[i][j] } } /* making each element as its own square value */ for(i=0;i<r;i++) { for(j=0;j<c;j++) { a[i][j]=a[i][j]*a[i][j]; } } /* printing the result to the user */ for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("%d ",a[i][j]); } printf("\n"); } return 0; }
PREVIOUS
NEXT
HOME