I see a number of things that could help you improve your program.
Don't abuse using namespace std
Putting using namespace std
at the top of every program is a bad habit that you'd do well to avoid.
Fix the formatting
I don't know if the indentation problems are a cut-and-paste error or really how your code looks, but it should be fixed.
Avoid using C++ keywords as variable names
The keyword final
is being used here as a variable name. While that's technically not an error, it's not good practice. I'd suggest using some other name for that.
Simplify your code
The maxNumber
function is more complex than it needs to be. Here's an alternative that minimizes the number of comparisons made:
int maxNumber(int num1, int num2, int num3) {
if (num1 > num2) {
return num1 > num3 ? num1 : num3;
}
return num2 > num3 ? num2 : num3;
}
Omit return 0
When a C or C++ program reaches the end of main
the compiler will automatically generate code to return 0, so there is no need to put return 0;
explicitly at the end of main
.
Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments: "I didn't know that." or "That's bad advice!" My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard. For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:
[...] a return from the initial call to the main
function is equivalent to calling the exit
function with the value returned by the main
function as its argument; reaching the }
that terminates the main
function returns a value of 0.
For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:
If control reaches the end of main
without encountering a return
statement, the effect is that of executing return 0;
All versions of both standards since then (C99 and C++98) have maintained the same idea. We rely on automatically generated member functions in C++, and few people write explicit return;
statements at the end of a void
function. Reasons against omitting seem to boil down to "it looks weird". If, like me, you're curious about the rationale for the change to the C standard read this question. Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.
So I advocate omitting it; others disagree (often vehemently!) In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.
cout << std::max(a, std::max(b, c));
\$\endgroup\$std::max
with an initializer list does not. Other things: "no recursion version" is not needed at all. With literally any level of optimization, the exact same assembly is generated. My point was that it's not too much work to write an n-ary max function as long as you kind of understand how templates work; you don't need tons of metaprogramming ability. Creating a perfect function is usually unneeded. \$\endgroup\$