The purpose of this exercise is to use the twosubscript meth

The purpose of this exercise is to use the two-subscript method of dynamic memory allocation. Input for this program is a two-dimensional array of floating point data located in a file named testdata2. The input array will contain 3 rows of data with each row containing 5 columns of data. Thus, if the input values are: 4.33 5.33 1.11 99.00 100.00 1.0 33.3 12.5 1.1 -1000.00 22.1 11.9 2.4 8.3 8.9 Use malloc to create an array that holds pointers. Each element of that array points at another array, which is the row of data. Use malloc in a loop to create your rows. Then you can use two subscript operators [r][c] to get at your data in order to sum the elements in a row and calculate the average, and to sum the elements in a column and calculate the average. Your program should output: The average values for the three rows are: 41.95 -190.42 10.72 The average values for the five columns are: 9.14 16.84 5.34 36.13 -297.03 This program calls for hard-coded height and width of the two-dimensional array, known ahead of time (3 times 5). Instead of writing in the literal numbers in your code, create two global constant variables to hold those dimensions, and use those variables in your code.

Solution

#include<stdio.h>
#include<stdlib.h>
#define ROW 3
#define COL 5

int main(){
   //scaning data from file
   freopen(\"testdata2\",\"r\",stdin); //comment this line to read from user input console
  
   int i,j;
   float *data[ROW];
  
   for(i=0;i<ROW;i++){
       float *row = (float*) malloc(sizeof(float)*COL);      
       for(j=0;j<COL;j++){
           scanf(\"%f\", &row[j]);
       }
       data[i] = row;
   }  
  
   //average of rows
   printf(\"The average values for the three rows are: \");
   for(i=0;i<ROW;i++){
       float sum = 0;
       for(j=0;j<COL;j++){
           sum += data[i][j];
       }
       printf(\"%.2f \", sum/COL);
   }  
  
   //average of columns
   printf(\"\ The average values for the three columns are: \");
   for(i=0;i<COL;i++){
       float sum = 0;
       for(j=0;j<ROW;j++){
           sum += data[j][i];
       }
       printf(\"%.2f \", sum/ROW);
   }
}

 The purpose of this exercise is to use the two-subscript method of dynamic memory allocation. Input for this program is a two-dimensional array of floating poi

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site