### Find the largest of 3 numbers - using a function.

I have the following code which gets the largest value of 3 inputed values:

 ``12345678910111213141516171819202122`` `````` #include using namespace std; int main() { float n1, n2, n3; cout << "Enter three numbers: "; cin >> n1 >> n2 >> n3; if(n1 >= n2 && n1 >= n3) { cout << "Largest number: " << n1; } if(n2 >= n1 && n2 >= n3) { cout << "Largest number: " << n2; } if(n3 >= n1 && n3 >= n2) { cout << "Largest number: " << n3; } return 0; } ``````

I want to be able to use a separate function here to get the largest number, e.g. with the header:

 `` `` ``int largest(int n1, int n2, int n3)``

How would I go about using this method and calling the function in main()?

Thank you.
Last edited on
I recommend taking a look at http://www.cplusplus.com/doc/tutorial/functions/

Let's look at `int largest(int n1, int n2, int n3)` part by part. The first word `int` simply means that the function will return an integer. `largest` is the name of the function. This is what you will use to call it in main. The `int` before each parameter specifies what the type of that parameter should be, in this case all integers. To use the function in main you use it's name and give it the right parameters then store the value in a variable or output it directly: `int biggestNum = largest(45, 987, -29999);`

P.S. To use largest in main, you must define the function before you define main. Or just put `int largest(int, int, int);` and then write the definition later.
Another hint:

The following two programs are equivalent in output:
 ``123456789`` ``````// Example program #include int main() { int a = 3; int b = 2; std::cout << "Sum: " << a + b << '\n'; }``````

 ``12345678910111213141516`` ``````// Example program #include int sum(int a, int b); int main() { int a = 3; int b = 2; std::cout << "Sum: " << sum(a, b) << '\n'; } int sum(int a, int b) { return a + b; }``````

Last edited on
Assuming the code works as is, you simply move things around a bit.

 ``1234567891011121314151617181920212223242526272829303132`` `````` #include using namespace std; int largest( int n1, int n2, int n3); // a forward declaration of the function int main() { float n1, n2, n3; cout << "Enter three numbers: "; cin >> n1 >> n2 >> n3; cout << "Largest number: " << largest( n1, n2, n3 ); return 0; } int largest( int n1, int n2, int n3) { if(n1 >= n2 && n1 >= n3) { return n1; } if(n2 >= n1 && n2 >= n3) { return n2; } // if(n3 >= n1 && n3 >= n2) // what else is possible now? Anything? { return n3; } }``````

This is not a study of your method (other than a question about the third test), just an example of how to turn a block of code into a function

Thank you guys.
Registered users can post here. Sign in or register to post.