Você está na página 1de 8

Qatar University

College of Engineering
Dept. of Computer Science & Engineering

Computer Programming -GENG106


Lab Handbook
Fall 2011 Semester

Lab7: Functions
Objectives:
At the end of this lab, you should be able to
Create and call functions in C++: functions that return values and void functions.
Distinguish between passing parameters by value and passing by reference

Quick Review - Summary of key concepts:

A function is an executable unit that has a set of statements and optional inputs and outputs.

Every function should be limited to performing a single, well-defined subtask.

The caller of a function may be either the main() function, or any other function. A function call
is represented by its name and the argument list (which must correspond and match the
parameter list). Parameters are passed either by value or by reference.

When passing a parameter by value, a copy of the arguments value is passed to the called
function.

When passing a parameter by reference, the address of the argument is passed to the called
function.

1) Problem Solving a detailed example:


The goal of this exercise is to practice how to design and write a program. The process of developing
a program to solve a problem involves several stages:
1. First understand the problem and what the program must do.
2. Design: Carefully plan your program. From the problem description you need to identify:
Input / Output data and key information about them - their type and whether they are
constants or variables.
Functions needed to solve the problem and key information about them - whether they are
built-in C++ operations or are defined in some library (and which one) or need to be
implemented.
Algorithm: Organize the data and functions into an algorithm - a sequence of steps that
solves the problem.
3. Coding: Translate your algorithm into a programming language like C++.
4. Testing: Run your program with sample data to check for errors, then debug and fix your errors.
This lab will use an example problem to demonstrate these steps.

Problem Description:
Design and write a function to convert from feet to meters (1 foot = 0.3048 m). The number of feet
should be a positive number.
1. Understanding the problem
Our function should receive from its caller the number of feet to be converted, and should check
that this value is non-negative.
if feet>0, it should convert that quantity to meters by multiplying it by 0.3048, and then
return the resulting value to the caller.
else, it should return 0.
2. Design
Note that where a program (i.e. function main()) typically inputs values from the keyboard, a
function typically receives values from its caller. Similarly, where a program typically outputs
values to the screen, a function typically returns a value to its caller. This distinction is very
important because, by far, most functions do not use cin or cout.
main()

main()

Input Data

Input Data

function()
Call function()

Process Data

Process Data

Display Results

Display Results

End

End

The main() is doing all the job

End

The main() calls function() to do part of the job

Function variables:
We list the variables of the function and we specify their movement. For each variable we ask:
does it move into the function from outside, does it move from the function out to the outside, or
is it purely local to the function?
Description

Kind

Movement

the number of feet

Type
double

varying

in

Name
feet

the conversion factor

double

constant

local

0.3048

the corresponding number of meters

double

varying

out

meters

Function specification:
receive: feet, the number of feet to be converted.
precondition: feet is not negative.
return: meters, the equivalent of feet in meters.
Keep in mind that none of this information here is magical. The nouns in the problem description
are our variables. Also from the problem description we infer the variable type, kind, and
movement of the variables.
The specification of a function provides us all we need to write a function prototype. A
prototype specifies what the function does, not how is does it.
The simplified pattern for a function prototype is:
returnType functionName(parameterList);
where

returnType is the type of value the function returns.


functionName is the name we decide to give to the function.
parameterList is a list of declarations of parameters.

From our function specification we can derive the function prototype:


double feetToMeters(double feet);

Algorithm for the meters-to-feet function


1. Receive feet value from the caller.
2. Check feet:
if feet >=0, compute meters = feet * 0.3048 and return the meters.
else, return 0.
Implementing the meters-to-feet function using C++
The function definition for feetToMeters():
double feetToMeters(double feet)
{
double meters ;
if(feet>=0)
meters = feet * 0.3048 ;
else
meters = 0;
return meters;
}
Writing a main() function (called a driver program) to test the meters-to-feet function
Most test programs use the same algorithm:
1. Display a prompt for whatever values the function requires as arguments.
2. Read those values from cin.
3. Call the function that you're testing using the input values as arguments.
4. Display via cout the result of calling the function plus a descriptive label.
2

int main()
{
double feet , meters;
cout << "Enter measurement in feet: ";
cin >> feet;
meters = feetToMeters(feet);
cout << feet <<" Feet = "<< meters <<" Meters\n";
return 0;
}
4. Testing
Once the program is successfully translated, we are ready to test what we have written. Execute
the program, and use the following sample data:
Feet
1.0
3.3
-5.9

Meters
0.3048
1.00584
0

2) Try It - Experiment
This exercise involves a series of experiments that will help you understand the key concepts related to
C++ functions particularly exploring reference parameters and scoping issues.

Type, compile and run the following C++ program:


#include <iostream>
using namespace std;
void change(int, int, int);
int main()
{
// Print a message explaining the program;
cout << "\nThis program provides a 'laboratory' in which\n"
<< "experiments can be performed on parameter-passing.\n";
int arg1, arg2, arg3;
// 1. Initialize arguments to -1
arg1 = arg2 = arg3 = -1;
// 2. Display arg1, arg2, and arg3 before calling change() function
cout << "\nBefore: arg1 = " << arg1
<< ", arg2 = " << arg2
<< ", arg3 = " << arg3 << endl;
// 3. Call change(), passing in arg1, arg2, and arg3 as arguments
change(arg1, arg2, arg3);
// 4. Display arg1, arg2, and arg3 after calling change() function
cout << "\nAfter: arg1 = " << arg1
<< ", arg2 = " << arg2
<< ", arg3 = " << arg3 << "\n\n";
return 0;
}

/**************************************************************************
* change() function:
*
* receives: 3 integers, stored in param1, param2, param3;
*
* supposed to return: the (altered ???) values of param1, param2, param3. *
**************************************************************************/
void change(int param1, int param2, int param3)
{
param1 = 1;
param2 = 2;
param3 = 3;
}

Using your editor, take a moment to look over the program. Its behavior consists of 3 steps:
1. Initialize a set of variables to some initial value (-1 in this case).
2. Call function change()that tries to modify the values of those variables.
3. Output the values of those variables to view the effects of function change().

Run your program to see how it works and write down the values of arg1, arg2 and arg3
before the change() function is called:
____________________________________________________________________

Did the values of arg1, arg2 and arg3 change after calling the change() function?
__________________________________________________________________________

The change() function tries to alter the values of its parameters. By comparing the values
displayed before the function call with those displayed after the function call, do the function's
changes affect the variables declared in the main() program? Explain the observed behavior?
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Modify the definition of change(), so that its parameter names match the argument names:
void change(int arg1, int arg2, int arg3)
{
arg1 = 1;
arg2 = 2;
arg3 = 3;
}

Recompile and rerun the modified program.

If a value parameter has the same name as its corresponding argument, will altering the
parameter alter the corresponding argument?
_____________________________________________________________________________
_____________________________________________________________________________

Undo the modifications performed on the previous step and then continue

Modify the prototype of change()function:


void change(int&, int&, int&);
and its definition to:
void change(int& param1, int& param2, int& param3)
{
param1 = 1;
param2 = 2;
param3 = 3;
}

Run your program and write down the values of arg1, arg2 and arg3 after the change()
function is called:
___________________________________________________________________________

Did the changes made by the change() function affect the variables declared in the main()
program? Explain the observed behavior?
____________________________________________________________________________
____________________________________________________________________________

Modify the prototype of change()function (notice the const keyword in front of the 3rd
parameter):
void change(int & param1, int & param2, const int & param3);
and its definition to:
void change(int & param1, int & param2, const int & param3)
{
param1 = 1;
param2 = 2;
param3 = 3;
}

Compile and execute your program. Were you successful? Explain the observed behavior?
________________________________________________________________________________
________________________________________________________________________________

What is the role of the const keyword in front of a function parameter? When should you use it?
________________________________________________________________________________
________________________________________________________________________________

3)
3.1 Write a function named celsiusToFahr(double C) that returns the Fahrenheit (F) equivalent of a
degree Celsius temperature represented by the parameter C. The conversion formula is:
F 1.8C 32

Write a C++ program that prompts the user to enter a value in Celsius, then calls the function
celsiusToFahr() and finally displays the equivalent value in Fahrenheit.
Sample output

3.2 Write a C++ program that uses the celsiusToFahr(double C) function and displays a properly
formatted table which has two columns of temperature values: degree Celsius between 0 and 100
in steps of 10oC and the equivalent Fahrenheit temperature.
Sample output:

4)
4.1 Using a loop structure, write function myPow(double x, int y) which calculates xy.
Write a C++ program that uses myPow() to calculate the following :
z =

where x is entered by the user

Sample output:

4.2 Modify your program such that the myPow(double x, int y) function can handle the case when y
is negative. Test your program using the following equation: Tip: x-y = 1/xy
k =
Sample output:

5) Write a C++ function that swaps two integers. An example of calling the function is shown below:
int x=10, y=20;
cout <<"Before: x = " << x << " and y= " <<y << endl;
mySwap(x, y);
//After calling the swap() function: x=20 and y=10
cout <<"After : x = " << x << " and y= " <<y << endl;
Hint: the mySwap()function should pass parameters by reference.
6)

The second moment of inertia is a mathematical representation of a beam's resistance to bending.


a. Write a function that returns the second moment of inertia (I) for a
rectangular section which has a width and height , as
shown in the figure. The formula is

Use the

following function prototype:


double rectangleMomInertia(double b, double h);
b. An I-section (i.e. a cross-section in the shape of the letter I) consists of a vertical part called the
web and two horizontal parts called the flanges (see the figure on
the right). The second moment of inertia for an I-section is given
by:

Flange

= [Second moment of inertia of the rectangle,


]
[Second moment of inertia of the two rectangles under the
flanges,
In C++
I = rectangleMomInertia(b,h) 2*rectangleMomInertia(0.5*(b-tw),h1)

Now, write a function that returns the second moment of inertia for an I-section. Let your
function use the function rectangleMomInertia() as explained above. Use the following
prototype:
double iSectionMomInertia(double b,double h,double tw,double h1);

c. Write a C++ program that inputs the dimensions of the following sections, and then computes
and outputs the second moment of inertia for each.

Web

Você também pode gostar