CSCI 159: exam practice sample solutions (Mar 22/23 questions)

Question 1: struct definitions

(i) Write the declaration for a struct datatype, ItemData, with three fields:
Sample answer:
struct ItemData {
   char iname[80];
   float iprice;
   int iquantity;
};
(ii) In a main routine, write code to declare a variable of type ItemData and set its field contents to "Fancy Widget", 19.99, and 314.
(Suggestion: strcpy(str, "blah blah blah") can be used to copy a text string into a char array.)
Sample answer:
int main()
{
   ItemData fw;
   strcpy(fw.iname, "Fancy Widget");
   fw.iprice = 19.99;
   fw.iquantity= 314;
}

Question 2: Arrays of structs

Write a function that takes two parameters: an array of ItemData elements and the array size, and for each item in the array displays the item name and the value of the in-stock items (i.e. that item's price times its quantity).
Sample answer:
void displayItems(ItemData items[], int size)
{
   for (int i = 0; i < size; i++) {
       float value = items[i].iprice * items[i].iquantity;
       cout << "Item: " << items[i].iname;
       cout << " has total stock value $" << value << endl;
   }
}