Untitled
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> /* Take a 2D array and perform the following : 1. CreateArray function to allocate space for the 2d array by passing the row and col size 2. Accept function to read the input from user 3. Display function to preint the elements in the array 4. Calculate sum function to print the total sum 5. Row-wise-sum to print the sum of each row 6. MinMax function to print the min and max elt in the array 7. Transpose function to transpose the array and print the elements */ int** createArray(int** a1, int row_size, int col_size) { int** a = (int ** )malloc( (row_size*col_size) * sizeof(int ) ); return a; } void Accept(int** a, int row_size, int col_size) { for(int i=0;i<row_size;i++) { a[i] = (int*) malloc(col_size*sizeof(int)); for(int j=0;j<col_size;j++) { //input from the user scanf("%d", &a[i][j]); } } } void Display(int** a, int row_size, int col_size) { printf("The elements are : \n"); for(int i=0;i<row_size;i++) { for(int j=0;j<col_size;j++) { printf("%d ", a[i][j]); } } } int calculateSum(int** a, int row_size, int col_size ) { int sum = 0; for(int i=0;i<row_size;i++) { for(int j=0;j<col_size;j++) { sum = sum + a[i][j]; } } printf("\nSum of all elements : %d\n", sum); } void MinMax(int** a, int row_size, int col_size ) { int min = a[0][0]; int max = 0; for(int i=0;i<row_size;i++) { for(int j=0;j<col_size;j++) { if(min > a[i][j]) { min = a[i][j]; } if(max < a[i][j]) { max = a[i][j]; } } } printf("Min elt : %d, Max elt : %d\n", min, max); } void FindElement(int** a, int row_size, int col_size ) { int elt = 3; //a flag value to check if given elt is present bool elt_found = false; for(int i=0;i<row_size;i++) { for(int j=0;j<col_size;j++) { if(a[i][j] == elt) { //if found set flag to true printf("Found at index : %d\n", i); elt_found = true; break; } } } //if elt is not found if(!elt_found) { printf("Given element is not present\n"); } } void FindRowSum(int** a, int row_size, int col_size ) { int row_sum = 0; for(int i=0;i<row_size;i++) { for(int j=0;j<col_size;j++) { //find sum of elts in each row row_sum = row_sum + a[i][j]; } printf("Sum of row %d is %d\n", i, row_sum); //set sum = 0 row_sum = 0; } } void Transpose(int** a, int row_size, int col_size ) { int** arr = (int ** )malloc( (row_size*col_size) * sizeof(int ) ); for(int i=0;i<row_size;i++) { arr[i] = (int*) malloc(col_size*sizeof(int)); for(int j=0;j<col_size;j++) { arr[i][j] = a[j][i]; } } printf("Array after the transpose\n"); for(int i=0;i<row_size;i++) { for(int j=0;j<col_size;j++) { printf("%d ",arr[i][j]); } } } int main() { int row_size, col_size; scanf("%d",&row_size); scanf("%d",&col_size); int** a; createArray(a,row_size, col_size); Accept(a,row_size, col_size); Display(a,row_size, col_size); calculateSum(a,row_size, col_size); MinMax(a,row_size, col_size); FindElement(a,row_size, col_size); FindRowSum(a,row_size, col_size); Transpose(a,row_size, col_size); }
Leave a Comment