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
// Area program: using area function that returns nothing
#include <iostream>
using namespace std;
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 
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
CODE
Output:
Enter length: 8
Enter width: 7
The area is 56
Press any key to continue . . .

Lines 4 to 8 are the function definition for the function area. Line 4 is the most important part of the function. This line tells the compiler that the function area does not return anything (void) and must receive 2 double values. The two values will be stored in the variables l and w. These are the parameters.

In line 15 we call function area and pass length and width. These values are called the arguments. The compiler will compare the parameters in line 4 with the arguments in the calling statements (line 15) to make sure that the function is called correctly.

NEXT: A function area with prototype