[go: up one dir, main page]

0% found this document useful (0 votes)
71 views13 pages

Functions: Computer Programming1

1) A program can be divided into subparts called functions, which can be either predefined functions from libraries or user-defined. 2) The top-down design strategy involves dividing a program's tasks into subtasks implemented as functions, making the program easier to understand, change, write, test and debug. 3) User-defined functions in C++ are defined with a return type, name, and parameters, and can return a value or void. Functions are called by name with arguments and may return a value to the calling function.

Uploaded by

Mohammed Msallam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views13 pages

Functions: Computer Programming1

1) A program can be divided into subparts called functions, which can be either predefined functions from libraries or user-defined. 2) The top-down design strategy involves dividing a program's tasks into subtasks implemented as functions, making the program easier to understand, change, write, test and debug. 3) User-defined functions in C++ are defined with a return type, name, and parameters, and can return a value or void. Functions are called by name with arguments and may return a value to the calling function.

Uploaded by

Mohammed Msallam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Computer Programming1 Academic Year 2018-2019

Functions
A program can be thought of as consisting of subparts, such as obtaining the input data, calculating
the output data, and displaying the output data. These subparts are called functions.

Functions come in two types :


1- Predefined functions ( or built in functions ) : They can be defined by the built in as part of the
compiler package .
2- User –defined functions: They can be defined by the user.

Top –Down Design


The top-down design strategy is an effective way to design an algorithm for a program. In this
strategy you divide the program’s task into subtasks and then implement the algorithms for these
subtasks as functions.

top-down design would make the program easier to understand, easier to change if need be, and
as will become apparent, easier to write, test, and debug.
One of the advantages of using functions to divide a programming task into subtasks is that
different people can work on the different subtasks.

C++, like most programming languages, has facilities to include separate subparts inside of a
program. In other programming languages these subparts are called subprograms, procedures, or
methods, while in C++ these subparts are called functions.

Predefined Functions ( or built-in functions )


The Built-in functions are declared in header files using the form:

#include <directive which contain predefined function file>

e.g. for common mathematical calculations we include the file math with the following statement:

#include <math.h> //directive which contains the function prototypes for the
mathematical functions in the math library.

Mathematical functions
Math library functions allow the programmer to perform a number of common
mathematical calculations:

37
Computer Programming1 Academic Year 2018-2019

Function Description
sqrt(x) square root
sin(x) trigonometric sine of x (in radians)
trigonometric cosine of x (in
cos(x)
radians)
trigonometric tangent of x (in
tan(x)
radians)
exp(x) exponential function
log(x) natural logarithm of x (base e)
log10(x) logarithm of x to base 10
abs(x) absolute value (unsigned)
ceil(x) rounds x up to nearest integer
floor(x) rounds x down to nearest integer
pow(x,y) x raised to power y

Example 1: By using predefined function, Write program that find x values from the equation :

where:

Example 2 : write program that find and print z value as fallow :

( ) ( )

| | | |

38
Computer Programming1 Academic Year 2018-2019

User- defined functions


A function is a group of statements that together perform a task. Every C++ program has at least one
function, which is main.
To understand functions we must understand the following terms
1- Function definitions
2- Function Declarations
3- Calling a Function
4- Function Arguments
5- Default Values for Parameters

Function definitions
There are two type of user-defined functions:
q First type: Return one value by its name function
Uses: use when we need a function that calculate and return just ONE value
[there are no input (cin) or output (cout) statements]
Define:
List of formal parameters names and their types
type of data that the Identifier of function that receive the values of the arguments
function returns name

return-type function-name(parameter list)


{
// body of the function
return data;
}

Note: : The return _type of the function may be (int, float, char, etc.)

Example : int function-name (parameters-list)

q Second type: Not return any value by its name (Void Function)
Uses: use when we need a function that calculate and return more than ONE value
or do subtask, we can here use input (cin) or output (cout) statements.
Define:
List of formal parameters names and their types
Identifier of function that receive the values of the arguments
name

void function-name(parameter list)


{
// body of the function
}

39
Computer Programming1 Academic Year 2018-2019

Example: void function-name (parameters-list)

Example : Following is the source code for a function called max(). This function takes two parameters num1
and num2 and returns the maximum between the two:
// function returning the max between two numbers
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

Function Declarations
A function declaration tells the compiler about a function name and how to call the function. The actual body
of the function can be defined separately.

A function declaration has the following parts:

return_type function_name( parameter list );


or
void function_name( parameter list );

For the above defined function max(), following is the function declaration:
int max(int num1, int num2);

Notes :
q Parameter names are not important in function declaration only their type is required, so following is
also valid declaration:
int max(int, int);
q Function declaration is required when you define a function in one source file and you call that function
in another file or you define function after main function. In such case, you should declare the function
at the top of the file calling the function.

40
Computer Programming1 Academic Year 2018-2019

q There are two ways to write the declaration and definition of function depending on their place in
program
# include <iostream.h> # include <iostream.h>
//Function declaration ; // Function definition
void main() void main()
{ {
.... ....
// function call //function call
} }
//Function definition

Calling a Function
While creating a C++ function, you give a definition of what the function has to do. To use a function, you will
have to call or invoke that function.
‫ ط‬When a program calls a function, program control is transferred to the called function.
‫ ط‬A called function performs defined task and when its return statement is executed or when its function-
ending closing brace is reached, it returns program control back to the main program.
‫ ط‬To call a function, you simply need to pass the required parameters along with function name, and if
function returns a value, then you can store returned value. For example:

Using way1 Using Way 2


#include <iostream> #include <iostream>
int max(int , int ); int max(int num 1, int num2 )
int main () {
{ // local variable declaration
// local variable declaration: int result;
int a = 100; if (num1 > num2)
int b = 200; result = num1;
int ret; else
// calling a function to get max value. result = num2;
ret = max(a, b); return result;
cout << "Max value is : " << ret << endl; }
return 0; int main ()
} {
int max(int num1, int num2) // local variable declaration:
{ int a = 100;
// local variable declaration int b = 200;
int result; int ret;
if (num1 > num2) // calling a function to get max value.
result = num1; ret = max(a, b);
else cout << "Max value is : " << ret << endl;
result = num2; return 0;
return result; }
}

41
Computer Programming1 Academic Year 2018-2019

After running the source code it would produce the following result:

Max value is : 200


Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the arguments.
These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon
entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:

Call Type Description

Call by value This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter
( IN-ONLY)
inside the function have no effect on the argument.

Call by reference This method copies the reference of an argument into the formal
parameter. Inside the function, the reference is used to access the actual
(IN-OUT) argument used in the call. This means that changes made to the
parameter affect the argument.
Note: By default, C++ uses call by value to pass arguments. In general, this means that code within a function
cannot change the arguments used to call the function .

‫ ط‬A function definition has a name, parentheses pair containing zero or more parameters and a
body.
‫ ط‬For each parameter, there should be a corresponding declaration that occurs before the body.
Any parameter not declared is taken to be an integer by default.

The Return one value by its name function:


Parameters type
(call by value): copies the value of argument (actual parameter) into formal parameter of
the function. In this case, changes made to the parameter have no effect on the arguments.
Call :
We can write the function name with its arguments in any place can put a variable of the
same type.
Syntax:
Function_name(argument 1, argument 2,..., argument n);

Identifier or function name actual parameters

42
Computer Programming1 Academic Year 2018-2019

Return Statement :
§ The keyword return is used to terminate function and return a value to its caller.
§ The return may also be used to exit a function without returning a value.
§ Its may or may not include on expression.
§ Its general syntax is:

return ;

return (exp);

The return statements terminate the exaction of the function and pass the control back to the calling
environment.

Call Examples :
§ Assignment statement : a = sum (n, m);
§ If statement : if (sum (n, m) >=4 )
§ Output statement: cout << sum (n, m);

‫ ط‬Not return by its name ( Void Function) : It uses when we need a function that calculate and
return more than one values or do special subtask

Parameters type:
1. call by value (IN-only ): copies the value of argument (actual parameter) into formal
parameter of the function. In this case, changes made to the parameter have no effect on
the arguments.

2. call by reference(INO-out): the address of an argument is copied into the parameter. Inside
the function, the address is used to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.

43
Computer Programming1 Academic Year 2018-2019

Call :
§ We can write the function name with its arguments in any place can put a variable of
the same type.

§ Function_name(argument 1, argument 2,..., argument n);

Identifier or function name actual parameters

Exercies:

1. Write C++ program that use function named powfun() that raises an integer number passed to it
to a positive integer power and returns the result as an integer.
2. Write C++ program can swap between two variables using function:
3. Write C++ program using a functions to read sequence of positive number, then print each
number with it factorial.
4. Write C++ program using a functions to read n of integer number, then print the summation and
average of even and odd numbers.
5. Write C++ program using function to calculate the average of two numbers entered by the user .
6. Write C++ program to calculate the squared value of a number passed from main program.
calculate the square of numbers from 1 to 10.

Functions Questions
1. Design the findMax() function accepts two double arguments (number1 and number2) and return
the max number.

2. Design a function named findAbs() that accepts a double number passed to it and returns that
number’s absolute value.

3. Design a function named mult() that accepts two floating-point numbers as parameters, multiplies
these two numbers, and returns the result.

4. Design a function named square() that computes and returns the square of the integer value passed
to it.

5. Design A function named powfun() that raises an integer number passed to it to a positive integer
power and returns the result as an integer.

6. Design a function named table() that produces a table of numbers from 1 to 10, their squares, and
their cubes.

44
Computer Programming1 Academic Year 2018-2019

7. Design a function named check() that accept two integer numbers as parameters, the function
return "ok" if the second number is factorial of first number otherwise the function return "not
ok"

8. Design a function to read sequence of number (N), then print the times repeat of a specific number.

9. Design a function to read sequence of number, then print each number with it factorial.

10. Design a function to generate N term of fibo series:


1 1 2 3 5 8 13 …..
Solve All Previous Questions and Examples by using Function Concept.

Default Values for Parameters


When you define a function, you can specify a default value for each of the last
parameters. This value will be used if the corresponding argument is left blank when calling to the
function.
This is done by using the assignment operator and assigning values for the arguments in
the function definition.
If a value for that parameter is not passed when the function is called, the default given
value is used, but if a value is specified, this default value is ignored and the passed value is used
instead.
Consider the following example:
#include <iostream.h>
int sum(int a, int b=20) {
int result;
result = a + b;
return (result); }
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int result;

// calling a function to add the values.


result = sum(a, b);
cout << "Total value is :" << result << endl;

// calling a function again as follows.


result = sum(a);
cout << "Total value is :" << result << endl;

return 0;
}

45
Computer Programming1 Academic Year 2018-2019

When the above code is compiled and executed, it produces the following result:
Total value is :300
Total value is :120

Scope rule of an Identifier

Variables definition in the Functions


There are three types of variables definition:
1. Local variable: every variable defined in any function is called local for this function, so it is
valid just in this function but not valid in the other functions.
2. Global variable: every variable defined in the beginning of the program before main and
any function is called global. it is valid in all the program.
3. Not-Local variable: every variable defined outside the functions and before some functions
is called Not-local. This variable is valid in all functions written after this variable definition
But not valid in all functions written before.

46
Computer Programming1 Academic Year 2018-2019

47
Computer Programming1 Academic Year 2018-2019

48
Computer Programming1 Academic Year 2018-2019

Parameters Restrictions

Parameter communication Trace

49

You might also like