How to get variable with biggest value

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.
Last edited on
//using c++ container
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <algorithm>
#include<vector>
using namespace std;

int main(){
vector<int> v1{3,8,9,7};
cout<<*max_element(v1.begin(),v1.end());
return 0;
}


//but if you want to know about implementation of max find algo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

using namespace std;

int main(){

int v1[]={7,8,9,6,15,8};
int max_no=0;
for(auto i:v1){
    if(i>max_no){
        max_no=i;
    }

}
cout<<max_no;
return 0;
}
Thanks for the detailed explanation.
int max_no=0;

dont initialize to 0; initialize to first element. max_no= v1[0];
because, all numbers could be negative!
Love the help on this one, information overload.
I just have one more question.

vector<int> v1{3,8,9,7};

int v1[]={7,8,9,6,15,8};

What is numbers {3,8,9,7} and {7,8,9,6,15,8} for? Why did you choose these ones?

Yes, Im pretty "noob".
Last edited on
you need to read array link is http://en.cppreference.com/w/cpp/language/array.

int v1[]={7,8,9,6,15,8};

input of array.

to know vector click http://www.cplusplus.com/reference/vector/vector/vector/
vector<int> v1{3,8,9,7};
Topic archived. No new replies allowed.