Summary: This C program defines a box
structure and calculates the volume of boxes whose height is less than a defined maximum. It demonstrates structures, typedefs, dynamic memory allocation, and filtering logic.
#include <stdio.h>
#include <stdlib.h>
#define MAX_HEIGHT 41
struct box
{
/**
* Define three fields of type int: length, width and height
*/
int length;
int width;
int height;
};
typedef struct box box;
int get_volume(box b) {
/**
* Return the volume of the box
*/
return b.length * b.width * b.height;
}
int is_lower_than_max_height(box b) {
/**
* Return 1 if the box's height is lower than MAX_HEIGHT and 0 otherwise
*/
return b.height < MAX_HEIGHT;
}
int main()
{
int n;
scanf("%d", &n);
box *boxes = malloc(n * sizeof(box));
for (int i = 0; i < n; i++) {
scanf("%d%d%d", &boxes[i].length, &boxes[i].width, &boxes[i].height);
}
for (int i = 0; i < n; i++) {
if (is_lower_than_max_height(boxes[i])) {
printf("%d\n", get_volume(boxes[i]));
}
}
return 0;
}
Structure Definition:
The program defines a struct box
with length
, width
, and height
fields to represent a box's dimensions.
Typedef:
The typedef
keyword creates an alias box
for struct box
to simplify future references.
Function - get_volume()
:
Returns the volume of a box using the formula length × width × height
.
Function - is_lower_than_max_height()
:
Returns 1 (true) if the height of the box is less than the defined MAX_HEIGHT
; otherwise returns 0 (false).
Dynamic Memory Allocation:
Memory is dynamically allocated for an array of n
boxes using malloc
.
Input and Processing:
The user inputs dimensions for each box. The program then checks if each box’s height is under the maximum and prints its volume if it is.
Looping and Conditionals:
Two loops are used — one for reading input and another for evaluating each box against the height condition and printing the volume.