Question

In: Computer Science

C language · Pointers · Dynamic memory allocation · Functions · Arrays (dynamically allocated) ​ PROBLEM:...

C language

· Pointers · Dynamic memory allocation · Functions · Arrays (dynamically allocated) ​

PROBLEM:  The user of your program will use it to do some elementary calculations for an unknown number of simple data sets. The data in each set consists of a number of floating point values, but the number of
the values to be entered will be input by the user, so you do not know in advance how many values there will be in each data set. Therefore, you cannot use a static array in C to store these numbers, because a statically declared array has a fixed size, which cannot be changed after the program begins running.

First, you should prompt the user to enter the number of data sets. The user will enter an integer greater than 1 to indicate the number of data sets.

You should then prompt the user to enter the number of floating point values in each data set (which the user will enter as an integer greater than 0), followed by the floating point values themselves on the same line (newline will follow the last floating point value on the line). Your program needs to read the user input, and store the floating point values in each data set in a dynamically allocated array of the appropriate size.

After getting the values in each data set, your program should repeatedly do the following two things:

 Select the data set to do operations on by number, with the following prompt:

Enter the number of the data set on which you wish to do calculations:


The user will enter an integer value, followed by newline, in response to this prompt (the user will enter 1 for the first data set, 2 for the second, etc.), and based on the value entered, your program must be able to access the values in the appropriate data set in the dynamically allocated storage which you have created, and then do what is described immediately below.

 Your program should then prompt the user to choose one of the following options for a calculation based on the data set chosen by the user (ask the user to enter one of the six numbers, followed by enter):

1. Find the minimum value.

2. Find the maximum value.

3. Calculate the sum of all the values.

4. Calculate the average of all the values.

5. Print the values in the data set.

6. Exit the program.

After the user selects one of these six options, your program should do the necessary calculation or printing of the data based on the user's choice (or terminate the program), and output the result with an appropriate message, for example:

The maximum value in the data set is: 569.45
The results for options 1, 2, 3, and 4 should be printed out as floating point values with 2 digits of precision, and the result for option 5 should be to output the values in the data set in the order in which they were input, with two digits of precision for each value, and with any two values separated by a tab (\t).

Sample Data Set Input (This does not include user responses to the prompts to select a data set or to select an operation to perform)

6

3.45 2.37 85.32 34.5 569.45 335.2 193.4 74.39

6 23.45 32.37 185.32 364.5 179.4

144.39 7 35.45 121.47 42.32 44.5

249.75 385.9 113.4 4 44.45 567.37 311.32

22.45 2.37 85.32 34.5 569.45

335.2 193.4 74.39 122.45 413.2 89.32

2

1

3

2

4

3

5

4

6

5

6

Solutions

Expert Solution

test2DArrays.c

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

/*
* function to calculate sum of 1-D array
*/
float calculateSum(float * arr, int n) {
int i=0;
float sum = 0;
for(i=0; i<n; i++) {
sum += arr[i];
}
return sum;
}

/*
* function to calculate average of 1-D array
*/
float calculateAvg(float * arr, int n) {
float sum = calculateSum(arr, n);
return sum/n;
}

/*
* function to calculate max of 1-D array
*/
float calculateMax(float * arr, int n) {
int i=0;
float max = arr[0];
for(i=1; i<n; i++) {
max = (max > arr[i]) ? max: arr[i];
}
return max;
}

/*
* function to calculate min of 1-D array
*/
float calculateMin(float * arr, int n) {
float min = arr[0];
int i=0;
for(i=1; i<n; i++) {
min = (min < arr[i]) ? min: arr[i];
}
return min;
}


/*
* Driver program
*/
int main()
{
int noOfDatasets;
printf("Enter no of datasets: ");
  
// scan no of datasets
scanf("%d", &noOfDatasets);
  
// declaring 2-D array reference pointer.
float ** array;
  
// counters
int i=0;
int j=0;
  
// allocaing memory for outer array
// they will be equal to no of datasets
array = malloc(noOfDatasets * sizeof(float *));
  
// keeping length of individual dataset
int lengths[noOfDatasets];
  
// to flush the new line from scanf
int c;
while ((c = getchar()) != '\n' && c != EOF);
  
// read individual dataset values from user
printf("Enter dataset values (One dataset values on one line seperated by single space)\n");
for(i=0; i< noOfDatasets; i++) {
lengths[i] = 0;
char dataSetValues[1000];
memcpy(dataSetValues, "", 1000);
  
// read the whole string
fgets(dataSetValues,1000,stdin);
if(dataSetValues == NULL)
break;
  
// creating a copy
char* copiedDataSetValues = calloc(strlen(dataSetValues)+1, sizeof(char));
strcpy(copiedDataSetValues, dataSetValues);
  
int noOfWords = 0;
  
// find no of values in dataset
char* token;
for (token = strtok(dataSetValues," "); token; token = strtok(NULL, " ")) {
noOfWords++;
}
  
// store individual values
if(noOfWords != 0) {
// allocate memory for this dataset
array[i] = malloc(noOfWords * sizeof(float));
lengths[i] = noOfWords;
  
// using tokenize with space, as values are sepearted with space
int count = 0;
for (token = strtok(copiedDataSetValues," "); token; token = strtok(NULL, " "))
{
array[i][count++] = atof(token);
}
}
  
// freeing the memory for copied string
free(copiedDataSetValues);
}
  
// prompt user for option
int selectedDataset = 0, option=0;
  
printf("Enter the number of the data set on which you wish to do calculations:");
scanf("%d", &selectedDataset);
  
printf("Select from below:\n");
printf("1. Find the minimum value.\n");
printf("2. Find the maximum value.\n");
printf("3. Calculate the sum of all the values.\n");
printf("4. Calculate the average of all the values.\n");
printf("5. Print the values in the data set.\n");
printf("6. Exit the program.\n");
  
scanf("%d", &option);
  
switch(option) {
case 1:
printf("The minimum of dataset is: %.2f", calculateMin(array[selectedDataset - 1], lengths[selectedDataset - 1]));
break;
case 2:
printf("The maximum value of dataset is: %.2f", calculateMax(array[selectedDataset - 1], lengths[selectedDataset - 1]));
break;
case 3:
printf("The sum of value of dataset is: %.2f", calculateSum(array[selectedDataset - 1], lengths[selectedDataset - 1]));
break;
case 4:   
printf("The average of value of dataset is: %.2f", calculateAvg(array[selectedDataset - 1], lengths[selectedDataset - 1]));
break;
case 5:
printf("Printing values\n");
for(i=0; i<lengths[selectedDataset - 1]; i++) {
printf("%.2f ", array[selectedDataset - 1][i]);
}
break;
case 6:
printf("Exiting the program.");
}
  
  
// freeing memory which has been allocated for array
for(i=0; i< noOfDatasets; i++) {
free(array[i]);
}
}

Sample output:


Related Solutions

Write a C++ program (using pointers and dynamic memory allocation only) to implement the following functions...
Write a C++ program (using pointers and dynamic memory allocation only) to implement the following functions and call it from the main function. (1)Write a function whose signature looks like (char*, char) which returns true if the 1st parameter cstring contains the 2nd parameter char, or false otherwise. (2)Create an array of Planets. Populate the array and print the contents of the array using the pointer notation instead of the subscripts.
Purpose Review and reinforcement of pointers, dynamic memory allocation, pointer arithmetic, passing pointers to a function,...
Purpose Review and reinforcement of pointers, dynamic memory allocation, pointer arithmetic, passing pointers to a function, returning a pointer by a function, dangling pointer, and memory deallocation, pointer initialization, and struct data type. Project description In this project, you will create a database of employees of an organization while meeting the requirements described below. Your program MUST NOT interact with the user to receive inputs, so that the instructor and/or the teaching assistant can save a big time in testing...
Prime Sum C program !! Dynamically allocated memory Let P(n) denote the sum of the first...
Prime Sum C program !! Dynamically allocated memory Let P(n) denote the sum of the first n prime numbers. For example, P(1) = 2 and P(3) = 10, since the first three prime numbers are 2, 3 and 5, respectively. Write a program to determine the value of the function P(n) for different values of n. The first few prime sums are 2, 5, 10, 17, 28, 41, 58 and 77. Input The first line of the input file contains...
Please write code for C language Problem: Write a couple of functions to process arrays. Note...
Please write code for C language Problem: Write a couple of functions to process arrays. Note that from the description of the function you have to identify what would be the return type and what would be part of the parameter. display(): The function takes an int array and it’s size and prints the data in the array. sumArray(): It takes an int array and size, and returns the sum of the elements of the array. findMax(): It takes an...
C++ programming test 2, chapters 6,7,& 9 on Functions, Arrays, & Pointers 1. Create a one...
C++ programming test 2, chapters 6,7,& 9 on Functions, Arrays, & Pointers 1. Create a one dimensional array, Ages, which will hold 4 ages. Each age is an int.        b. Write a for loop and print, in reverse order the 4 values stored in memory assuming that the ages in the previous question have already been entered with a space between each value. Use subscript notation.                                     short cnt; c. Do the same as above, but use pointer...
The concept of pointers in C++ is inherited from the C language, which relies extensively on the use of pointers.
  Topic: The concept of pointers in C++ is inherited from the C language, which relies extensively on the use of pointers. What are the advantages and disadvantages of having the functionality of pointers in a programming language?
Constructors/Destructors - Initialize your data. Allocate memory if using a dynamically allocated array. The destructor should...
Constructors/Destructors - Initialize your data. Allocate memory if using a dynamically allocated array. The destructor should deallocate the memory. The constructor should take a single int variable to determine the size. If no size is specified (default constructor), then the size should be set to 50. operator[](size_t) - This should return the location with the matching index. For example if given an index of 3, you should return the location at index 3 in the list. Location class/struct - This...
malloc() searches the recently de-allocated memory objects to satisfy incoming memory allocation request. Explain the rationale...
malloc() searches the recently de-allocated memory objects to satisfy incoming memory allocation request. Explain the rationale of this design.
Using C++ Use dynamic allocation and functions (using pointer variables only) to read the names from...
Using C++ Use dynamic allocation and functions (using pointer variables only) to read the names from the .txt file and sort the names in lexical order Grumpy Dopey Doc Happy Bashful Sneezy Sleepy
When it comes to dynamic memory allocation and delete[] pointer, what does it mean to say...
When it comes to dynamic memory allocation and delete[] pointer, what does it mean to say that, CRT detected that the application wrote to memory after end of heap buffer? I tried to duplicate the error by deleting the pointer address twice and it didn't produce the same error code so that's not it. What might cause this problem?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT