Hey, I got bored so was making this program and i know how to get the highest and lowest number but I was wondering if there was a even quicker way, or would :

if( number1 > number2 && number1 > number3)
    highNum = number1;
    
    else if( number2 > number1 && number2 > number3)
    highNum = number2;
    
    else if( number3 > number1 && number3 > number2)
    highNum = number3;
    
    if( number1 < number2 && number1 < number3)
    lowNum = number1;
    
    else if( number2 < number1 && number2 < number3)
    lowNum = number2;
    
    else if( number3 < number2 && number1 < number1)
    lowNum = number3;

put the numbers in an array

int array[3] = {3,1,5};
int largest = array[0];
int smallest = array[0];
for(int i = 1; i < 3; i++)
{
    if( array[i] > largest)
        largest = array[i];
    // now do similar for smallest
}

Potentially quicker, you can use the STL min and max template functions. It's definitely easier, but it gets tedious with more than a few numbers:

#include <iostream>
#include <algorithm>

int main()
{
  int a = 0;
  int b = 1;
  int c = 2;

  std::cout << "Low number: " << std::min(std::min(a, b), c) << '\n';
  std::cout << "High number: " << std::max(std::max(a, b), c) << '\n';
}

How about:

#include <algorithm>
#include <iostream>
using namespace std;

int main()
  {
  int numbers[] = { 12, -7, 42, 9 };

  cout << "largest  = " << max_element( numbers, numbers +4 ) << endl;
  cout << "smallest = " << min_element( numbers, numbers +4 ) << endl;
  }

using c++09 variadic templates http://www.osl.iu.edu/~dgregor/cpp/variadic-templates.pdf

#include <iostream>

template < typename T > T largest( T first, T second )
{  return first > second ? first : second ; }


template < typename T, typename... U > T largest( T first, U... rest )
{ return largest( first, largest( rest... ) ) ; }

int main()
{
   int n1=5, n2=7, n3=1 ; 
   std::cout << largest( n1, 4, n2 ) << '\n' ;
   std::cout << largest( n1, 78, 3, n2, 12, n3 ) << '\n' ;
}

// compile with: g++43 -Wall -std=c++0x -pedantic -Werror myfile.cc

Geek.

/me runs off to try out this super coolness.... :)

using c++09 variadic templates http://www.osl.iu.edu/~dgregor/cpp/variadic-templates.pdf

#include <iostream>

template < typename T > T largest( T first, T second )
{  return first > second ? first : second ; }


template < typename T, typename... U > T largest( T first, U... rest )
{ return largest( first, largest( rest... ) ) ; }

int main()
{
   int n1=5, n2=7, n3=1 ; 
   std::cout << largest( n1, 4, n2 ) << '\n' ;
   std::cout << largest( n1, 78, 3, n2, 12, n3 ) << '\n' ;
}

// compile with: g++43 -Wall -std=c++0x -pedantic -Werror myfile.cc

just amazing.... {i had no intention of spamming , but this code is awesome...}

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.