Sunteți pe pagina 1din 13

Lecture Notes on Functions

Functions[1] are subroutines containing a statement or a collection of statements that


perform a certain task.

Benefits of Functions[2]
At times, a certain portion of codes has to be used many times. Instead of re-writing the
codes many times, it is better to put them into a "subroutine", and "call" this "subroutine"
many time - for ease of maintenance and understanding. Subroutine is called method (in
Java) or function (in C/C++).
The benefits of using functions are:

Divide and conquer: construct the program from simple, small pieces or
components. Modularize the program into self-contained tasks.
Avoid repeating codes: It is easy to copy and paste, but hard to maintain and
synchronize all the copies.
Software Reuse: you can reuse the functions in other programs, by packaging
them into library codes.
Two parties are involved in using a function: a caller who calls the function, and the
function called. The caller passes argument(s) to the function. The function receives
these argument(s), performs the programmed operations within the function's body, and
returns a piece of result back to the caller. (see Figure 1)

Figure 1. How a function works

Dizon, Chester F., CpE

CS 100A Lecture on Functions

Syntax of a Function
returnedValuetype functionName( parameterList ) // function header
{
local variable declarations; // if any
statement1;
statement2;
.
.
.
statementN;

body of a function

Function Definition[3]
The syntax for function definition is as follows:
returnValueType functionName ( parameterList )
{
functionBody ;
}
The parameterList consists of comma-separated parameter-type and parametername, i.e., param-1-type param-1-name, param-2-type param-2-name,...
The returnValueType specifies the type of the return value, such as int or double. An
special return type called void can be used to denote that the function returns no
value. In C++, a function is allowed to return one value or no value (void).

Function Declaration and Function Prototype [4]


All identifiers in C need to be declared before they are used. This is true for functions as
well as variables. For functions the declaration needs to be before the first call of the
function. A full declaration includes the return type and the number and type of the
arguments. This is also called the function prototype.
Note: Older versions of the C language didn't have prototypes, the function declarations
only specified the return type and did not list the argument types. Unless your stuck with
an old compiler, function declarations should always be prototypes and this book uses
the terms interchangeably.

Having the prototype available before the first use of the function allows the compiler to
check that the correct number and type of arguments are used in the function call and
that the returned value, if any, is being used reasonably.
Syntax of a Function Declaration
returnedValuetype functionName ( parameterList );

Dizon, Chester F., CpE

CS 100A Lecture on Functions

Function Naming Convention[5]


A function's name shall be a verb or verb phrase (action), comprising one or more words.
The first word is in lowercase, while the rest are initial-capitalized (known as camelcase). For example, getArea(), setRadius(), moveDown(), isPrime(), etc.

Two (2) Kinds of Functions


Built-in functions - are functions already defined in the C libraries such as printf( ) and
the scanf( ) functions, and the like.
User-defined functions - are functions created by programmers to perform a certain
task inside a program.

The "return" Statement[6]


Inside the function's body, you could use a return statement to return a value (of the
returnValueType declared in the function's header) and pass the control back to the
caller.
The syntax is:
return expression; // Evaluated to a value of returnValueType declared in function
return;
// For function with return type of void
Take note that invoking a function (by the caller) transfers the control to the function. The
return statement in the function transfers the control back to the caller.

The "void" Return Type[7]


Suppose that you need a function to perform certain actions (e.g., printing) without a
need to return a value to the caller, you can declare its return-value type as void. In the
function's body, you could use a "return;" statement without a return value to return
control to the caller. In this case, the return statement is optional. If there is no return
statement, the entire body will be executed, and control returns to the caller at the end of
the body.

Dizon, Chester F., CpE

CS 100A Lecture on Functions

Sample Problem 1:
Write a program that would ask a user two numbers and how to process the numbers,
either add or subtract. The program should display the answer of the users desired
choice.

Flowchart (Design):

Dizon, Chester F., CpE

CS 100A Lecture on Functions

Implementation (Code):
/* Write a program that would ask a user two numbers and how to process the numbers,
either add or subtract. The program should display the answer of the users desired
choice. */
#include<iostream> // pre-processor directives
#include<conio.h>
#include<stdlib.h>
using namespace std;
main()
{
int num1, num2, choice, sum, diff; // local variable declaration
system ("cls");
cout << "Enter two numbers: ";
cin >> num1 >> num2;
cout << "What do you want to do with the numbers?\n";
cout << "[1] Add \n[2] Subtract";
cout << "\nEnter your choice: ";
cin >> choice;
switch(choice)
{
case 1: sum=num1+num2;
cout << "\nThe sum is " << sum;
break;
case 2: diff=num1-num2;
cout << "\nThe difference is " << diff;
break;
default: cout << "Invalid input.";
}
getch();
}

Dizon, Chester F., CpE

CS 100A Lecture on Functions

Flowchart (Design with pre-defined processes):

Dizon, Chester F., CpE

CS 100A Lecture on Functions

Implementation (Code with Function Definitions):


/* The program now has 3 functions, including the main( ) function. In this
implementation, all identifiers are globally declared and no function declarations were
used since the user-defined functions are located before the main( ) function. */
#include<iostream> // pre-processor directives
#include<conio.h>
#include<stdlib.h>
using namespace std;
int num1, num2, choice, sum, diff; // global variable declaration
int Add() // function definition
{
sum=num1+num2;
cout << "\nThe sum is " << sum;
}
int Subtract()
{
diff=num1-num2;
cout << "\nThe difference is " << diff;
}
main()
{
system ("cls");
cout << "Enter two numbers: ";
cin >> num1 >> num2;
cout << "What do you want to do with the numbers?\n";
cout << "[1] Add \n[2] Subtract";
cout << "\nEnter your choice: ";
cin >> choice;
switch(choice)
{
case 1: Add(); break;
case 2: Subtract(); break;
default: cout << "Invalid input.";
}
getch();
}

Dizon, Chester F., CpE

CS 100A Lecture on Functions

Implementation (Code with Function Declarations):


/* The program now has function declarations since the function definitions are placed
after the main( ) function. */
#include<iostream> // pre-processor directives
#include<conio.h>
#include<stdlib.h>
using namespace std;
int Add(); // function declaration or function prototype
int Subtract();
int num1, num2, choice, sum, diff; // global variable declaration
main()
{
system ("cls");
cout << "Enter two numbers: ";
cin >> num1 >> num2;
cout << "What do you want to do with the numbers?\n";
cout << "[1] Add \n[2] Subtract";
cout << "\nEnter your choice: ";
cin >> choice;
switch(choice)
{
case 1: Add(); break;
case 2: Subtract(); break;
default: cout << "Invalid input.";
}
getch();
}
int Add() // function definition
{
sum=num1+num2;
cout << "\nThe sum is " << sum;
}
int Subtract()
{
diff=num1-num2;
cout << "\nThe difference is " << diff;
}
Dizon, Chester F., CpE

CS 100A Lecture on Functions

Sample Problem 2:
Write a program that would ask a user two numbers and how to process the numbers,
either add or subtract. The program should display the answer of the users desired
choice. In addition, the program would ask the user if he/she would like to try again. The
program would continuously run the whole process until he/she decides to exit the
program.

Flowchart (Design with loop process):

Dizon, Chester F., CpE

CS 100A Lecture on Functions

Implementation (Code with loop process):


/* The program is now incorporated with the loop process using the do-while statement.*/
#include<iostream> // pre-processor directives
#include<conio.h>
#include<stdlib.h>
using namespace std;

Dizon, Chester F., CpE

CS 100A Lecture on Functions

10

int Add(); // function declaration or function prototype


int Subtract();
int num1, num2, choice, sum, diff; // global variable declaration
char tryagain;
main()
{
do{
system ("cls");
cout << "Enter two numbers: ";
cin >> num1 >> num2;
cout << "What do you want to do with the numbers?\n";
cout << "[1] Add \n[2] Subtract";
cout << "\nEnter your choice: ";
cin >> choice;
switch(choice)
{
case 1: Add(); break;
case 2: Subtract(); break;
default: cout << "Invalid input.";
}
cout << "\n\nWould you like to try again?[Y/N] ";
cin >> tryagain;
}while ((tryagain=='Y')||(tryagain=='y'));
system("cls");
cout << "Thank you for using the program. ^_^";
getch();
}
int Add() // function definition
{
sum=num1+num2;
cout << "\nThe sum is " << sum;
}
int Subtract()
{
diff=num1-num2;
cout << "\nThe difference is " << diff;
}

Implementation (Code with looping process using function calling):

Dizon, Chester F., CpE

CS 100A Lecture on Functions

11

/* The program calls the main( ) function as a way of looping process to repeat the
program until the user chooses to end the execution. */
#include<iostream> // pre-processor directives
#include<conio.h>
#include<stdlib.h>
using namespace std;
int Add(); // function declaration or function prototype
int Subtract();
int num1, num2, choice, sum, diff; //global variable declaration
char tryagain;
main()
{
system ("cls");
cout << "Enter two numbers: ";
cin >> num1 >> num2;
cout << "What do you want to do with the numbers?\n";
cout << "[1] Add \n[2] Subtract";
cout << "\nEnter your choice: ";
cin >> choice;
switch(choice)
{
case 1: Add(); break;
case 2: Subtract(); break;
default: cout << "Invalid input.";
}
cout << "\n\nWould you like to try again?[Y/N] ";
cin >> tryagain;
if ((tryagain=='Y')||(tryagain=='y'))
main(); // the main( ) function is called to repeat the process.
else
{
system("cls");
cout << "Thank you for using the Kemberler software. ^_^";
}
getch();
}
int Add() // function definition
{
sum=num1+num2;
cout << "\nThe sum is " << sum;
}

Dizon, Chester F., CpE

CS 100A Lecture on Functions

12

int Subtract()
{
diff=num1-num2;
cout << "\nThe difference is " << diff;
}

References:
[1]

CS 200L2 Computer Fundamentals and Programming Laboratory Manual

[2][3][5][6][7]

http://www.ntu.edu.sg/home/ehchua/programming/cpp/cp1_Basics.html

[4]

http://opencbp.sourceforge.net/en_US.ISO8859-1/books/opencbook/func.prototypes.html

Dizon, Chester F., CpE

CS 100A Lecture on Functions

13

S-ar putea să vă placă și