Module 3 CSC 201
Module 3 CSC 201
Objectives
By the end of this module, you will
understand:
Function main and other functions
reference
Variable Scope: local, global or static
Overloading functions
MODULE –4: Functions
A simple Example:
void displayInfo()
{
cout << ”\nPls Enter Your Input Value\n”);
cout << ”Note That Your Input is”;
cout << ”within the range 0 – 24 :”;
}
Explanation on the typical function
header
displayInfo():
This is the name you chose to give the function,
followed by a pair of empty brackets, meaning the
function receives no value or parameter. Note, we can
send information or value into a function. This
information is or are some values a function will use to
perform its task. Also, the type of data(eg. int, double)
should also be stated.
After declaration and definition, you get a function to
perform its task by calling the function. To call, use its
name followed by empty brackets when there is no
parameter to pass and a semicolon. e.g.
displayInfo();
Explanation on the typical function
calculatePerimeter(breadth, height);”
calculatePerimeter(double b, double h)
//this function fills in the content of the array t; the change is permanent
void readT(double tmp[] ) // note that tmp is a formal parameter receiving
from t
{
for (int i = 0; I < 7; ++i)
{
cout <<“Enter Temperature for day: ”<<( i+1) << endl;
cin >> tmp[i];
}
}
void readT(double tmp[] );//function prototype
int main()
{
double t [ ] ;
t = readT( );// this function fills the array and return it as object
displayT(t);//this displays the content of the array pass
}
double [ ] readT( ) // [ ] after double means this is an array
{
double tmp [7];
for (inti = 0; i<7; ++i)
{
cout<<“Enter Temperature for day: ”<<( i+1);
cin>>tmp[i];
}
return tmp; //only the name is needed to return the array
}
4.6 Scope of a variable:
Local Variables
The variables declared within the function body and in
the function header line input list belonging to that
function.
Visible and usable by the members of that function
Also called automatic variable
Fig.4.6: A program illustrating local and global variables.
Global Variables
Here, only this function sees total. Every time it is called, it remembers the
value and keeps adding it to the previous total.
TUTOR MARKED ASSESSMENT (TMA)
Reusability
Information hiding
Reducing complexity
Summarized rules for making a
function:
3. Write a program having five methods, such that one of the functions is the main where
others are called. Your main is to receive an input value n from the user and send to
other functions where necessary. Let the program implement the following:
a)Create a detectPrime function to test if the input received is prime or not
b)Create a detectOdd function to test is the input is odd number
c)Create a factorial function to compute the factorial value of the input
d)Create a summation function to compute 1 + 2 + 3 + … + n.
Note: Use a switch statement to select which function to call at a point in time