66
 1 Functions Lecture 4 Computer Programming (MEng 1052) Mechanical Engineering Department Prepare d by: Addisu D. & Beza T. March, 2015

Lecture 4. Functions

Embed Size (px)

DESCRIPTION

C++ lecture Notes

Citation preview

  • 1Functions

    Lecture 4

    Computer Programming(MEng 1052)

    Mechanical Engineering

    Department

    Prepared by: Addisu D. & Beza T. March, 2015

  • Introduction A function is defined as a group of instruction used to achieve a

    specific task.

    When we write larger programs we have to have a way of

    breaking problems down into smaller sub-problems.

    C++, like most programming languages, has facilities to include

    separate subparts inside of a program. In C++ these subparts are

    called functions.

    Functions decrease the complexity of a program. A program

    having multiple functions can be easily debugged than a program

    that is large and runs without a single function. So a function

    reduces the size of a program and increases the program

    modularity.

    Functions would make the program easier to understand, write,

    test, and debug.

    Every C++ program has at least one function, main().2

  • Advantages of functions

    Increase program modularity

    Reduction in the amount of work & development time

    Program and function debugging is easier

    Division of work is simplified

    Reduction in the size of the program due to code

    reusability

    Functions can be accessed repeatedly without

    redevelopment, which in turn promotes reuse of code

    3

    Introduction

  • Types of function

    Functions are of two types:

    1. Predefined functions (Library/built-in function)

    2. User defined function

    4

  • Predefined functions

    C++ comes with libraries of predefined functions that you can

    use in your programs.

    Library functions are pre-written functions or built in

    functions. Many activities in C++ use library functions.

    Use of all library functions requires the inclusion of a header

    file, which contains function prototypes and constant

    definitions.

    We have already seen the use of #include in all of

    the examples so far.

    The name inside the angular brackets < > is the name of a file

    known as a header file. A header file for a library provides the

    compiler with certain basic information about the library, and

    an include directive delivers this information to the compiler.

    5

  • This enables the linker to find object code for the functions in

    the library so that it can correctly link the library to your

    program.

    For example, the library iostream contains the definitions of

    cin and cout, and the header file for the iostream library is

    called iostream.

    The other most commonly used library in C++ is the math

    library which contains the definition of many mathematical

    functions, and the header file for this library is cmath.

    If your program uses a predefined function from some library,

    then it must contain a directive that names the header file for

    that library, such as the following:

    #include

    6

    Predefined functions

  • Some Predefined Functions

    7

  • 8Some Predefined Functions

  • 9Some Predefined Functions

  • Notice that the absolute value functions abs and labs are in the

    library with header file cstdlib, so any program that uses either of

    these functions must contain the following directive:

    #include

    If you want to produce the absolute value of a number of type

    int, you use abs; if you want to produce the absolute value of a

    number of type long, you use labs; and if you want to produce

    the absolute value of a number of type double, you use fabs.

    abs and labs are in the library with header file cstdlib, while fabs

    is in the library with header file cmath.

    fabs is an abbreviation for floating-point absolute value.

    Recall that numbers with a fraction after the decimal point, such

    as numbers of type double, are often called floating-point

    numbers.10

    Predefined functions

  • Another example of a predefined function is pow, which is

    in the library with header file cmath. The function pow can

    be used to do exponentiation in C++.

    For example, if you want to set a variable result equal to xy,

    you can use the following:

    result = pow(x, y);

    Hence, the following three lines of program code will

    output the number 9.0 to the screen, because (3.0)2.0 is 9.0:

    double result, x = 3.0, y = 2.0;

    result = pow(x, y);

    cout

  • Function Call

    A function call is an expression consisting of the function name

    followed by arguments enclosed in parentheses. If there is more

    than one argument, the arguments are separated by commas.

    A function call is an expression that can be used like any other

    expression of the type specified for the value returned by the

    function.

    12

  • 13

    Example

  • 14

  • PROGRAMMER-DEFINED FUNCTIONS

    Declaring and Defining Functions

    Using functions in your program requires that you first declare

    the function and then define the function.

    Function declaration tells the compiler the name, return type,

    and parameters of the function.

    The definition tells the compiler how the program works.

    No function can be called from any other function that hasnt

    first been declared.

    The declaration of a function is called its prototype.

    Many of the built-in functions you use will have their function

    prototypes already written in the files you include in yourprogram by using#include.

    For functions you write yourself, you must include the

    prototype.15

  • Function Declaration

    Function declarations are normally placed before the main part

    of your program.

    16

  • Example: A Function Definition

    17

  • 18

  • The description of the function is given in two parts that are

    called the function declaration and the function definition.

    The function declaration (also known as the function

    prototype) describes how the function is called.

    C++ requires that either the complete function definition or the

    function declaration appears in the code before the function is

    called.

    In the above sample function program given the function

    declaration is

    double total_cost(int number_par, double price_par);

    The function declaration tells you everything you need to know

    in order to write a call to the function.

    19

    Function Declaration

  • It tells you the name of the function, in this case total_cost.

    It tells you how many arguments the function needs and

    what type the arguments should be; in this case, the

    function total_cost takes two arguments, the first one of

    type int and the second one of type double.

    The identifiers number_par and price_par are called formal

    parameters.

    The names of the formal parameters can be any valid

    identifiers.

    The first word in a function declaration specifies the type

    of the value returned by the function.

    Thus, for the function total_cost, the type of the value

    returned is double.

    20

    Function Declaration

  • Function call

    In the above sample program the function call is in the

    following line:

    bill = total_cost(number, price);

    The function call is the expression on the right-hand side of

    the equal sign.

    The function name is total_cost, and there are two arguments:

    The first argument is of type int, the second argument is of

    type double.

    The compiler does not care whether theres a comment along

    with the function declaration, but you should always include a

    comment that explains what value is returned by the function.

    21

  • A function definition describes how the function computes

    the value it returns.

    If you think of a function as a small program within your

    program, then the function definition is like the code for this

    small program. In fact, the syntax for the definition of a

    function is very much like the syntax for the main part of a

    program.

    A function definition consists of a function header followed

    by a function body.

    The function header is written the same way as the function

    declaration, except that the header does not have a semicolon

    at the end. This makes the header a bit repetitious, but thats

    OK.

    22

    Function definition

  • The function body consists of declarations and executable

    statements enclosed within a pair of braces.

    Thus, the function body is just like the body of the main part of

    a program.

    When the function is called, the argument values are plugged

    in for the formal parameters and then the statements in the

    body are executed.

    The value returned by the function is determined when the

    function executes a return statement.

    A return statement consists of the keyword return followed by

    an expression.

    return (subtotal + subtotal*TAX_RATE);

    23

    Function definition

  • When this return statement is executed, the value of the

    following expression is returned as the value of the function

    call:

    (subtotal + subtotal*TAX_RATE)

    The parentheses are not needed. The program will run

    exactly the same if the return statement is written as

    follows:

    return subtotal + subtotal*TAX_RATE;

    However, on larger expressions, the parentheses make the

    return statement easier to read.

    24

    Function definition

  • 25

  • Function Prototype and Function Definition

    The prototype for the FindArea ( ) function is on line 4.

    Compare the prototype with the definition of the function on

    line 25. Note that the name, the return type, and the parameter

    types are the same. If they were different, a compiler error

    would have been generated.

    In fact, the only required difference is that the function

    prototype ends with a semicolon and has no body.

    Also note that the parameter names in the prototype are lengthand width, but the parameter names in the definition are l and w.

    The names in the prototype are not used; they are there as

    information to the programmer. When they are included, they

    should match the implementation when possible. This is a

    matter of good programming style and reduces confusion, but it is not required, as you see here.

    26

  • The body of the function is always enclosed in braces, even when

    it consists of only one statement, as in this case.

    The definition of a function consists of the function header and its

    body. The header is exactly like the function prototype, except

    that the parameters must be named, and there is no terminating

    semicolon.

    The body of the function is a set of statements enclosed in braces.

    A function prototype tells the compiler the return type, name, and

    parameter list.

    Functions are not required to have parameters, and if they do, the

    prototype is not required to list their names, only their types.

    A prototype always ends with a semicolon (;).

    27

    Function Prototype and Function Definition

  • 28

    Function Prototype and Function Definition

  • A function definition must agree in return type and parameter

    list with its prototype. It must provide names for all the

    parameters, and the body of the function definition must be

    surrounded by braces.

    All statements within the body of the function must be

    terminated with semicolons, but the function itself is not ended

    with a semicolon; it ends with a closing brace.

    If the function returns a value, it should end with a return

    statement, although return statements can legally appear

    anywhere in the body of the function. Every function has a return type

    29

    Function Prototype and Function Definition

  • 30

  • Analysis

    On lines 7 and 8, two float variables are declared, one to hold the temperature in Fahrenheit and one to hold the temperature in

    degrees Celsius.

    The user is prompted to enter a Fahrenheit temperature on line 10, and that value is passed to the function Convert ( ).

    Execution jumps to the first line of the function Convert ( ) on line 20, where a local variable, also named TempCel, is declared.

    Note that this local variable is not the same as the variable TempCel on line 8. This variable exists only within the function

    Convert ( ). The value passed as a parameter, TempFer, is also just a local copy of the variable passed in by main ( ).

    This function could have named the parameter FerTemp and the local variable CelTemp, and the program would work equally

    well. You can enter these names again and recompile the program to see this work.

    31

  • The local function variable TempCel is assigned the value that

    results from subtracting 32 from the parameter TempFer, multiplying by 5, and then dividing by 9..

    This value is then returned as the return value of the function,

    and on line 12 it is assigned to the variable TempCel in the main ( ) function. The value is printed on line 14.

    As an exercise, try entering the program again with other

    variable names as illustrated below:

    32

    Analysis

  • 33

  • Local Variables

    Variables that are declared within the body of a function

    definition are said to be local to that function or to have that

    function as their scope.

    Variables that are declared within the main part of the program

    are said to be local to the main part of the program or to

    have the main part of the program as their scope.

    When we say that a variable is a local variable without any

    mention of a function and without any mention of the main

    part of the program, we mean that the variable is local to some

    function definition.

    If a variable is local to a function, then you can have another

    variable with the same name that is declared in the main part of

    the program or in another function definition, and these will be

    two different variables, even though they have the same name.

    34

  • Example-Function with local variables

    35

  • Global Variables

    Variables defined outside of any function have global scope and thus are available from any function in the program,

    including main ( ).

    Local variables with the same name as global variables do not change the global variables. However, a local variable

    with the same name as a global variable hides the global

    variable.

    If a function has a variable with the same name as a global variable, the name refers to the local variable-not the global--

    when used within the function.

    36

  • Example-Global variable

    37

  • 38

  • 39

  • More Sample programs and

    Exercises

    40

  • 41

  • 42

  • 43

  • A p

    rog

    ram

    wh

    ich

    re

    ad

    s t

    wo

    nu

    mb

    ers

    an

    d

    mu

    ltip

    lie

    s t

    ho

    se

    nu

    mb

    ers

    us

    ing

    fu

    nc

    tio

    n.

    44

  • The following program finds the larger of two accepted numbers from

    the user.

    45

  • 46

  • 47

  • Exercise

    48

  • Exercise

    Write a function declaration and a function definition for a

    function that takes three arguments, all of type int, and that

    returns the sum of its three arguments.

    49

  • 1. Write a function declaration and a function definition for a

    function that takes one argument of type int and one argument

    of type double, and that returns a value of type double that is

    the average of the two arguments.

    2. Write a function declaration and a function definition for a

    function that takes one argument of type double. The function

    returns the character value 'P' if its argument is positive and

    returns 'N' if its argument is zero or negative.

    3. Write an int function cube ( ) that returns the cube of its

    single int formal parameter.

    4. Write a float function triangle ( ) that computes the area of a

    triangle using its two formal parameters h and w, where h is

    the height and w is the length of the bases of the triangle.

    50

    Exercises

  • void FUNCTIONS

    The functions discussed so far always return a single value.

    In C++, a function must either return a single value or return

    no values at all.

    A function that returns no value is called a void function.

    Definitions of void Functions

    In C++ a void function is defined in a way similar to the way

    that functions that return a value are defined.

    For example, the following is a void function that outputs the

    result of a calculation that converts a temperature expressed in

    Fahrenheit degrees to a temperature expressed in Celsius

    degrees.

    The actual calculation would be done elsewhere in the program.

    This void function implements only the subtask for outputting

    the results of the calculation.51

  • there are only two differences between a function definition

    for a void function and the function definitions of functions

    that return a value.

    52

    void FUNCTIONS

  • One difference is that we use the keyword void where we

    would normally specify the type of the value to be returned.

    This tells the compiler that this function will not return any

    value. The name void is used as a way of saying no value is

    returned by this function.

    The second difference is that the return statement does not

    contain an expression for a value to be returned, because,

    after all, there is no value returned.

    53

    void FUNCTIONS

  • 54

    void FUNCTIONS

  • 55

  • 56

  • 57

  • 58

  • 59

  • Recursion Functions

    Sometimes, the best way to solve a problem is by solving a smaller version of the exact same problem first.

    Recursion is a technique that solves a problem by solving a smaller version of the same type.

    When you turn this into a program, you end up with functions that call themselves (recursion functions).

    There are many problems whose solution can be defined recursively

    Example: n factorial

    60

    1 if n = 0n!= (recursive solution)

    (n-1)!*n if n > 0

    1 if n = 0n!= (closed form solution)

    1*2*3**(n-1)*n if n > 0

  • 61

    Recursion Functions

  • 62

  • 63

  • 1. Write a function called isPrime ( ) that accepts a

    number and determine whether the number is prime

    or not.

    2. Write a function called isEven ( ) that uses the

    remainder operator(%) to determine whether an

    integer is even or not.

    64

    Quiz_Sec. C (5%)

  • Quiz_Sec. D (5%)

    1. Write a function called SumofEven ( ) that

    calculates and displays the sum of even numbers

    from 2 to 100.

    2. Write a function called isOdd ( ) that uses the

    remainder operator(%) to determine whether an

    integer is odd or not.

    65

  • End of Lecture 4

    Next Lecture

    Lecture 5: Arrays and Strings

    66