//Cameron Pham CS1A Chapter 4, P. 224, #19
//
/*******************************************************************************
*
* Calculate the Speed of Sound in Gases
*
*______________________________________________________________________________
* This program displays a menu of four gases. A gas is selected and the program
* accepts a value for the time it took for sound to travel through it. The
* program then calculates the distance the sound traveled.
*
* INPUT
* Choice of gas
* Time in seconds
*
* OUTPUT
* Distance the sound traveled
*
******************************************************************************/
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int choice; //INPUT - Menu selection for 1-4 gases
float seconds; //INPUT - Time in seconds for the sound to travel
float speed; //Speed of sound for the selected gas
float distance; //OUTPUT - Distance sound traveled in meters
// Display the menu
cout << "Speed of Sound Calculator" << endl;
cout << "1. Carbon Dioxide" << endl;
cout << "2. Air" << endl;
cout << "3. Helium" << endl;
cout << "4. Hydrogen" << endl;
cout << "Enter your choice: ";
cin >> choice;
cout << endl;
// Validate the menu choice
while (cin.fail() || choice < 1 || choice > 4)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid choice. Please enter a number 1-4: ";
cin >> choice;
}
// Assign speed based on menu choice using a switch statement
switch (choice)
{
case 1:
speed = 258.0;
break;
case 2:
speed = 331.5;
break;
case 3:
speed = 972.0;
break;
case 4:
speed = 1270.0;
break;
}
// Get and validate the number of seconds
cout << "Enter the number of seconds: ";
cin >> seconds;
cout << endl;
while (cin.fail() || seconds < 0 || seconds > 30)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid time. Please enter a value between 0 and 30 seconds: ";
cin >> seconds;
}
// Calculate and display the distance
distance = speed * seconds;
cout << "The sound source was " << distance << " meters away." << endl;
return 0;
}