How to Compare 2 Integers in a Function Using C++

How to Compare 2 Integers in a Function Using C++ thumbnail
Let your computer compare integer values.

One of the useful features of the C++ language is its ability to use functions. A function is a piece of code that performs a specific calculation and returns the result to the main program. Collections of these functions can be stored in libraries and turned into header files. Functions stored in these files can be called by simply issuing the "#include" directive at the beginning of a program's source file, eliminating the need to rewrite a common function each time it is needed in a different program. Comparing the value of two integers is a common operation that can be coded in a simple function, added to a header file and used in any number of programs.

Instructions

    • 1

      Declare the function and the type of data it returns:

      int numberCompare()

      {

    • 2

      Declare the variables the function accepts:

      int FirstNumber;

      int SecondNumber;

    • 3

      Ask the user to input two values to assign to the declared variables:

      cout << "Enter the two integers you wish to compare: ";

    • 4

      Get the user's input and assign values to the variables:

      cin >> FirstNumber >> SecondNumber;

    • 5

      Use a collection of "if" statements to test the integers and output the results:

      if (FirstNumber == SecondNumber)

      cout << FirstNumber " is equal to " <<SecondNumber << endl;

      if (FirstNumber != SecondNumber)

      cout <<"These numbers are not equal" << endl;

      if (FirstNumber < SecondNumber)

      cout << SecondNumber " is larger than "FirstNumber << endl;

      if (FirstNumber > SecondNumber)

      cout <<FirstNumber " is larger than "SecondNumber << endl;

    • 6

      Close the function and return to the calling program:

      return 0;

      }

Tips & Warnings

  • The comparison operators in C++ are: == equal to; != not equal; < less than; > greater than; <= less than or equal to; >= greater than or equal to.

Related Searches:
  • Photo Credit Goodshoot/Goodshoot/Getty Images

Comments

Related Ads

Featured