Define a structure (struct) named Product that contains the following members: A
ID: 3693814 • Letter: D
Question
Define a structure (struct) named Product that contains the following members: A c-string for product name An integer for product code. A float for product cost. Create a dynamic array of Product that can be resized on demand. The initial size of the array (SIZE) is determined by the user input. Fill in the array with SIZE number of products. The program allows the use to append additional n (input) products to the array. Show the content of the array and the average cost before and after appending products. Note, you need to define the following functions to perform input, output and finding average cost. InputProduct: The function inputs the name, code, and the cost of each product I the array you create. OutputProduct: The function outputs the name, code, and the cost of each product in array you create AverageCost: The function finds the average cost of the products stored in the array you create. The following is a sample run:Explanation / Answer
#include <stdio.h>
#include<stdlib.h>
struct Products {
char name[100];
int pcode;
float pcost;
} *pdt;
void InputProduct(int start,int size,struct Products *pdt)
{
int i;
for(i=start;i<size;i++)
{
scanf("%s %d %f ",(pdt[i]).name,&(pdt[i]).pcode,&(pdt[i]).pcost);
}
}
void OutputProduct(int start,int size,struct Products *pdt)
{
int i;
for(i=start;i<size;i++)
{
printf("%s %d %f ",(pdt[i]).name,(pdt[i]).pcode,(pdt[i]).pcost);
}
}
float AverageCost(int start,int size,struct Products *pdt)
{
int i;
float avgcost=0;
for(i=start;i<size;i++)
{
avgcost=avgcost+(pdt[i]).pcost;
}
return avgcost;
}
int main() {
int size,i,ch,newsize;
float avgcost=0;
scanf("%d ",&size);
pdt=(struct Products *)malloc(size*(sizeof(struct Products)));
InputProduct(0,size,pdt);
printf("The details before appending are ");
OutputProduct(0,size,pdt);
avgcost=AverageCost(0,size,pdt);
printf("The average cost before appending is %f ",avgcost/size);
printf("Do you want to append details? 0 or 1 ");
scanf("%d ",&ch);
if(ch==1)
{
printf("Enter the final size of the array after appending some details ");
scanf("%d ",&newsize);
pdt=(struct Products *)realloc(pdt, newsize);
InputProduct(size,newsize,pdt);
size=newsize;
printf("The details after appending are ");
OutputProduct(0,size,pdt);
avgcost=AverageCost(0,size,pdt);
printf("The average cost after appending is %f ",avgcost/size);
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.