Hey. I'm just started learning programming and c++ language. But I have a question... For example I have 3 variables. How to get variable with biggest value?
EXAMPLE :
1 2 3 4 5 6 7 8 9 10 11 12 13
int main ()
{
int var, var1, var2;
var=1;
var1=1;
var2=2'
if(how to get variable (or variables) with biggest value??)
{
cout << "Biggest variable: "<< endl;
}
return 0;
}
Hi, the easiest thing would be to organize your variables in an array that you can scan with a simple for loop. Anyway it is not necessary... You can imagine the process like a mini tournament: you take the first two variables and determine (with a simple if) which one has the biggest value. Then you take this "semifinal winner" and you compare it to the third variable to determine the "final winner".
Note: this approach does not scale well at all! Imagine having 10 variables or even much more, like 1000. How many if-clauses should you write? A lot! Instead, if you put all of your values in an array, then you can determine the maximum with a very simple algorithm:
- you initialize a max variable to the first value of the array
- you scan the whole array with a for loop
- you compare each value with the one stored in max
- if you find a value which is bigger than max, then you replace it
- when you have finished your cycle, you have your max value
And note that this approach has the same complexity for any number of variables.