Method adding two numbers

Method programming with C++ is a way to save time when you need to redo same/similar code, and also it allows for clearer code because when you read the code you can tell what is happening instead of just having the same code over and over again within the main method of the program.

To declare a method within c++ there is syntax for the way that a method is defined.

[return type] methodname(parameters if required...)

So for example if you want to pass in two integer variables and then to return a integer variable (the function could add the parameters together so shall we call it addTwoNumbers,

int addTwoNumbers(int value1, int value2);

this means that the return value is a int (integer), you “call” the method by its name (addTwoNumbers) and pass in local variables to the method in the parameters (value1 and value2).

Here is a full c++ code example that will read in two values from the keyboard and output the result to the screen.

#include <iostream>
#include <exception>
#include <stdio.h>
 
//using the namespace std (standard) for the cin -> console input
using namespace std;       
 
int addTwoNumbers(int val1, int val2)
{
    return (val1 + val2);
}
 
int main()
{
       // setup the defaul values.
       int val1 =0, val2 =0;
       try 
       {
              // output to the console
              printf("Please enter number 1 : ");
              // read in the input, if not a integer value, this will
              // cause a error 
              cin >> val1;       
              printf("Please enter number 2 : ");
              cin >> val2;
       }
       catch (exception& e)
       {
              // write out any error exception
              printf("Not a valid input %s\n", e.what());
       }
       // output the answer of the two inputted values.
       printf("Answer : %d\n", addTwoNumbers(val1, val2));
       return 0;
}

and here is the output

Please enter number 1 : 20
Please enter number 2 : 10
Answer : 30

Leave a Reply

Your email address will not be published. Required fields are marked *