3. Write a C program with the following functions:die: like program #1, you can
ID: 3845083 • Letter: 3
Question
3. Write a C program with the following functions:die: like program #1, you can just copy that die function into this program.
show: a void function with 2 args: an array of doubles, which show doesn't change, and the
number of elements in the array. show's job is to output the array values, separated by commas,without a comma before the first element or after the last element. e.g. 3, 5, -17, 0, 8show may assume without checking that the array has at least one element.
square: this function returns a pointer to a dynamically allocated array.
It has 2 args: an array of doubles (which square doesn't change)
an unsigned that is the number of elements in the array. square may assume without
checking that the number of elements is greater than 0.
square's job is to dynamically allocate an array of doubles that is parallel to the arg array (and sohas the same number of elements). As usual, if the allocation fails, c&d. square sets each elementof the DA array to the square of the corresponding element in the arg array.For example, if the arg array held {1.5, 2, 3, 4}, then the DA array would hold {2.25, 4, 9, 16}.square does no I/O.
main: create an array of doubles and somehow get values into it.
call show to display that arraycall square to get a DA array of squared valuescall show to display that arraydeallocate the DA array
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
//show elements in array
void show(double a[], int N){
//if there is only one element in array
if(N==1){
printf("%lf", a[0]);
return;
}
//If more than one element in array
int i;
for(i=0;i<N-1;i++){
printf("%lf, ", a[i]);
}
printf("%lf", a[N-1]);
}
//allocate array and assigns squares of given array in allocated array
double* square(double a[], int N){
double *sqrs;
sqrs = (double*) malloc(N*sizeof(double));
int i;
for(i=0;i<N-1;i++){
sqrs[i] = a[i]*a[i];
}
return sqrs;
}
int main()
{
double arr[10] = {1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0};
show(arr,10);
printf(" ");
double * sqr;
sqr = square(arr,10);
show(sqr,10);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.