PF Lab 6

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

LAB 06: Functions

Objective(s):
To Understand:
1. User defined functions in C++
 Void Functions
 Return Value Functions
2. Function declaration, calling and definition.
3. Scope of an identifier
4. Value Parameters & Reference Parameters
5. Overloading Functions

CLOs: CL01, CLO4


Introduction:
The best way to develop and maintain a large program is to construct it from small, simple pieces, or
components. This technique is called divide and conquer. Functions allow you to modularize a program
by separating its tasks into self-contained units. Functions you write are referred to as user-defined
functions or programmer-defined functions.

User Defined Functions:


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, which we will explain shortly.
 Void functions—functions that do not have a return type. These functions do not use a return
statement to return a value.

Here’s mentioned all parts of a function.

Suppose num1 = 40.75 and num2 = 25.50


Formal Parameter: A variable declared in the function heading.
Actual Parameter: A variable or expression listed in a call to a function

C++ programmers customarily place the function main before all other user defined functions.
However, this organization could produce a compilation error because functions are compiled in the
order in which they appear in the program.

For example, if the function main is placed before the function larger, the identifier larger is undefined
when the function main is compiled. To work around this problem of undeclared identifiers, we place
function prototypes before any function definition (including the definition of main).

Function Prototype: The function heading without the body of the function.

Note: Function prototypes appear before any function definition, so the compiler translates
these first. The compiler can then correctly translate a function call. However, when the program
executes, the first statement in the function main always executes first, regardless of where in the
program the function main is placed. Other functions execute only when they are called.

The scope of an identifier refers to where in the program an identifier is accessible (visible).

Local identifier: Identifiers declared within a function (or block). Local identifiers are not accessible
outside of the function (block).

Global identifier: Identifiers declared outside of every function definition.

In general, there are two types of formal parameters: value parameters and reference parameters.

Value parameter: A formal parameter that receives a copy of the content of the corresponding actual
parameter.
Reference parameter: A formal parameter that receives the location (memory address) of the
corresponding actual parameter.

Note: When you attach & after the dataType in the formal parameter list of a function, then variable
following that dataType becomes a reference parameter.
Parameter Local Global
Scope It is declared inside a function. It is declared outside the function.
Value If it is not initialized, a garbage value is stored If it is not initialized zero is stored as default.
It is created before the program's global
It is created when the function starts execution
Lifetime execution starts and lost when the program
and lost when the functions terminate.
terminates.
Data sharing is not possible as data of the local Data sharing is possible as multiple functions
Data sharing
variable can be accessed by only one function. can access the same global variable.
Parameters passing is not necessary for a
Parameters passing is required for local
Parameters global variable as it is visible throughout the
variables to access the value in other function
program
When the value of the local variable is When the value of the global variable is
Modification of
modified in one function, the changes are not modified in one function changes are visible in
variable value
visible in another function. the rest of the program.
Local variables can be accessed with the help
You can access global variables by any
Accessed by of statements, inside a function in which they
statement in the program.
are declared.
It is stored on a fixed location decided by the
Memory storage It is stored on the stack unless specified.
compiler.

Example # 1
//Program: Largest of three numbers
#include <iostream>
using namespace std;
double larger(double x, double y);
double compareThree(double x, double y, double z);
int main()
{
double one, two;
cout << "The larger of 5 and 10 is " << larger(5, 10) << endl;
cout << "Enter two numbers: ";
cin >> one >> two;
cout << endl;
cout << "The larger of " << one << " and " << two << " is "
<< larger(one, two) << endl;
cout << "The largest of 43.48, 34.00,and 12.65 is "
<< compareThree(43.48, 34.00, 12.65) << endl;
return 0;
}
double larger(double x, double y)
{double max;
if (x >= y)
max = x;
else
max = y;
return max;
}
double compareThree(double x, double y, double z)
{
return larger(x, larger(y, z));
}
Program Output
The larger of 5 and 10 is 10
Enter two numbers: 25.6 73.85
The larger of 25.6 and 73.85 is 73.85
The largest of 43.48, 34.00, and 12.65 is 43.48

Example # 2
//Program: Roll dice
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int rollDice(int num);
int main()
{
cout << "The number of times the dice are rolled to "
<< "get the sum 10 = " << rollDice(10) << endl;
cout << "The number of times the dice are rolled to "
<< "get the sum 6 = " << rollDice(6) << endl;
return 0;
}
int rollDice(int num)
{
int die1;
int die2;
int sum;
int rollCount = 0;
srand(time(0));
do
{
die1 = rand() % 6 + 1;
die2 = rand() % 6 + 1;
sum = die1 + die2;
rollCount++;
} while (sum != num);
return rollCount;
}

Program Output
The number of times the dice are rolled to get the sum 10 = 11
The number of times the dice are rolled to get the sum 6 = 7

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 memory space and time relative to copying a large
amount of data
Example # 3
//Example: Reference and value parameters
#include <iostream>
using namespace std;
void funOne(int a, int& b, char v);
void funTwo(int& x, int y, char& w);
int main()
{
int num1, num2;
char ch;
num1 = 10;
num2 = 15;
ch = 'A';
cout << "Inside main: num1 = " << num1 << ", num2 = "
<< num2 << ", and ch = " << ch << endl;
funOne(num1, num2, ch);
cout << "After funOne: num1 = " << num1
<< ", num2 = " << num2 << ", and ch = " << ch << endl;
funTwo(num2, 25, ch);
cout << "After funTwo: num1 = " << num1
<< ", num2 = " << num2 << ", and ch = " << ch << endl;
return 0;
}
void funOne(int a, int& b, char v)
{
int one;
one = a;
a++;
b = b * 2;
v = 'B';
cout << "Inside funOne: a = " << a << ", b = " << b
<< ", v = " << v << ", and one = " << one << endl;
}
void funTwo(int& x, int y, char& w)
{
x++;
y = y * 2;
w = 'G';
cout << "Inside funTwo: x = " << x << ", y = "
<< y << ", and w = " << w << endl;
}

Program Output
Inside main: num1 = 10, num2 = 15, and ch = A
Inside funOne: a = 11, b = 30, v = B, and one = 10
After funOne: num1 = 10, num2 = 30, and ch = A
Inside funTwo: x = 31, y = 50, and w = G
After funTwo: num1 = 10, num2 = 31, and ch = G
Example # 4
//Program: Print a triangle of stars
#include <iostream>
using namespace std;
void printStars(int blanks, int starsInLine);
int main()
{
int noOfLines; //variable to store the number of lines
int counter; //for loop control variable
int noOfBlanks; //variable to store the number of blanks
cout << "Enter the number of star lines (1 to 20) "
<< "to be printed: ";
cin >> noOfLines;
while (noOfLines < 0 || noOfLines > 20)
{
cout << "Number of star lines should be "
<< "between 1 and 20" << endl;
cout << "Enter the number of star lines "
<< "(1 to 20) to be printed: ";
cin >> noOfLines;
}
cout << endl << endl;
noOfBlanks = 30;
for (counter = 1; counter <= noOfLines; counter++)
{
printStars(noOfBlanks, counter);
noOfBlanks--;
}
return 0;
}
void printStars(int blanks, int starsInLine)
{
int count;
for (count = 1; count <= blanks; count++)
cout << ' ';
for (count = 1; count <= starsInLine; count++)
cout << " * ";
cout << endl;
}

Program Output
Enter the number of star lines (1 to 20) to be printed: 15
Default Arguments
Default arguments are passed to parameters automatically if no argument is provided in the function
call.
It’s possible to assign default arguments to function parameters. A default argument is
passed to the parameter when the actual argument is left out of the function call.

Example # 5
#include <iostream>
using namespace std;
// defining the default arguments
void display(char = '*', int = 3);
int main() {
int count = 5;
cout << "No argument passed: ";
// *, 3 will be parameters
display();
cout << "First argument passed: ";
// #, 3 will be parameters
display('#');
cout << "Both arguments passed: ";
// $, 5 will be parameters
display('$', count);
return 0;
}
void display(char c, int count) {
for (int i = 1; i <= count; ++i)
{
cout << c;
}
cout << endl;
}

Program Output
No argument passed: *** First argument
passed: ###
Both arguments passed: $$$$$

Note: Once we provide a default value for a parameter, all subsequent parameters must also havedefault
values. For example,

void add(int a, int b = 3, int c, int d); // Invalid

void add(int a, int b = 3, int c, int d = 4); // Invalid

void add(int a, int c, int b = 3, int d = 4); // Valid

Function Overloading:
With function overloading, multiple functions can have the same name with different
parameters:
Example # 6
#include <iostream>
using namespace std;
double area(double length, double width);
double area(int radius);

const double PI = 3.1415;


int main() {
double l = 10.50, w = 5.50, r = 2.25;
cout << "Area of Rectangle: " << area(l, w) << endl;
cout << "Area of Circle: " << area(r) << endl;

return 0;
}
double area(double length, double width) {
return length * width;
}
double area(int radius) {
return PI * radius * radius;
}

Program Output
Area of Rectangle: 57.75
Area of Circle: 12.566

Task 1
Write a value-returning function, isVowel, that returns the value true if a given character is a
vowel and otherwise returns false

Task 2
Write a program that prompts the user to input a sequence of characters and outputs the number
of vowels. (Use the function isVowel written in Programming Task 1.)

Task 3
Implement the following algorithm to determine is the number Palindrome. A nonnegative integer
is a palindrome if it reads forward and backward in the same way. For example, the
integers 5, 44, 434, 1881, and 789656987 are all palindromes.
1. If num < 10, it is a palindrome, so the function should return
true.
2. Suppose num is an integer and num >= 10. To see if num is a palindrome:
a. Find the highest power of 10 that divides num and call it pwr.
For example, the highest power of 10 that divides 434 is 2; the
highest power of 10 that divides 789656987 is 8.
b. While num is greater than or equal to 10, compare the first and last
digits of num.
i. If the first and last digits of num are not the same, num is not a
palindrome. Return false
ii. If the first and the last digits of num are the same:
1. Remove the first and last digits of num
2. Decrement pwr by 2.
c. Return true.
Task 4
Write a program that asks the user to enter an item’s wholesale cost and its markup
percentage. It should then display the item’s retail price.
For example:
• If an item’s wholesale cost is 5.00 and its markup percentage is 100%, then the item’s
retail price is 10.00.
• If an item’s wholesale cost is 5.00 and its markup percentage is 50%, then the item’s
retailprice is 7.50.
The program should have a function named calculateRetail that receives the wholesale cost
and the markup percentage as arguments and returns the retail price of the item.
You can use this formula:
retailPrice = (wholesaleCost * markupPercent) + wholesaleCost

Input Validation: Do not accept negative values for either the wholesale cost of the item
or the markup percentage.

Task 5
Write a C++ Program that contains one user defined function cal_grades().
In main() function:
• Prompt user to enter obtained (0 - 100) marks for one subject.
• Call cal_grades(marks_subject).
• Print the corresponding Grade with respect to Marks.
In user defined function:
• Perform conditioning with else if statement return char value.
• Function must return value.

Task 6
Write a C++ Program that contains four user defined function(s): addition(), subtraction(),
division(), multiplication(). Develop a calculator as follows:
In main() function:
• A menu with choices addition, subtraction, division and multiplication must be
displayed.
• Get two numbers and a choice from user
• Call the respective functions with user given number as parameter using switch
statement
• Print the result from addition (), subtraction (), division (), multiplication()

Task 7
Write a program that computes and displays the charges for a patient’s hospital stay.
First, the program should ask if the patient was admitted as an in-patient or an outpatient.
If the patient was an in-patient, the following data should be entered:
• The number of days spent in the hospital
• The daily rate
• Hospital medication charges
• Charges for hospital services (lab tests, etc.)
The program should ask for the following data if the patient was an out-patient:
• Charges for hospital services (lab tests, etc.)
• Hospital medication charges
The program should use two overloaded functions to calculate the total charges. One
of the functions should accept arguments for the in-patient data, while the other function
accepts arguments for out-patient information. Both functions should return the
total charges.
Input Validation: Do not accept negative numbers for any data.

Task 8: Paint Job Estimator


A painting company has determined that for every 110 square feet of wall space,
one gallon of paint and eight hours of labor will be required. The company charges
$25.00 per hour for labor. Write a modular program that allows the user to enter
the number of rooms that are to be painted and the price of the paint per gallon. It
should also ask for the square feet of wall space in each room. It should then display
the following data:
• The number of gallons of paint required
• The hours of labor required
• The cost of the paint
• The labor charges
• The total cost of the paint job
Input validation: Do not accept a value less than 1 for the number of rooms. Do not
accept a value less than $10.00 for the price of paint. Do not accept a negative value for
square footage of wall space.

Task 9:
Use functions to rewrite the program that determines the number of odds and evens from a
given list of integers.
• A function to initialize the variables, such as zeros, odds, and evens.
• A function getNumber to get the number.
• A function classifyNumber to determine whether the number is odd or even (and
whether it is also zero). This function also increments the appropriate count.
• A function printResults to print the result

You might also like