Lecture 11
Lecture 11
Structured Programming
Lecture 11– Functions
Functions
• A function is a set of statements designed to accomplish a particular task.
Experience has shown that the best way to develop and maintain a large
program is to construct it from smaller pieces or (modules).
At the point at which the function is called from within main, the control is lost by
main and passed to function sum. The value of both arguments passed in the call
(99 and 10) are copied to the local variables int a and int b within the function.
Function sum declares another local variable (int r), and by means of the
expression r=a+b, it assigns to r the result of a plus b. Because the actual
parameters passed for a and b are 99 and 10 respectively, the result is 109. The
following line of code: return (r);
Definition after main function (prototype)
• There is an alternative way to avoid writing the whole code of a
function before it can be used in main function. This can be achieved
by declaring just a prototype of the function before it is used, instead
of the entire definition.
• This declaration is shorter than the entire definition, but significant
enough for the compiler to determine its return type and the types of
its parameters.
• type name (type1 argument1, type2 argument2, ...);
• It is identical to a function definition, except that it does not include
the body of the function itself (i.e., the function statements that in
normal definitions are enclosed in braces { }) and instead of that we
end the prototype declaration with a semicolon (;).
Example 4 : Write a C++ program using function prototype to calculate
the average of two numbers entered by the user in the main program.