Programming Fundamentals: Practical#07)
Programming Fundamentals: Practical#07)
in
C++
(PRACTICAL#07)
Objective: To become familiar with Functions in C++
A function is a subprogram or part of a program that is called many
times throughout the main program.
functions by themselves.
Creating User-Defined Functions in C++
In order to create a user-defined function in C++ you need to
provide:
Three main components of a function
Function Declaration
Function Definition
Function Calling
Creating User-Defined Functions in C++
Function Declaration : are also called Function prototype.
Examples
There
are two ways to define/ use functions in a program. First
approach is to declare the function before it is called.
Thesecond approach is to eliminate the function declaration
and place the function definition before the first call to the
function.
Advantages :
The most important reason to use functions is to aid in the conceptual
organization of a program.
The function’s code is stored in only one place in memory, even though the
function is executed many times in the course of the program.
functions save memory space b/c all calls to the function cause the same code
to be executed.
Passing arguments to functions
OR arguments are the values that are passed from the calling
program/code to the function.
Arguments
Arguments :
An argument is an input to the function,
Values passed from the calling program to the function are called
arguments.
Example sum(5, 10); Function call
Passing arguments to functions
Declaring a function with a Parameter
Arguments :
An argument is an input to the function,
Values passed form the calling program to the function are called
arguments.
Example sum(5, 10); Function call
In pass by reference the function can access the original variable in the
calling program.
Overloaded Functions
Task#3 Write a function called swap() that interchanges two int values
passed to it by the calling program.