patterncppMinor
Counting trains by type code
Viewed 0 times
typecodetrainscounting
Problem
A train operator has decided to hire an observer to track the
different types of trains transiting at a major train platform in
Europe. Write a program, using a for loop, to track the different
train types at the major train station.
The different types of trains are shown in the following table:
The program should ask the user to enter five sets of train codes.
The program should then count the number of train codes entered and
display the statistics.
Sample run
Sample output
Can you please check whether this code is correct, and maybe make it shorter?
`#include
using namespace std;
int main()
{
int train;
int InterCity = 0;
int Regional = 0;
int Overnight = 0;
cout > train;
if (train == 23)
{
InterCity++;
}
else if (train == 51)
{
Regional++;
}
else if (train == 72)
{
Overnight++;
}
}
cout
different types of trains transiting at a major train platform in
Europe. Write a program, using a for loop, to track the different
train types at the major train station.
The different types of trains are shown in the following table:
Train types | Train code
Inter-city | 23
Regional | 51
Overnight | 72
The program should ask the user to enter five sets of train codes.
The program should then count the number of train codes entered and
display the statistics.
Sample run
Enter train type #1: 23
Enter train type #2: 23
Enter train type #3: 51
Enter train type #4: 72
Enter train type #5: 23
Sample output
Statistics:
3 Inter-city trains
1 Regional train
1 Overnight train
Can you please check whether this code is correct, and maybe make it shorter?
`#include
using namespace std;
int main()
{
int train;
int InterCity = 0;
int Regional = 0;
int Overnight = 0;
cout > train;
if (train == 23)
{
InterCity++;
}
else if (train == 51)
{
Regional++;
}
else if (train == 72)
{
Overnight++;
}
}
cout
Solution
Use a
switch statement. Add a default condition to show the error message when the entered train type is not matched with any specified train type.switch (train) {
case 23: InterCity++; break;
case 51: Regional++; break;
case 72: Overnight++; break;
default: // TODO: error handling
}Code Snippets
switch (train) {
case 23: InterCity++; break;
case 51: Regional++; break;
case 72: Overnight++; break;
default: // TODO: error handling
}Context
StackExchange Code Review Q#98304, answer score: 4
Revisions (0)
No revisions yet.