I used a function to find the max between 2 numbers, what should i add to find max among 3 numbers???? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

I used a function to find the max between 2 numbers, what should i add to find max among 3 numbers????

#include <iostream> using namespace std; int maxNumber(int x,int y){ int max; if(x>y) max=x; else max=y; return max; } int main(){ int a;int b; cin>>a>>b; cout<<a<<b<<" "<<endl; cout<<"the max number btw a & b is::"<<maxNumber(a,b)<<endl; }

31st Jul 2017, 7:54 PM
RiGeL
RiGeL - avatar
2 Answers
+ 4
One way of doing it would be to add a nested if statement: int maxNumber(int x, int y, int z) { int max; if (x > y) { if (x > z) { max = x; } else { max = z; } } else { if (y > z) { max = y; else { max = z; } } return max; } However something like this becomes really inefficient and complicated when you have more inputs. Another way could be to put them into an array and use an algorithm to sort the array into ascending order.
31st Jul 2017, 8:04 PM
Shane
+ 2
Just call maxNumber(x, maxNumber(y, z)).
31st Jul 2017, 11:19 PM
Denis Felipe
Denis Felipe - avatar