C++ Tutorial for beginners – Functions

Basics of C++ | Variables | If statements | Loops | Functions

 

 

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

#include <iostream.h>

 

int sumof(int numberone, int numbertwo);

int main()

{

            int firstnum, secondnum;

            cout << "Enter a number: ";

            cin >> firstnum;

            cout << "Enter another number: ";

            cin >> secondnum;

            cout << sumof(firstnum, secondnum) << endl;

            return 0;

}

 

int sumof(int numberone, int numbertwo)

{

            int sumis;

            sumis = numberone + numbertwo;

            return sumis;

}

This will ask for a number and then ask you for another number and then it will go to sumof and add them togother

 

 

3

int sumof(int numberone, int numbertwo);

 

You have to do this because if you don’t then if you try and call it then it will not be able to find it. Notice how this has a semi-colon after it and the actual function doesn’t.

 

11

cout << sumof(firstnum, secondnum) << endl;

 

First of all what this does is calls sumof() and because sumof() has int numberone and int numbertwo we need to pass numbers through, so in this case we will pass through firstnum and secondnum. When it has done that it will print on the screen what the value of sumof() is.

 

15

int sumof(int numberone, int numbertwo)

 

This is the start of the new function. It is just like the main() function except to get this one to work you have to call to it