0% found this document useful (0 votes)
2 views37 pages

Chapter2 Function[1]

Chapter 2 focuses on functions in programming, teaching students how to create structured programs using functions, understand variable scope, and utilize both library and user-defined functions. It explains the importance of functions for code modularity, reusability, and ease of debugging, while also covering the types of functions and the various ways to pass data to them. Additionally, the chapter distinguishes between global and local variables, and outlines the significance of parameters in function calls.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views37 pages

Chapter2 Function[1]

Chapter 2 focuses on functions in programming, teaching students how to create structured programs using functions, understand variable scope, and utilize both library and user-defined functions. It explains the importance of functions for code modularity, reusability, and ease of debugging, while also covering the types of functions and the various ways to pass data to them. Additionally, the chapter distinguishes between global and local variables, and outlines the significance of parameters in function calls.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

CHAPTER 2

FUNCTIONS (Part 1)
Chapter’s Outcome
At the end of this chapter, student should be able to:
a) Learn how to build structured programs that are divided into
functions.

b) Understand what is meant by the phrase "scope of variables."

c) Understand how data is passed to functions.

d) Learn how to use the library functions that are included with the
compiler.

e) List and explain the four basic types of statements. (This objective
is not from our textbook.)
Chapter’s Outline
1) Creating structured programs that are divided into functions

2) Library function and User defined function


Creating structured programs that are divided
into functions.
▪ A function is a subpart of a program. In C++, all programs have at least one
function: main().

▪ When a program is very small, the entire program can reasonably be done as
part of main(). However, as your programs grow, it will be increasingly
more important to divide your program into subtasks, each of which can
be performed by an individual function.

▪ Every C++ program must have a main function. However, it is wise to


develop an algorithm for any given project that divides large tasks into smaller
ones. Each of the smaller tasks (let's say, subtasks) can be coded as C++
functions that go together with the main function to make up a structured
program.
Reasons to Use Functions
1) The primary reason to use a function is that it provides a way to break a
complex task into subtasks which are simpler.

2) Computations that are done more than once can be coded as functions.
This eliminates duplicating program instructions.

3) The process of dividing the program into smaller parts helps you to
determine the most appropriate algorithm for your problem. (This is called
top-down design.)

4) Modularizing (divided into smaller module) your program will make it much
easier to read, both for you and for everyone else.
Reasons to Use Functions (cont…)
5) Most importantly, separating individual tasks in functions makes your
program more robust and reusable. This is one of the major emphases of
object-oriented programming. The more independent and readable your
individual functions are, the easier it will be for you or someone else to
modify your code later, or to use it as part of a new program. This is the
strength of object-oriented design.

6) Using functions makes it easier to code programs.

7) Using functions also makes it easier to debug large programs.

8) Using functions makes it easier to maintain and upgrade a program after


the first version has been finished.
Reasons to Use Functions (cont…)
5) Most importantly, separating individual tasks in functions makes your
program more robust and reusable. This is one of the major emphases of
object-oriented programming. The more independent and readable your
individual functions are, the easier it will be for you or someone else to
modify your code later, or to use it as part of a new program. This is the
strength of object-oriented design.

6) Using functions makes it easier to code programs.

7) Using functions also makes it easier to debug large programs.

8) Using functions makes it easier to maintain and upgrade a program after


the first version has been finished.
Types of Functions

There are two types of functions:


1) Predefined function
2) User defined function
Types of Functions

Predefined function
Predefined Functions (cont…)
▪ In order to use predefined function calls in your program, you need to
include the library containing the function you are interested in. For
example, to use sqrt and pow, you need to put the following statement near
the top of your file:

1) #include <math.h>
For example, sqrt(x); pow(x, y); abs(x); fabs(x); ceils(x);
floor(x);
2) #include <stdlib.h>
For example, labs(x); rand();
3) #include <string.h>
For example, strcmp(string1, string2); strcpy(var, string);
strlen(string);
4) #include <ctype.h>
For example, toupper(); tolower();
Predefined Functions
Predefined function are functions that have already been defined for you by C++. The
C++ language includes libraries of predefined functions that are available for use in
your programs. Some predefined function calls for #include <math.h> :

a) sqrt(x); returns the square root of x


e.g. sqrt(25) will return the value 5

b) pow(x, y); returns the value of x to the y power


e.g. pow(2,3) will return the value 23, or 8

c) abs(x); returns the absolute value of x


e.g. abs(-15) will return the value 15

d) fabs(x); returns the absolute value for double of x


e.g. fabs(-3.5) will return 3.5

e) ceils(x); round up the value of x


e.g. ceil (3.4) will return 4.0

f) floor(x); round down the value of x


a) e.g. floor(3.8) will return 3.0
Predefined Functions (cont…)

Some predefined function calls for #include <stdlib.h> :

a) labs(x); absolute value for x;


e.g. labs(-50000) = 50000

b) rand(); return random number;


e.g. rand() = return any number
Predefined Functions (cont…)

Some predefined function calls for #include <string.h> :

a) strcmp(string1, string2); //string compare


return true if two strings are different; otherwise returns 0

b) strcpy(var, string); //string copy


assign the string into variable

c) strlen(string); //string length


return the length of string
Predefined Functions (cont…)

Some predefined function calls for #include <ctype.h> :

a) toupper();
change to uppercase

b) tolower();
change to lowercase

For more information about predefined function please go to:


http://guinness.cs.stevens-tech.edu/~asatya/courses/cs115/lectures/lect5_1.pdf
Types of Functions

User defined function


User Defined Functions
▪ Functions are given valid identifier names, just like variables. However, a
function name must be followed by parentheses.

▪ C++ programmers generally add functions to the bottom of a C++ program,


that is after the main function. While this is not a requirement of the
compiler, it makes your code easier to read and follow by fellow
programmers.

▪ If the functions are listed after the main function, then function prototypes
must be included at the top of the program, above the main function.

▪ The function prototypes "warn" the compiler about the eventual use of the
prototyped function and allocate memory.

▪ An error will definitely result if you call a function from within the main
function that has not been prototyped.
User Defined Functions (cont…)
Example of user defined function. User defined function will be used if the function is not
provided in the library.
User-defined Functions Structure

Five important terms about user-defined functions:

1) Function Definition
a) Function Name
b) Formal Parameter Lists

c) Return value

2) Function Prototype/Declaration

3) Function Call
Types of User-defined Functions
Three types of user-defined functions:
1) Function without return value and without parameter (void
function)
2) Function with return value but with parameter
3) Function without return value but with parameter
Function without return value & without parameter
(void function)

void DisplayMenu()
{
cout<<"---------------------------"<<endl;
cout<<" Choice | Operation "<<endl;
cout<<"---------------------------"<<endl;
cout<<" A | Addition "<<endl;
cout<<" B | Subtraction "<<endl;
cout<<"---------------------------"<<endl;
}
Function with return value & with parameter

int CalculateAddition(int num1, int num2)


{
int sum;

sum = num1+num2;

return sum;

}
Function with return value & without parameter

float GetInput( )
{
float radius;

cout<<"Enter the radius of a circle: ";


cin>>radius;

return radius;
}
CHAPTER 2
FUNCTIONS (Part 2)
Chapter’s Outline
1) Scope of variables – Global dan Local

2) Types of Parameters – Formal and Actual

3) Parameter passing in functions

4) List and explain the four basic types of statements. (This objective is not
from our textbook.)
User Defined Scope of Variables

▪ Variables are either global or local in nature.


Global variables Local variables

They are declared outside and They are declared inside of a


above the main function function (defined inside function
body between { } braces).
It can be used in any function It can be used only in that
throughout the program function.

But, it is not wise to use global They cannot be used or referred


variables any more than you have to in other functions.
to. One small error (for example,
miscalculating a value) could lead
to multiple, hard-to-find errors in
large programs.
User Defined Global Variables

• Global variables are declared outside of all the functions,


usually on top of the program. The global variables will hold
their value throughout the lifetime of your program.

• A global variable can be accessed by any function. That is, a


global variable is available for use throughout your entire
program after its declaration.
Example of Global Variables
#include <iostream>
using namespace std;
void calTotal ();

int g; // Global variable declaration

int main()
{
int a = 10, b = 20; // Local variable declaration

g = a + b;
cout<<"G = "<<g<<endl;;
calTotal ();
return 0;
}

void calTotal ()
{
int total; // Local variable declaration

total = g * 2;
cout<<"Total = "<<total;
}
User Defined Local Variables
▪ A local variable is a variable declared within a block and not
accessible outside that block.
▪ Formal function parameters and variables declared within the body of a
function are local to that function:
void PrintLines( int numLines )
{
int count; // Loop control LOCAL VARIABLES
count = 1;

while (count <= numLines)


{
cout << "**************** " << endl;
count++;
}
}

▪ numLines and count are local to the void function PrintLines.


User Defined Parameters

** Every function, regardless of which type it is, has a "parameter list."

▪ This parameter list is a list of values that are passed to or from the function.
Sometimes, however, this parameter list is empty, because no values need to be
passed.

▪ When the parameter list is empty, the parentheses that are used to contain the
parameters are empty as shown in the example below.

▪ Example:

void main()
OR
int main()

▪ Most functions, though, contain at least one parameter in their parameter lists.
User Defined Parameters (cont…)
Why use parameters?

▪ Parameters allow you to share information between functions.


▪ Generally, variables that are declared within a function are local to that function.
This means that other functions generally do not have access to those variables
unless they are "sent" from one function to another by use of parameters.

"pass by value" parameters:

▪ Parameters that are "passed by value" provide information to the function that is
being called.
▪ When a parameter is passed by value, it does not change anything in the calling
function.
▪ (Parameters that change values in the calling function are called "pass by
reference" parameters; these will be discussed in a separate slide.)
Parameter passing in a function (cont…)

▪ Data is passed to functions as arguments (sometimes referred to as actual


parameters).

▪ When a function is "called" by the main function (or another function), one or more
arguments are passed to the function.

▪ On the receiving end, the function accepts these arguments (technically, as formal
parameters).

▪ The variable names of the arguments (that is, actual parameters) from the "calling"
function do not have to be the same as the names of the formal parameters in
the "called" function.

▪ But, the datatypes of the arguments and the parameters should match exactly. An
error could occur if the data types do not match.
Parameter passing in a function (cont…)

▪ We type "return 0;" as the last statement in the main functions of all
the programs that we write in this C++course.

▪ This returns a message (of "0") to the operating system indicating


that our C++ program ran successfully.

▪ A returned nonzero value is often used by programmers to indicate


that an error occurred during the program's execution.
Parameter passing in a function (cont…)

There are technically three ways to pass data as arguments to


functions. You can pass data :

1) by value,

2) by address,

3) by reference.
Parameter passing by value
PASSING BY VALUE is the preferred method. You simply use a variable name, an actual numeric literal, or an expression
in the parentheses of the call statement. This method is the safest because it does not actually change the value of the
argument in the calling function.

In the example below, the argument named price is passed by value to the function addTax.

#include <iostream.h>

double addTax(double);

int main()
{
double price = 10.00;
double finalPrice = 0.0;

//ACTUAL parameter
finalPrice = addTax(price); // function call

cout << "The final price with tax is " << finalPrice << endl;
return 0;
}// end of main
//FORMAL parameter
double addTax(double initialPrice)
{
return (initialPrice + initialPrice * 0.06);
}// end of addTax
Parameter passing by address

▪ PASSING BY ADDRESS is technically what happens when you pass an array to a


function.

▪ Since arrays are actually pointers to one memory address, you are not passing the
actual array but just information that tells the function where the first element of the
array is stored in the RAM of the computer.

▪ Making changes to the array within the function will affect the values within the
array permanently, so this method should be used with care.
Parameter passing by reference

▪ PASSING BY REFERENCE is to be used when you want the function to actually and permanently
change the values of one or more variables. This method is dangerous but beneficial sometimes since
it allows you to affect the values of arguments in your calling function.

▪ You would purposefully pass by reference if you want to return 2 or more values to the calling function.
Since it is not possible in C++ to execute two return statements within a function and since it is not
possible to return two values in the same return statement (i.e. return myResult, myOtherResult
is illegal), passing by reference can allow you to modify two or more variables in the calling function (i.e.
main).

▪ Also, if you need to pass a really large variable or object, it saves memory to pass by reference. Since a
copy of the variable is not being made when you pass by reference, less memory overhead is required.

▪ For int, double, and char variables, passing by reference to save memory is not really necessary.
However, if you were to pass a large "object" such as a piece of clipart or a whole file, you would
intentionally pass by reference.
Reference(&) Parameter (cont…)

▪ You must use an ampersand (&) before the formal parameter names in the function header
(the first line of the function definition) to denote passing by reference.In the example
below, the argument named price is passed by reference to the function addTax.

#include <iostream.h>

void addTax(double &); // function prototype

int main()
{
double price = 10.00;

addTax(price); // function call


cout << "The final price with tax is " << price << endl;
return 0;
} // end of main

void addTax(double & incomingPrice) // function header or definition


{
incomingPrice = incomingPrice + incomingPrice * 0.06;
} // end of addTax

You might also like