Again, I appeal to my active audience to correct me :)
Last time we had some code which, given an array of square sizes, calculated the corresponding areas. It was preceded by some code to set up the sizes, and followed by some code to print out the result, but it looked something like:
However, what if we had rectangles instead of squares? Would we have two separate arrays, one for widths and one for heights? We clearly need to store that much data. However, storing them in two separate arrays leads to the risk of them getting out of sync (say, switching the order of two elements, but forgetting to do it in one of the arrays). What it is possible to do instead is invent a new data type, rect[1], which contains two numbers. It would look something like this:
Last time we had some code which, given an array of square sizes, calculated the corresponding areas. It was preceded by some code to set up the sizes, and followed by some code to print out the result, but it looked something like:
for (int i=0;i<4;++i) { squares_area[i] = squares_size[i] * squares_size[i], }
However, what if we had rectangles instead of squares? Would we have two separate arrays, one for widths and one for heights? We clearly need to store that much data. However, storing them in two separate arrays leads to the risk of them getting out of sync (say, switching the order of two elements, but forgetting to do it in one of the arrays). What it is possible to do instead is invent a new data type, rect[1], which contains two numbers. It would look something like this:
( Read more... )struct rect { int width; int height; }; int main() { rect rect_array[4] = { {4,5}, {6,2}, {3,9}, {5,5} }; int cumulative_total_area = 0; for (int i=0;i<4;++i) { cumulative_total_area += rect_array[i].width * rect_array[i].height; } // Pretend there's some code here to print the result }