// Chapter 4 - Programming Challenge #19
// The Speed of Sound in Gases
// This program allows the user to select a gas and enter
// the amount of time sound traveled through that gas.
// It then calculates and displays the distance the sound
// traveled in meters.
#include <iostream>
using namespace std;
int main()
{
// Constants for the speed of sound in each gas
const double CARBON_DIOXIDE = 258.0;
const double AIR = 331.5;
const double HELIUM = 972.0;
const double HYDROGEN = 1270.0;
// Variables for the user's choice, time, speed, and distance
int choice;
double time, speed, distance;
// Display the gas menu
cout << "Select a gas:" << endl;
cout << "1. Carbon Dioxide" << endl;
cout << "2. Air" << endl;
cout << "3. Helium" << endl;
cout << "4. Hydrogen" << endl;
cout << "Enter your choice: ";
cin >> choice;
// Check that the user entered a valid menu choice
if (choice < 1 || choice > 4)
{
cout << "Invalid choice." << endl;
return 0;
}
// Get the travel time from the user
cout << "Enter the time in seconds: ";
cin >> time;
// Check that the time is between 0 and 30 seconds
if (time < 0 || time > 30)
{
cout << "Invalid time." << endl;
return 0;
}
// Determine the speed of sound for the selected gas
switch (choice)
{
case 1:
speed = CARBON_DIOXIDE;
break;
case 2:
speed = AIR;
break;
case 3:
speed = HELIUM;
break;
case 4:
speed = HYDROGEN;
break;
}
// Calculate the distance traveled
distance = speed * time;
// Display the calculated distance
cout << "The sound traveled " << distance
<< " meters." << endl;
return 0;
}