Вы находитесь на странице: 1из 8

DEPARTMENT OF TELECOMMUNICATION ENGINEERING

MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO


INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 8
ST

________________________________________________________________________

Name: _____________________________________________ Roll No: _____________

Score: ____________Signature of the Lab Tutor: _____________ Date: _/01/2018____


________________________________________________________________________

To introduce Standard and user defined functions

PERFORMANCE OBJECTIVE
Upon successful completion of this experiment, the student will be able to:
Becoming familiar with Functions in C++ and its usage in developing program
modules.

A function is collection of statements that perform a specific task. So far, we have


experienced functions in two ways.
1. Main function: Which was created in every program we have written
2. We have also used library functions such as getch() or clrscr(). These are known
as built in functions.

Similar to pre-defined or built in functions, we can create our own functions that can be
used like library functions.

One of the main reasons to write functions is that they simplify programs. If a specific
task is performed in several places in a program, a function can be written once to
perform that task, and then be executed anytime it is needed. This benefit of using
functions is known as code reuse because you are writing the code to perform a task once
and then reusing it each time you need to perform the task.

Defining & Calling functions:


A function call is a statement that causes a function to execute. A function definition
contains the statements that make up the function.
When creating a function, you must write its definition. All function definitions have the
following parts:
1. Name: Every function must have a name. In general, the same rules that apply to
variable names also apply to function names.
2. Parameter list: The program module that calls a function can send data to it. The
parameter list is the list of variables that hold the values being passed to the
function. If no values are being passed to the function, its parameter list is empty.
3. Body: The body of a function is the set of statements that carry out the task the
function is performing. These statements are enclosed in a set of braces.
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 8
ST

________________________________________________________________________
4. Return Type: A function can send a value back to the program module that called
it. The return type is the data type of the value being sent back.

Figure 1 - Different parts of function definition

It isn’t necessary for all functions to return a value, however. Some functions simply
perform one or more statements and then return. In C++ these are called void functions.
The displayMessage function shown here is an example:

The function’s name is displayMessage. This name is descriptive, as function names


should be. It gives an indication of what the function does. It displays a message. Notice
the function’s return type is void. This means the function does not send back a value
when it has finished executing and returns to the part of the program that invoked it.
Because no value is being sent back, no return statement is required. When the statements
in the function have finished executing and the right brace that ends the function is
encountered, the program automatically returns.
Calling a function:
A function is executed when it is called. Function main is called automatically when a
program starts, but all other functions must be executed by function call statements.
When a function is called, the program branches to that function and executes the
statements in its body. Let’s look at Program, which contains two functions: main and
displayMessage.
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 8
ST

________________________________________________________________________

with friends , family and specialy facebook addiction all over the world.
// This program has two functions: main and displayMessage.
#include <iostream.h>
#include <conio.h>
void displayMessage()
{
cout << "Hello from the function displayMessage.\n";
}
/***************************************
* main *
***************************************/
void main()
{
cout << "Hello from main.\n";
displayMessage(); // Call displayMessage
cout << "Back in function main again.\n";
}

Program Output
Hello from main.
Hello from the function displayMessage.
Back in function main again.

FUNCTION PROTOTYPE:

A function prototype eliminates the need to place a function definition before all calls to the
function.
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 8
ST

________________________________________________________________________
Before the compiler encounters a call to a particular function, it must already know
certain things about the function. In particular, it must know the number of parameters
the function uses, the type of each parameter, and the return type of the function.
Here is a prototype for the displayMessage function in previous Program:
void displayMessage();
This prototype looks similar to the function header, except there is a semicolon at the
end. The statement tells the compiler that the function displayMessage uses no
parameters and has a void return type, meaning it doesn’t return a value.

SENDIGN DATA TO FUNCTION:

When a function is called, the program may send values into the function

Values that are sent into a function are called arguments. We are already familiar with
how to use arguments in a function call. In the following statement the function pow is
being called with two arguments, 2.0 and 4.0 passed to it:

result = pow(2.0, 4.0);

Here is the definition of a function that uses a parameter:

void displayValue (int num)


{
cout << "The value is " << num << endl;
}

Notice the integer variable definition inside the parentheses (int num). The variable num
is a parameter. This enables the function displayValue to accept an integer value as an
argument.
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 8
ST

________________________________________________________________________
Example program demonstrating arguments:
// This program demonstrates a function with a parameter.
#include <iostream.h>
#include <conio.h>
// Function prototype
void displayValue(int num);

void main()
{
cout << "I am passing 5 to displayValue.\n";
displayValue(5); // Call displayValue with argument 5
cout << "Now I am back in main.\n";
}

/********************************************
* displayValue *
* This function uses an integer parameter *
* whose value is displayed. *
********************************************/
void displayValue(int num)
{
cout << "The value is " << num << endl;
}

Program Output
I am passing 5 to displayValue.
The value is 5
Now I am back in main.

Notice the function prototype for displayValue in line 6:


void displayValue(int num); // Function prototype

displayValue(5); // Function call

A function
void displayValue(int may
num) send a header
// Function value back to the part of the program that called
{ the function.
cout << "The value is " << num << endl;
}

THE RETURNING VALUE FROM A FUNCTION:

We have seen that data may be passed into a function by way of parameter variables.
Data may also be returned from a function back to the statement that called it. Functions
that return a value are known as value-returning functions.
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 8
ST

________________________________________________________________________

When we define value returning functions, we must decide what type of value the
function returns. This is because data type has to be specified in the function header and
prototype. Up until now all the functions we have written have been void functions. This
means they do not return a value. These functions use the key word void as the return
type in their function header and function prototype. A valuereturning function, on the
other hand, uses int, double, bool, or any other valid data type in its header. Here is an
example of a function that returns an int value:

Return Type

int sum(int num1, int num2)


{
int result;
result = num1 + num2;
return result;
}

CALLING A VALUE RETURNING FUNCTION:


Following is an example of program calling a value returning function.
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 8
ST

________________________________________________________________________
// This program uses a function that returns a value.
int sum(int num1, int num2);
void main()
{
int value1 = 20, // The first value
value2 = 40, // The second value
total; // Holds the returned total
total = sum(value1, value2);
// Display the sum of the values.
cout << "The sum of " << value1 << " and "
<< value2 << " is " << total << endl;
return 0;
}

/*********************************************************
* This function returns the sum of its two parameters. *
*********************************************************/
int sum(int num1, int num2)
{
return num1 + num2;
}

Program Output
The sum of 20 and 40 is 60
total = sum(value1, value2);

int sum(int num1, int num2)


{
return num + num;
}
DEPARTMENT OF TELECOMMUNICATION ENGINEERING
MEHRAN UNIVERSITY OF ENGINEERING & TECHNOLOGY, JAMSHORO
INTRODUCTION TO PROGRAMMING
(1 SEMESTER, 1ST Year) LAB EXPERIMENT # 8
ST

________________________________________________________________________
EXERCISE
1. Make a function named area. It should accept Length and width of a rectangle
from main function as arguments and return the area to main. Results will be
printed in main function.
2. Write a program that calculates the average of a group of test scores, where the
lowest score in the group is dropped. It should use following functions:
• Void getScore( ) should ask the user for a test score, store it in a reference
parameter variable. The function should be called by main once for each of
the five scores to be entered.
• Void calcAverage( ) should calculate and display the average of the four
highest scores. This function should be called just once by main, and should
be passed the five scores.
• int findLowest( ) should find and return the lowest of the five scores passed to
it. It should be called by calcAverage, which uses the function to determine
which of scores to drop.
3. Write a function named isprime, which takes an integer as an argument and tells if
the argument is prime number or not. Hint: Use the % operator
4. Write a function that takes the time as three integer arguments (hours, minutes,
seconds) and returns the number of seconds.

5. Write a function integerPower that returns the value of baseexponent . Assume that
the exponent is a positive, non-zero integer and base is an integer. Do not use any
math library function.

6. Write a program that inputs a series of integers and passes them one at a time to a
function “even” which uses the remainder operator to determine if an integer is even.
The function should take an integer argument and return 1 if the integer is even and
0 otherwise.
7. Define recursive and non-recursive functions by writing a simple program for each.

SUBMISSION DUE ON 24TH JAN 2018

Вам также может понравиться