//Zachary Abdollahi CS1A Chapter 4, P. 224, #19
//
/*******************************************************************************
*
* CALCULATE SPEED OF SOUND IN GASES
*
*______________________________________________________________________________
* This program displays a menu of four gases. The user selects a gas and enters
* the time it took sound to travel through it. The program then calculates and
* displays the distance the sound traveled, using each gas's speed of sound.
*
* INPUT
* choice : Menu selection for the gas (1-4)
* seconds : Time in seconds for sound to travel (0-30)
*
* OUTPUT : Distance sound traveled, in meters
*
******************************************************************************/
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int choice; //INPUT - Menu selection for the gas (1-4)
double seconds; //INPUT - Time in seconds for the sound to travel
double speed; //Speed of sound for the selected gas
double distance; //OUTPUT - Distance sound traveled, in meters
// Display 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;
// Validate 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;
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;
}