| Functions are used to define a block of code, unlike the loops we discussed earlier, functions can be called from any place in your program so that you do not have to repeat the same code over and over again. Here is a basic function at work: |
#include
using namespace std;
int addNumbers( int a, int b){
return a+b;
}
int main(){
int a; int b;
cout << "Enter a number: "; cin >> a;
cout << "Enter an other number: "; cin >> b;
cout << "Sum of the two numbers is: " << addNumbers( a, b) << "\n";
system("pause");
return 0;
}
|
| Here we create a function called addNumbers, which returns an integer. main() collects the data from the user and then sends it to addNumbers(), notice how I declared the integers in both main() and addNumbers. This is because the ones in main() are local variables which cannot be touched by other functions. The parameters for addNumbers() does not have to be the same as the variables containing the values being sent to addNumbers(). Once addNumbers() is called, it takes the values given to it by main() and returns the sum of them to the function that called it, which in this case is main(). Also notice how addNumbers() goes before main(). If you flip them around it will error out. If a function is being called by a function that apears before it in your source file, it must be declared at before it is called. Here is an example of this: |
#include
using namespace std;
int addNumbers( int a, int b);
int main(){
int a; int b;
cout << "Enter a number: "; cin >> a;
cout << "Enter an other number: "; cin >> b;
cout << "Sum of the two numbers is: " << addNumbers( a, b);
system("pause");
return 0;
}
int addNumbers( int a, int b){
return a+b;
}
|