Let’s now take a step back and discuss why we would want to use structures. Look at an example of a program that uses bottle data without structures.
char bottleName1[] = "Medium Bottle"; int maxCapacity1 = 24; int currentCapcity1 = 0; char bottleName2[] = "Large Bottle"; int maxCapacity2 = 48; int currentCapcity2 = 20;
Notice that we need to keep track of six variables while working with this bottle data. As we increase the number of bottles, the number of variables would increase by 3 per bottle. This approach can get extremely unmaintainable.
In a small number of situations, we could possibly use arrays. But that’s only when the data is the same type, so this isn’t useful all the time.
struct Bottle { char* name; int maxCapacity; int currentCapacity; }; struct Bottle bottle1 = {"Medium Bottle", 24, 0}; struct Bottle bottle2 = {"Large Bottle", 48, 20};
Using a struct to encapsulate all the members that represent a Bottle
we can:
- Reduce complexity by representing a set of data with one variable
- Package different, but logically similar, data together
- Better represent real-world “things” into data types
Being able to represent data using structures is extremely beneficial as you continue working on more complex real-world problems.
Instructions
Someone has been working with a group of variables that represent coffee table data. Use structs to organize this data.
Above the main()
function:
- Create a
Table
structure - Define the following variables inside the structure,
length
,width
,height
andcolor[20]
Now initialize the data using the defined structure.
Inside the main()
function:
- Initialize the
table1
using theTable
struct and the first set of table data - Initialize the
table2
using theTable
struct and the second set of table data