Using the struct Part definition from the lecture, declare a variable called myP
ID: 3874665 • Letter: U
Question
Using the struct Part definition from the lecture, declare a variable called myPart of that data type. Initialize all field values appropriately (the actual values are your choice).
Write a line of code that doubles the cost field of the myPart variable.
Write two lines of code that get the cost field of the myPart variable from the user using fgets() and sscanf(). You do not have to prompt the user.
Using the struct Part definition from the lecture, declare an array variable called myParts, containing 45 struct Parts.
Write a line of code that doubles the cost field of element #5 of the myParts variable (that is, the element with 5 between the square brackets).
Write two lines of code that get the cost field of element #5 of the myParts variable from the user using fgets() and sscanf(). You do not have to prompt the userstruct Part
{
char partNumber[8];
char name[20];
double cost;
};
Explanation / Answer
program:-- for one variable (one structure)
#include <stdio.h>
//declare structure
struct Part
{
char partNumber[8];
char name[20];
double cost;
};
int main ()
{
struct Part mypart={"1014110","x540la",25000.0}; //one structure with initilize
char buffer[30]="40000.0"; //buffer for sscanf
char readcost[10]={0}; //temp verable for fgets
mypart.cost=mypart.cost*2; //double the cost of structure variable
printf("%lf ",mypart.cost); //print cost of structure variable
fgets(readcost, sizeof(mypart.cost),stdin); //using fgets
mypart.cost=atoi(readcost); //convert char to int
printf("%lf ",mypart.cost); //print cost of structure variable
sscanf (buffer,"%lf",&mypart.cost); //using sscanf
printf ("%lf ",mypart.cost); //print cost of structure variable
return 0;
}
output:--
50000.000000
15000
15000.000000
40000.000000
Process exited normally.
Press any key to continue . . .
program:-- for 45 variables (array of 45 structures)
#include <stdio.h>
//declare structure
struct Part
{
char partNumber[8];
char name[20];
double cost;
};
int main ()
{
struct Part myparts[45]={0}; //45 array of structures
char buffer[30]="30000.0"; //buffer for sscanf
char readcost[10]={0}; //temp verable for fgets
myparts[5].cost=myparts[5].cost*2; //cost of 5th structure variable
printf("%lf ",myparts[5].cost); //print cost of 5th structure variable
fgets(readcost, sizeof(myparts[5].cost),stdin); //using fgets
myparts[5].cost=atoi(readcost); //convert char to int
printf("%lf ",myparts[5].cost); //print cost of 5th structure variable
sscanf (buffer,"%lf",&myparts[5].cost); //using sscanf
printf ("%lf ",myparts[5].cost); //print cost of 5th structure variable
return 0;
}
output:--
0.000000
25000
25000.000000
30000.000000
Process exited normally.
Press any key to continue . . .
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.