Functions in C++
Functions in C++
Programming
Fundamentals
Functions
Lecture # 19
Wednesday, December 16, 2020
FALL 2020
FAST – NUCES, Faisalabad Campus
Rizwan Ul Haq
Objectives
2
Functions
Called modules
Like miniature programs
Can be put together to form a larger program
pow(x,y) calculates xy
pow(2, 3) = 8.0
Returns a value of type double
x and y are the parameters (or arguments)
This function has two parameters
sqrt(x) calculates the nonnegative square root of x,
for x >= 0.0
sqrt(2.25) is 1.5
Type double
x = -15 ; //Line 8
cout << "Line 9: Absolute value of " << x
<< " = " << abs(x) << endl; //Line 9
return 0;
}
CS118 - FALL 2020
User-Defined Functions
14
return number;
}
Definition includes
return type: Data type of the value the function returns to
the part of the program that called it
name: Name of the function. Function names follow same
rules as variable names
parameter list: Variables that hold the values passed to the
function
body: Statements that perform the function’s task
Can be zero
parameter
From the heading of the function pow, it follows that the formal
parameters of pow are base and exponent. Consider the following
statements:
double u = 2.5;
double v = 3.0;
double x, y;
x = pow(u, v); //Line1
y = pow(2.0, 3.2) + 5.1; //Line2
cout << u << " to the power of 7 = " << pow(u, 7) << endl; //Line3
return number;
}
if (isValid(score)) // call
…
CS118 - FALL 2020
Function Prototypes
38
1 4 9 16 25 36 49 64 81 100