Sie sind auf Seite 1von 13

The UNIVERSITY of MINDANAO

College of Engineering Education

EDP 101
Computer Programming Fundamentals
Laboratory

Laboratory Exercise # 6-A

Programmer-Defined Function
Return type

Student Name
(LN, FN MI)

Laboratory Rm No. Subject Code

Subject Teacher

Date Submitted

Score
Laboratory Exercise # 6

PROGRAM-DEFINED FUNCTIONS

Objective:

At the conclusion of this laboratory exercise, the student should be able to:

1. create a program-defined function of a particular task, void type


2. create a program-defined function of a particular task, return type

Materials:

1 computer set

C ++ IDE

Introduction:

A function is a block of code that performs a specific task. Every C++ program
contains at least one function, which is named main. However, most C++ programs
contain many functions. Some of this functions are built into the C++ language. If
for example the function pow (base, exp) and sqrt() are to be used, you must
include the header file that contains the function’s specification via the include
statement, which is in this case #include<cmath>.

In the previous exercises, you use only the function main(); the programming
instructions are packed into one function. This technique, however, is good only for
short programs. For large programs, it is not practical to put the entire
programming instructions into one function. You must learn to break the problem
into manageable pieces.

Other program functions, like main(), are created by the programmer. These
functions are often referred to as program-defined functions because the function
definitions are contained in the program itself rather than in a different file. But
why would a programmer need more than the main function? One reason is to
avoid duplication of code. If the same task needs to be performed in more than one
section of a program, it is more efficient for the programmer to enter the code
once, in a function. Any section in the program can then call the function to perform
the required task.

Program-defined functions also allow large and complex programs to be


broken into small and manageable tasks. Other advantages:

 It allows you to focus on just that part of the program and construct it.
 Different people can work on different functions simultaneously.
 If a function is needed in more than one place in a program or in different
programs, you can write it once and use it many times.
 Using functions greatly enhances the program’s readability because it
reduces the complexity of the function main.

User-defined functions in C++ are classified into two categories:

 Value-returning functions – functions that have a return type. These


functions return a value of a specific data type using the return statement
 Void functions - functions that do not have a return type. These functions
do not use a return statement to return a value.

All value-returning functions, whether built-in or program-defined, perform a


task and then return precisely one value after the task is completed.

Syntax: Value –Returning Function

functionType funtionName(formal parameter list)


{
statements;
return statement;
}
In which; statements are usually declaration statements and/or executable
statements. In this syntax, functionType is the type of the value that the function
returns. The functionType is also called the data type or the return type of the
value-returning function. Moreover, statements enclosed between curly braces
form the body of the function.

Syntax: Formal Parameter list

datatype identifier, datatype identifier,…

Various parts of the function larger():

Function Function Formal Parameters


return type name

Function double larger (double x, double y)


heading
{

double max; Local variable

if (x>=y)
Function max = x;
body
else
max = y;
return max; Function return value

Consider the following statements:

double a = 13.00;
double b = 36.53;
cout <<” The larger of “ << a << “ and “ << b
<<” is “ << larger(a, b) << endl;
The expression larger(a, b) is a function call. Here, a and b are the actual
parameters. When the expression larger(a, b) executes, the value of a is copied
into x, and the value of b is copied into y. Therefore the statement larger(a, b)
outputs the larger of a and b.

Encode the program below and observe how the function larger works.

//This program finds the largest number of a set of 10 numbers

#include <iostream>
using namespace std;
double larger(double x, double y); // function declaration

int main()
{
double num; //variable to hold the current number
double max; //variable to hold the larger number
int count; // loop control variable
cout << “Enter 10 numbers.” << endl;
cin >> num;
max = num;

for (count = 1; count < 10; count++)


{
cin >> num;
max = larger(max, num);
} // end of loop

cout << “ The largest number is “ << max << endl;

return 0;
} // end main

double larger(double x, double y)


{
double max;
if ( x >=y )
max = x;
else
max = y;
return max;
}

Void functions and value-returning functions have similar structures. Both


have a heading and a body. Both can be placed either before or after the function
main. However; void functions do not have a data type. Therefore, return
statement and return function type of the void functions are meaningless. Return
statement can still be used without any value; it is typically used to exit the function
early. A call to a void function is a stand-alone statement. Therefore, to call a void
function, you use the function name together with the actual parameters, if any, in
a stand-alone statement.

Syntax: Function Definition

void functionName (formal parameter list)

statements;

Two types of formal parameters:

1. Value parameter (pass by value): A formal parameter that received a


copy of the content of the corresponding actual parameter.
2. Reference parameter (pass by reference): A formal parameter that
receives the location (memory address) of the corresponding actual
parameter.

When you attach & after the datatype in the formal parameter list of a
function, the variable following that datatype becomes a reference parameter.
When a function is called, the value of the actual parameter is copied to the formal
parameter. If the formal parameter is a value parameter, then after copying the
value of the actual to the formal parameter, there is no connection between the
formal and actual parameters because the formal parameter has now its own copy
of the data. Therefore, at run time, the formal parameter manipulates the data
stored in its own memory space.

Encode the following program below and observe how a value parameter works
(pass by value).

#include<iostream>
using namespace std;

void fValueParameter( int num);

int main()
{
int number = 6;
cout << “Before calling the function fValueParameter, number = “
<< number << endl;
fValueParameter(int num);
cout << “ After calling the function fValueParameter, number = “
<< number << endl;
return 0;
}

void fValueParameter(int num)


{
cout << “ Inside the function fValueParameter, before changing, num = “
<< num << endl;
num = 15;
cout << “ In the function fValueParameter, after changing, num = “
<< num << endl;
}
After copying the data from actual to formal, a value parameter has no
connection with the actual parameter. Therefore, a value parameter cannot pass
any result back to the calling function. When the function executes, any changes
made to the formal parameters do not in any way affect the actual parameters.
Value parameters provide only a one-way link between actual and formal
parameters.

If a formal parameter is a reference parameter, that is if you attach


&(ampersand) after the datatype, reference parameters can pass one or more
values from a function and can change the value of the actual parameter, because
a reference parameter receives the address (memory location) of the actual
parameter. The & which is referred to as the address-of operator, tells the
computer to pass the variable’s address rather than copy of its contents.

Reference parameters are useful in three situations:

 When the value of the actual parameter needs to be changed.


 When you want to return more than one value from a function
 When passing the address would save the memory space and time relative
to copying a large amount of data.

Encode the program below and observe how passing variables by reference works

#include<iostream>
using namespace std;
void getAge(int &inYears);
void displayAge(int years);
int main()
{
int age = 0;
getAge(age);
displayAge(age);
return 0;
}

void getAge(int &inYears)


{
cout << “How old are you? “;
cin << inYears;
}

void display( int years)


{
cout << “ You are “ << years << “ years old.” << endl;
}

Remember that when you pass a variable by a value, the computer uses the
data type and name of its corresponding formal parameter to create a separate
memory location in which to store the value. When you pass a variable by
reference, on the other hand, the computer locates the variable in memory and
then assigns the name of its corresponding formal parameter to the memory
location. When you pass a variable by reference, the variable will have two names:
one assigned by the calling function and the other assigned by the receiving
function. Value-returning functions, on the other hand, send information back to
the calling function through their return value.

Laboratory Task 6-A: (return type)

Code the IPO chart shown below. Display the Celsius temperature in fixed-point
notation with no decimal places.

Input Processing Output


Main function

Fahrenheit temperature Processing items: none Celsius temperature

Algorithm:
1. Call getFahrenheit
function to get the
Fahrenheit temperature
2. Call the calcCelsius to
calculate temperature;
pass the Fahrenheit
temperature
3. Display the Celsius
temperature
getFahrenheit function

Fahrenheit temperature Processing items: none Fahrenheit temperature

Algorithm:
1. Enter the Fahrenheit
temperature
2. Return the Fahrenheit
temperature
calcCelsius function

Fahrenheit temperature Processing items: none Celsius temperature

Algorithm:
1. Celsius temperature =
5.0 / 9.0 * (Fahrenheit
temperature – 32.0)
2. Return the Celsius
temperature

1. Observations: Pass by value


___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________

Laboratory Task 6-B (void type, &, pass by reference)

Modify the code from Laboratory Task 6-A. Change the getFahrenheit and
calcCelsius functions to void functions.

2. Observations: Pass by reference


___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
Student Generated Code Exercises

Create a program that calculates the average of three test scores. The
program should contain two value-returning programs (main and calcAverage) and
two void functions (getTestScores and displayAverage). The main function should
call the void getTestScores function to get three scores. The test scores may
contain a decimal place. The main function then should call the value-returning
calcAverage function to calculate and return the average of the three test scores
on the screen. Display the average with one decimal place. Use a sentinel value to
end the program.

Create IPO charts for the problem. List the input, processing and output
items, as well as the algorithm, in a chart similar to the one shown in Laboratory
Task A. Code the algorithm into a program. Use file format <lastname_Lab6.cpp>
and upload to specified link at schoology.com.

Answer: IPO Chart


Rubric
Ratings
Parameters
3 2 1

Syntax Source code contains Source code Source code


(30%) no syntax error. contains 1 to 5 contains more than
syntax errors. 5 syntax errors.
(30) (20) (10)

Source code contains Source code lacks Source code is not


Specifications the complete details to necessary details to enough to run the
(30%) run the program run the program program correctly.
correctly. correctly.
(30) (20) (10)

Source code is well Minor issues such as Major issues are


Readability organized and easy to variable naming, causing the codes to
(10%) understand. variable utilization, be not readable.
etc. are observed.
(10) (6) (3)

Screen Output Source code is well Source code allows Source code does
(10%) organized and easy to the required screen not meet the
understand. output to be required screen
displayed correctly output to be
with 1-3 errors displayed correctly.
found.
(10) (6) (3)

The documentation is The documentation The documentation


Documentation well written and clearly lacks some didn’t satisfy all the
(20%) explained all the information and questions that were
questions given in the some mistakes are given in the
laboratory exercise. found in the laboratory exercise.
questions.
(20) (14) (7)

Das könnte Ihnen auch gefallen