Functions


Text of video

The program asks the user to enter a number, and then a function is used to find half of the number.

Compare the two programs below. The first puts the function definiton before main. The second one uses a function prototype before main, and the function definition after main.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/Function half
#include<iostream>
using namespace std;
double half(double a) {
  return a/ 2;
}
int main()
{
  double num;
  cout << "Enter a number:";
  cin >> num;
  cout << half(num) << endl;;
  system("pause");
  return 0;
} //main
CODE
Output:
Enter a number:17
8.5
Press any key to continue . . .
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/Function half
#include<iostream>
using namespace std;
double half(double a);
int main()
{
  double num;
  cout << "Enter a number:";
  cin >> num;
  cout << half(num) << endl;;
  system("pause");
  return 0;
} //main
double half(double a) {
  return a/ 2;
}
CODE
Output:
Enter a number:17
8.5
Press any key to continue . . .

* The function prototype does not need to give names to the variables.

* We would not really write a function called half. It is much simpler to just use num/2.

NEXT: A function to print area