"Q. Write a C++ program that asks the user to enter the name and time for 5 athletes, then prints the name and time of the winner. All times are measured in minutes. The winner has the lowest time."
I got the answer already on my own, using "while" loops as this question was supposed to be solved that way.
But the big question is.. whats the logic of this code. I really don't know how it worked. Like how's it possible for "if" statement to compare "time" with "minimum" which is not associated with any value. Nevertheless, the code is 100% correct, and again I just want to understand how it works. Thank you.
You're partially right that minimum isn't associated with any value at the beginning. It is associated with a value, but we have no idea what it is, because you've declared 'minimum' and used it without instantiating it. Your program happens to work by luck that the initial value of 'minimum' is not less than the actual minimum time the user inputs.
You need to initialize minimum in some way before you use it. Something like this before entering your loop is safe assuming the user inputs valid data.
1 2
cin>>name>>time;
minimum = time;
minimum = INT_MAX; is another way to initialize. It will set 'minimum' to the maximum possible value allowed by 'int'. This will almost always be safe. You have to #include <climits> to use this.
You should probably not be using 'int' for the time. Times will often be decimals. You should use a floating point data type.
You're ignoring the name of the winner. You need a separate variable to keep track of the winner as well, or you can bind the winners name to his time:
#include<iostream>
#include<string>
usingnamespace std;
int main()
{
float time, minimum;
int count=0;
string name, ch;
cout<<"Enter the name and time: \n";
cin>>name>>time;
minimum=time;
ch=name;
while(count<4)
{
if(time<minimum)
{
minimum=time;
ch=name;
}
cout<<"Enter the name and time: \n";
cin>>name>>time;
if(time<minimum)
{
minimum=time;
ch=name;
}
count++;
}
if(count != 0)
cout<<"winner is: "<<ch<<" with a score of: "<<minimum<<" minutes";
else
cout<<"No winner";
return 0;
}
I know this code can be executed in an easier way, for instance, using the way you suggested: "minimum = INT_MAX;". But I'm trying to solve the code within the material we're going to be examined with which is limited to the while loop and if statement.
#include<iostream>
#include<string>
usingnamespace std;
int main()
{
int time, count=0, minimum;
string name, ch;
cout<<"Enter the name and time: \n";
cin>>name>>time;
minimum=time;
ch=name;
while(count<4)
{
cout<<"Enter the name and time: \n";
cin>>name>>time;
if(time<minimum)
{
minimum=time;
ch=name;
}
count++;
}
cout<<"winner is: "<<ch<<" with a score of: "<<minimum<<" minutes";
return 0;
}