Functions

The program asks the user to enter the length and width. A function is called to print the area.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Area program: using area function that returns nothing
#include <iostream>
using namespace std;
void area(double,double); // receives length & width, prints area
int main(){ 
  double length, width;
  cout<<"Enter length: ";
  cin>>length;
  cout<<"Enter width: ";
  cin>>width;
  area(length, width); // calls function area
  system("Pause");
  return 0;
} // main
void area(double l, double w) { // print the area given l and w
  double a;
  a=l*w;
  cout<<"The area is "<<a<<"\n";
} // area 
CODE
Output:

The number of parameters in a function must match the number of arguments in the calling statement. For example, if a function is supposed to receive one integer, and the calling statement is passing two doubles, the compiler will know that it is an error.

The compiler compares the functions parameters to the values that you are passing to it (the arguments) to see if it is called correctly.

If we change the calling statement to just area(length); the compiler will indicate that there is an error. error

NEXT: