Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C program to find amount of volume passed through a tunnel
In C programming, we can solve problems involving conditional volume calculations using structures and functions. This program determines which boxes can pass through a tunnel based on height restrictions and calculates their volumes.
Syntax
struct Box {
int length, width, height;
};
int volume(struct Box box);
int canPass(struct Box box, int tunnelHeight);
Problem Description
Given a tunnel with height 41 and unlimited width, we need to find the total volume of boxes that can pass through it. A box can pass if its height is strictly less than the tunnel height. The volume is calculated as length × width × height.
Example
Here's a complete program that solves the tunnel volume problem −
#include <stdio.h>
#define TUNNEL_HEIGHT 41
#define N 4
struct Box {
int length, width, height;
};
int volume(struct Box box) {
return box.length * box.width * box.height;
}
int canPassTunnel(struct Box box) {
return box.height < TUNNEL_HEIGHT;
}
void calculatePassableVolumes(struct Box boxes[]) {
printf("Volumes of boxes that can pass through the tunnel:<br>");
for (int i = 0; i < N; i++) {
if (canPassTunnel(boxes[i])) {
printf("Box %d: %d<br>", i + 1, volume(boxes[i]));
}
}
}
int main() {
struct Box boxes[N] = {
{9, 5, 20}, /* height 20 < 41, can pass */
{3, 7, 15}, /* height 15 < 41, can pass */
{8, 15, 41}, /* height 41 = 41, cannot pass */
{6, 3, 42} /* height 42 > 41, cannot pass */
};
printf("Tunnel height: %d<br>", TUNNEL_HEIGHT);
printf("Number of boxes: %d<br><br>", N);
calculatePassableVolumes(boxes);
return 0;
}
Tunnel height: 41 Number of boxes: 4 Volumes of boxes that can pass through the tunnel: Box 1: 900 Box 2: 315
How It Works
- The
struct Boxstores dimensions of each box -
volume()function calculates length × width × height -
canPassTunnel()checks if box height is strictly less than tunnel height - Only boxes with height < 41 can pass through the tunnel
- Box 1: height 20, volume = 9 × 5 × 20 = 900
- Box 2: height 15, volume = 3 × 7 × 15 = 315
- Box 3: height 41 (equal to tunnel), cannot pass
- Box 4: height 42 (greater than tunnel), cannot pass
Key Points
- Use structures to organize related data (box dimensions)
- Separate logic into functions for better code organization
- The condition is strictly less than (<), not less than or equal to
- Volume calculation requires all three dimensions
Conclusion
This program demonstrates how to use structures and conditional logic to solve real-world problems. By organizing box data in structures and using functions for calculations, we create clean, readable code that efficiently determines which boxes can pass through a tunnel based on height restrictions.
