+ All Categories
Home > Documents > C++Lang chap5

C++Lang chap5

Date post: 03-Jun-2018
Category:
Upload: samaan
View: 227 times
Download: 0 times
Share this document with a friend

of 31

Transcript
  • 8/11/2019 C++Lang chap5

    1/31

    CHAPTER 5

    Functions

    5.1 WHAT IS A FUNCTION?A function can be equated to a "blackbox" to which one or more input values are passed, some

    processing done, and output value(s) is(are) then returned automatically.

    Figure 5.1 illustrates this sequence when a function namedsqrtis called. The value of x (16.0)

    is the function input, and the function result or output is the square root of 16.0, i.e. 4.0.

    Figure 5.1

    Function sqrt

    as a "Black

    Box"

    5.1.1 Functions as Program Building Blocks

    Programmers use functions like building blocks to construct large programs. Arguments of a

    function are used to pass information into the function subprogram from the main function and to

    return to the calling function multiple results computed by the function subprogram. Arguments

    that carry information from the main function into the function subprogram are called input argu-

    ments or parameters. Arguments that return results to the main function are called output argu-

    ments.

    Figure 5.2 shows a function with multiple inputs and outputs.The most fundamental idea in problem solving is dividing a problem into subproblems and

    solving each subproblem independently. In attempting to solve a subproblem at one level, we

    often introduce further subproblems at a lower level. This is shown in Example 1.

    result is 4.0x is 16.0square root

    computation

    function sqrt

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap5

    2/31

    96 Programming in C++ Part I

    Figure 5.2

    Function with

    multiple

    Inputs and

    Outputs

    Ex a m ple 1Suppose you want to draw simple diagrams or figures shown in Figure 5.3. The figure on the left

    consists of a triangle without its base on top of a rectangle. The figure on the right consists of a

    pattern consisting of a circle, a triangle and a triangle without its base.

    o

    utputss

    p

    tu

    n

    i

    function

    Figure 5.3

    House and

    Stick Figure

    We should be able to draw both diagrams using the four basic graphical components shown in

    Figure 5.4. Initially, we shall focus on the stick figure. We can divide the problem of drawing this

    figure into the following three sub problems:

    (a) Draw a circle(b) Draw a triangle

    (c) Draw intersecting lines

    The sub problem of step (b) containing triangle can be further divided into following subproblems,

    viz.,

    (i) draw intersecting lines

    (ii) draw a base

    *

    *

    *

    *

    *

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap5

    3/31

  • 8/11/2019 C++Lang chap5

    4/31

    98 Programming in C++ Part I

    subproblemDraw a triangle(at level 1) is dependent on the solutions to the subproblems Draw

    intersecting linesand Draw a base(both at level 2). The solution of such type of problems can

    easily be carried out using step-down approach.

    C ++ Func t ion

    A C++ function is a grouping of program statements into a single unit to carry out tasks at a given

    level. Each C++ function can be activated through the execution of a function call.

    If we assume that we have functions available that implement each of the level 2 subproblems

    of Figure 5.5, we can use the following program segment to implement the level 1 subproblem

    Draw a triangle.

    /* Draw a triangle */draw_intersect();draw_base();

    The above program segment contains two function call statements. During program execution,

    the function call statement

    draw_intersect();

    causes the statements contained in the body of functiondraw_intersectto be executed.

    The program shown in Figure 5.6 also contains another function namely draw_circle. This

    function call causes the statements contained in the body of the function draw_circle to be

    executed.

    When we run the program, the first statement in the main function body (the call to

    draw_circle) is the first statement to be executed. When the computer executes a function call

    statement, it transfers control to the function that is referenced.

    After the last statement in the function body is executed, control returns to the main function.

    After the return to the main function, the next statement will be executed (namely the call to

    draw_intersect).

    The function declarations must appear before any call to the functions. Any of the three func-

    tions may be declared first. Their order of execution is determined by the order of function call

    statements in the body of the main function. The output of the program given in Figure 5.6 is

    shown in Figure 5.7.

    The definition of a simple function like draw_circle is similar to the definition of amainfunc-

    tion. It consists of the name of the function followed by the function body. It is desirable to place a

    block comment explaining the purpose of the function immediately before the functions name.The definition of the function (prototype) draw_circle consists of the keyword void, the function

    namedraw_circle, and then the keywordvoidagain in parentheses.

    The result of a function is referred to as its return type. A function that does not yield a value

    has a return type ofvoid. The actual actions a function performs are specified in the body of the

    function. The function body always starts with the opening brace "{" and ends with the closing

    brace "}". Each function body may contain declaration for its own variables. These variables are

    consideredlocalto the function. In other words, they can be referenced only within the function.

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap5

    5/31

    Part I Functions 99

    /* Draw a stick figure */#include#include/* Draws a circle */void draw_circle (void){

    cout

  • 8/11/2019 C++Lang chap5

    6/31

    100 Programming in C++ Part I

    Figure 5.7

    Output of stick figure

    5.1.2 Classification of Functions

    Functions are of two types. These are:

    (a) Built-in Functions or Library functions(b) User Defined Functions

    5.1.3 Built-in Functions

    Many of the operations, like taking the square root of a number, sine value of a number etc., will

    be frequently used by many programmers in their programs. Writing a program to find the square

    root of a number or sine value of a number every time in each program by individual programmers

    is an unnecessary and tiresome job. Such operations are programmed in the form of standard

    functions and stored in C++ library, so that they can be called in any program. These functions are

    called library functions or built-in functions. Table 5.1 shows some of the commonly used mathe-

    matical built-in library functions.

    Table 5.1

    Some Mathematical Built-in Library FunctionsFunction Library File Purpose: Example Argument(s) Result

    abs(x) Returns the absolute value of its integer int intargument:if x is -5, abs(x) is 5

    ceil(x) Returns the smallest whole number that is double doublenot less than x:if x is 45.23, ceil(x) is 46.0

    (Contd...)

    *

    * *

    * *

    / \

    / \

    / \

    -------/ \

    / \

    / \

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap5

    7/31

  • 8/11/2019 C++Lang chap5

    8/31

    102 Programming in C++ Part I

    /* Computing the roots of a quadratic equation */#include#include#includedouble disc,root_1,root_2;double a,b,c;main (){cout > a >> b >> c;disc = pow(b,2) - 4 * a * c;

    if (disc >=0) {root_1 = (-b + sqrt(disc))/(2*a); root_2 = (-b -sqrt(disc))/(2*a); cout

  • 8/11/2019 C++Lang chap5

    9/31

    Part I Functions 103

    (a) The complexity of the entire program can be divided into simple subtasks and function

    subprograms can be written for each subtasks.

    (b) The subprograms are easier to write, understand and debug.

    (c) A function can be shared by other programs by compiling it separately and loading them

    together.

    (d) In C++, a function can call itself again. It is called recursiveness. Many calculations can

    be done easily using recursive process such as calculation of factorial of a number.

    (e) The functions such as cout, cin, the numerical computation functions sin, cos, sqrt etc.,

    are used very frequently. Hence these are kept in C++ library and compiler is written in

    such a way that any C++ program can call any of the library functions.5.2 DEFINING A FUNCTION

    A function definition has a name, a parentheses pair containing zero or more parameters and a

    body. For each parameter, there should be a corresponding declaration that occurs before the body.

    Anyparameternot declared is taken to be an intby default. For good programming, one should

    declare all parameters. Turbo C++ compiler permit including the argument declaration with the

    parentheses.

    The general format of the function definition is as follows:

    func_type func_name(datatype argument1,datatype argument2...)

    { body of the function_______________return statement;

    }

    5.2.1 Declaring the type of Function

    The function refers to the type of value it would return to the calling portion of the program. Any

    of the basic data types such as int, float, char etc. may appear in the function declaration. In case,

    when a function isnotsupposed to return any value, it may be declared as typevoid. For example:

    int func_name (int a );void func_nam (float b);

    5.2.2 Function Name

    The function name can be any name conforming to the syntax rules of the variables. One should

    normally use a function name relevant to the function operation. For example:

    void show(void)void square (int a, int b)

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap5

    10/31

    104 Programming in C++ Part I

    Figure 5.9 illustrates the definition of a user defined line() function. You will notice that the

    function definition is at the beginning of the function itself, and the semicolon isnotused after the

    name of the function. The program is shown in Figure 5.10.

    Figure 5.9

    Definition of

    line() funciton

    int j ;

    for ( j = 1 ; j < 20 ; j ++ )

    cout

  • 8/11/2019 C++Lang chap5

    11/31

    Part I Functions 105

    must be defined externally.

    int counter (float x1, int x2, char c){__________return (int value);

    }

    In the above program segment,x1, x2andcare formal arguments applicable to the function

    only. The function returns anint valueto the calling program.

    The program listed in Figure 5.10 uses a line() function to draw a line containing 20 asterisks

    (*). We can draw any number of such lines by calling the line() function. Thus there is no need to

    write a program every time. You need to define the function once and call the user defined func-tion any number of time to perform the desired function. The variable jused in line() function in

    Figure 5.9 is only known to line(). It is invisible to the main() function. If we used this variable in

    function main() without declaring it there, then compiler gives an error message because main()

    would not know any thing about this variable. This is very important to know while writing func-

    tions in C++. Variables used in a function are unknown outside the function. Thus a local variable

    will be known to the function it is defined in, but not to others. A local variable used in this way in

    a function is known in C++ as an "automatic" variable, because it is automatically created when a

    function is called and destroyed when the function returns.

    The following program demonstrates the function declaration, function calling and function

    definition.

    // Program demonstrating function calling, declaration and defi-nition#includevoid show (void); //prototypevoid main (void){void show (void); // function declarationshow(); // function calling}void show(void) // function definition

    {cout

  • 8/11/2019 C++Lang chap5

    12/31

    106 Programming in C++ Part I

    Ex a m ple 3

    The program given in Figure 5.11 uses a special character \x7 which is called BELL in the stan-

    dard ASCII code. By using thecoutstatement, we can create a beeping sound by using this code.

    The program calls a function calledtwobeep(). The function sounds two beeps separated by a short

    silent interval. Then the program asks you to type a letter. When you do, it sounds the two beeps

    again. You should note how the delay is created. Aforloop is set up to cycle 1000 times. You will

    notice that there is no statement in the body offorloop. The statement consists of only the semi-

    colon. This constitutes a "null" statement: a statement with nothing in it. Its only role is to termi-

    nate theforloop after cycling 1000 times. This may be thought as aforloop for introducing delay

    in the loop.

    #include#include/*twobeep *//*beeps the speaker twice */void twobeep (void){int k;cout

  • 8/11/2019 C++Lang chap5

    13/31

    Part I Functions 107

    Func tion type

    The function "type" is the type of the returned value. If the function does not return a value, the

    type is defined asvoid.

    Func tion na m e

    The function name is any legal identifier followed by the parentheses without any spaces in

    between.

    Argume nts

    The arguments (or parameters) are given inside the parentheses, preceded by their types and sep-

    arated by commas. If the function does not use any parameters, the word void is used inside the

    parentheses. Here are some examples for prototypes of built-in functions.

    int getchar(void);

    double pow(double x,double y);

    void exit(int x);

    The first function int getchar (void);returns an integer value and does not take anyarguments. The second function double pow(double x, double y);takes two doublearguments (the value ofx and the value ofy) and returns a value of the type double. The third

    function void exit (int x);returns no value but it accepts an argumentxof the type inte-ger.

    Function prototype serves to notify the C++ compiler of the type and number of argu-

    ments that a function will use. You may occasionally encounter functions written with an

    old method of prototyping such as "int func()," or without any prototyping at all. The

    programs written in this way are prone to errors and hard to debug. Prototyping helps the

    compiler to detect errors if the function is improperly used.

    Actually, the header files such asiostream.handstdio.hcontain the prototypes of the built-in

    C++ functions. You may sometimes forget to include the proper header file in your program, but

    you still have the program running and may get correct results. This is because if you do not

    include the header file, the compiler will use the default type which is of the typeintfor any func-

    tion.

    5.2.5 Use of void( ) If the function is of the type void, no return statement is used. Actually, the main() block of the

    C++ program is a function, and because no type is specified, it is therefore considered of the type

    int. Turbo C++ compiler gives a warning if you do not use the returnstatement at the end of the

    main() block. You can avoid this warning by writing your main function as given below:

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap5

    14/31

    108 Programming in C++ Part I

    main(){statement(s);return(0);

    }

    This means that no returned value is expected from the main function. Another way to avoid

    the warning message is to use thevoidtype like this:

    void main(){.....

    }You may also run across programs with the main function declared as:

    void main(void);

    5.3 ACCESSING A FUNCTION

    A user defined function is invoked or called from the main program simply by using its name,

    including the parentheses containing the parameters to be passed, if any, which follow the name.

    The parentheses are mandatory so that the compiler knows you are referring to a function and not

    a variable that you forgot to declare.

    5.3.1 Invoking a Function without Passing Argument(s)

    It is the simplest way of writing a user defined function because there is no formal argumenttransfer between the calling statement of the program and a called program function. Program

    shown in Figure 5.12(a) calls the function sample()without passing any argument. The function

    sample()after execution transfers the control back to the functionmain(). The presence of void in

    the functionvoid sample (void)shows that no value is passed to the function.

    / * Program for calling function without passing values from main() */#includevoid sample (void); /* prototype declaration of function sample */void main (void){ cout

  • 8/11/2019 C++Lang chap5

    15/31

    Part I Functions 109

    Figure 5.12(b)

    Output of the

    program

    shown in Fig-

    ure 5.12(a)

    5.3.2 Passing Arguments to Function

    Arguments are used to pass the values of variable to a function. The structure of a function passing

    one argument is shown in Figure 5.13(a).

    In the definition of functionbar1()shown in Figure 5.13(a),int scorewithin the parenthesis isthe formal argument. This shows that themain()will transfer the argument forscorewhich has a

    integer value. The keywordvoidbefore bar1 indicates that the functionbar1()does not return any

    value to the main() block.

    Figure 5.13(a)

    Structure of

    function with

    one argument

    You will observe the following points while using the function call with arguments:

    (a) In the main() program, shown in Figure 5.13(b), the argument or parameter we want to

    pass to the function bar1(), is included in the parentheses i.e. () following "bar1" such as inthe function call bar1(7).

    (b) We can also use the variable in place of the constant value 7 within the parentheses namely

    bar1(int score). This ensures that the value included between parentheses in the main pro-

    gram is assigned to the variable between parentheses in the function definition [See Figure

    5.13(c)]

    I am calling function sample

    Thank you for calling me. I am sample

    int j;

    for (j=1;j

  • 8/11/2019 C++Lang chap5

    16/31

    110 Programming in C++ Part I

    Figure 5.13(b)

    Passing a con-

    stant value to a function

    7main( )

    {

    bar1(7);

    }

    void bar1(int score)

    }

    {

    The value of 7 is assigned

    to the variablescore (the argument)

    in the function

    Calling program

    Function

    Figure 5.13(c)

    Passing a value

    to a function

    using

    variable as an

    argument

    (c) The declaration for the variable score takes place between the braces just after the name

    bar1. For example:

    void bar1(int score)

    25main( )

    {

    bar1(25);

    }

    void bar1(int score)

    }

    {

    Whatever argument value bar1has that is passed to the

    variable score

    in the function

    Calling program

    Function

    void bar1(int score)

    score is called the"actual argument" "formal argument"

    score is called the

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap5

    17/31

    Part I Functions 111

    The unique placement of the declarations for the argument variables serves to remind the

    compiler and the programmer that these are special variables whose values are supplied by the

    calling program. The use of variable used as argument is illustrated in Figure 5.13(c).

    Let us now study the program shown in Figure 5.14(a). This program generates a bar graph of

    names and bars representing the value assigned to the variablescore. The output of the program is

    shown in Figure 5.14(b).

    /* Program using argument to pass data to a function */#include#includevoid bar1(int score)

    {int j;for (j = 1; j

  • 8/11/2019 C++Lang chap5

    18/31

    112 Programming in C++ Part I

    The definition of the functionbar1is given first. The main program calls this function several

    times by passing the value of the argumentscore. For example, bar1(25) calls the function bar1

    and passes the argument 25 as the value of thescore. The function prints the double line character

    "CD" 25 times and returns control to main(). Similarly, in the next line of the main program,

    bar1(35) is executed. In this case, a value of 35 is passed as value ofscoreand double line char-

    acter "CD" is executed 35 times. After this, control is returned to main program. The output is

    shown in Figure 5.14(b).

    Stora ge of Va lue s whe n pa sse d a s Argum e nts to a Func t ion

    The program given in Figure 5.15(a) transfers the value of x and y to the function swap1() and the

    function swap1() receives them and stores them as separate variables xx and yy in a separate loca-

    tion in the main memory. It then prints the values of xx and yy when asked to do so.

    /* This program demonstrates passing arguments to a function */#include#includevoid swap1(int xx, int yy){cout

  • 8/11/2019 C++Lang chap5

    19/31

    Part I Functions 113

    Figure 5.15(b)

    Values dupli-

    cated in Func-

    tions main

    memory

    /* Program for calling function by passing formal arguments from main() */#includevoid cube (int, int); /* prototype declaration of function cube */void main (void){ int x, y; cout x >> y; cube(x,y); /* function call */}void cube (int x, int y) /* function definition */

    { x = x*x*x; y = y*y*y ; cout

  • 8/11/2019 C++Lang chap5

    20/31

    114 Programming in C++ Part I

    Figure 5.16(b)

    Output of the

    program

    shown in Fig-

    ure 5.16(a)

    /* Program showing passing of formal arguments to function from main() *//* and computed value passed back to calling program */#include float cube (float); /* prototype declaration of function cube */void main (void){ float i,max,value; max = 2.0; i = -2.0; while ( i

  • 8/11/2019 C++Lang chap5

    21/31

    Part I Functions 115

    Figure 5.17(b)

    output of the

    program

    shown in Fig-

    ure 5.17(a)

    5.3.3 Passing Multiple Arguments to a FunctionYou can pass as many arguments to a function as you wish. For example, in the program given in

    Figure 5.18(a), two arguments are passed to a function called rectang1(). The purpose of this

    function is to draw a rectangle whose sides are given as multiple arguments namely (int length, int

    width) in the declaration:

    void rectang1(int length,int width);

    /* Program passing multiple arguments to a function */#include#includevoid rectang1(int length, int width){int j,k;length /= 2; /* scaling length to half */width /= 4; /* scaling width to one fourth */for (j = 1; j

  • 8/11/2019 C++Lang chap5

    22/31

    116 Programming in C++ Part I

    The typical run of the program is shown in Figure 5.18(b). Figure 5.18(c) illustrates the pass-

    ing of multiple arguments to a function.

    Figure 5.18(b)

    Typical run of

    the program

    shown in

    Figure 5.18(a)

    drawing room

    kitchen

    bedroom

    bathroom

    Figure 5.18(c)

    Illustration of

    passing multi-ple arguments

    to a functionvoid rectang1(int length,int width)

    }

    {

    Function

    void rectang1(int length,int width)

    }

    main()

    Calling program

    {

    rectang1(22,12);

    12

    22

    The first actual argument is passedto the first formal argument; the

    second actual argument is passed

    to the second formal argument.

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap5

    23/31

    Part I Functions 117

    5.3.4 Returning values by the Function

    How function returns a value can be understood by the following analogy. Suppose you hire

    someone to find out some information for you. Say for example, you dial telephone number. 174

    to find out what time it is. You make the call, and the person (or computer) at the other end of the

    line gives you the time. You do not need to tell them what you want which is understood when you

    call that telephone number. No information flows from you to the telephone exchange but some

    information is given back from it to you.

    A function that accepts no arguments from the main() block, but returns a value performs a

    similar role. You call the function, it gets a certain piece of information and returns it to you. The

    built-in function getche() operates just in this way. You call it without giving it any

    information and it returns the value of the first character typed on the keyboard.Ex a m ple 5

    Suppose we want to build a function that returns a character but that also automatically translates

    any uppercase characters into lower case. That means if we type Ait returnsa. This function is

    given the namegetlc()and the program is given in Figure 5.19(a).

    #include#include/* getlc() *//* returns character *//* converts to lowercase if in uppercase */

    char getlc(char){ char ch; cin >> ch; /* read character */ if ( ch > 64 && ch < 91 ) /* if uppercase, */ ch += 32; /* add 32 to convert to lower case */ return (ch); /* return character value */}int main (void){ char chlc,ch; cout

  • 8/11/2019 C++Lang chap5

    24/31

  • 8/11/2019 C++Lang chap5

    25/31

    Part I Functions 119

    Purp ose o f re turn() Sta tem e nt:

    The return() statement has two purposes.

    (a) Transferring control from the function back to the calling program.

    (b) Whatever is inside the parentheses following return is returned as a value to the calling pro-

    gram.

    Figure 5.20 shows a function returning a value to the calling program. The return statement need

    not be at the end of the function. It can be placed anywhere in the function; as soon as it is

    encountered, control will return to the calling program. For example, the function getlc() written in

    Example 5 could be rewritten as shown in Figure 5.21.

    Figure 5.20

    Function

    Returning a

    Value to the

    calling pro-

    gram

    #include#include/* getlc() */

    /* returns character *//* converts to lowercase if in uppercase */char getlc(ch){ char ch; cin >> ch; /* read character */

    (Contd...)

    main ( )

    {

    }

    ans = func ( ) ;

    }

    {

    x = 3 ;

    func ( )

    return (x) ;

    Calling program Function

    The value of x ,

    which is 3 , is

    returned to

    and assigned to

    main ( )

    ans.

    3

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap5

    26/31

    120 Programming in C++ Part I

    if ( ch > 64 && ch < 91 ) /* if uppercase, */ return (ch+32); /* return converted value */ else /* otherwise */ return (ch); /* return character value */}

    Figure 5.21 Alternative form of program to convert a character to lower case if in upper case

    In this modified version of the program, different returnstatements are used depending on

    whetherchis uppercase or not.

    The return statement can also be used without parentheses. When this is the case, no value

    is returned to the calling program.

    Lim ita tion o f re turn() Sta tem e nt:

    Main limitation in the use of the return() statement is that you can only use it to returnone value.

    Ex a m ple 6

    The program shown in Figure 5.21(a) uses the functionfactorialto calculate the factorial of a

    number between 0 and 10.

    /* Computes and prints the factorial of a number *//* Demonstrates an user-defined function that has an inputparameter */#include#include/* function computes factorial n */int factorial(int n){ int i,product; /* local variable */ product = 1; /* Computes the product n into (n-1) (n-2) ... 2 1 */ for ( i = n; i > 1; i = i - 1) {

    product = product * i; } /* Returns function result */ return (product);}

    (Contd...)

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap5

    27/31

    Part I Functions 121

    voidmain (void){ int num, fact; cout > num; if (num < 0) {

    cout

  • 8/11/2019 C++Lang chap5

    28/31

    122 Programming in C++ Part I

    Figure 5.22(b)

    Output of the

    program in

    Figure 5.22(a)

    Enter an integer between 0 and 10: 0

    The factorial of 0 is 1

    Enter an integer between 0 and 10: 4

    The factorial of 4 is 24

    Enter an integer between 0 and 10: 10

    The factorial of 10 is 24320

    Enter an integer between 0 and 10: -5

    The factorial of a negative number is undefined-5Enter an integer between 0 and 10: 11

    Number out of range 11

    Figure 5.22(c)

    Effect of execu-

    tion of factorial

    when numis 5 /*

    * Computes Factorial n* Pre: n is greater than or equal to zero */

    int

    factorial(int n)

    {

    int i, /* local variables */

    product = 1;

    /* Compute the product n x (n - 1) x (n - 2)

    x ... x 2 x 1 */

    for (i = n; i > 1; i = i - 1) {

    product = product * i;

    }

    /* Return function result */

    return (product);}

    Call factorial with n = 5

    Return result value of 120

    fact = factorial (num);

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap5

    29/31

    Part I Functions 123

    /* Program using function to find largest of three numbers */#includefloat largest (float, float, float);void main (void){ float u,v,w,max; cout > u >> v >> w; max = largest(u,v,w); cout z )

    return (x); else return (z); } else { if ( y > z )

    return (y);

    elsereturn (z);

    }} /* end of function */

    Figure 5.23(a) Program using a function for calculating the largest of three numbers

    Figure 5.23(b)

    Output of the

    program in

    Figure 5.23(a)

    5.3.5 Organization of Program containing Functions

    Organize your program according to the following steps:

    (a) Begin with a block comment identifying the programs purpose.

    (b) Include any preprocessor directives such as

    #define, etc.

    Enter any three numbers

    4.01 3.201 4.001

    largest of the three numbers = 4.01

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap5

    30/31

    124 Programming in C++ Part I

    (c) Precode definitions of your function subprograms before any call to them

    5.4 PASSING ADDRESSES TO A FUNCTION

    In sections 5.3.1 and 5.3.2, we have seen how to pass value(s) to a function. In some cases the

    function also returns a single value to the main program. But how can a function return more than

    one value to the calling program? This is achieved by passing the value of the argument by refer-

    ence or passing the address where the argument is stored in the main memory. This is better

    understood by the concept of pointers.

    In order to economize on the main memory and to transfer multiple values from the function

    to the main() or the calling program, we use pointers. The calling program, instead of passingval-

    uesof arguments to the function, passes theiraddresses. These addresses are where the calling

    program wants thefunctionto place the data it modifies. This is explained in Chapter 6 of Part II.

    TEST PAPER

    Time: 3 Hrs

    Max Marks: 100

    Answer the following questions.

    1. Which of these are valid reasons for using functions?

    (a) They use less memory than repeating the same code.

    (b) They run faster.

    (c) They keep different program activities

    separate.

    (d) They keep variables safe from other parts of the program.

    Ans[All except (b) are valid reasons for using functions]

    2. Which of the following are valid reasons for using arguments in functions?

    (a) To tell the function where to locate itself in memory.

    (b) To convey information to the function that it can operate on.

    (c) To return information from the function to the calling program.

    (d) To specify the type of the function.

    Ans(b and c)

    3. Which of the following can be passed to a function via arguments?

    (a) constants

    (b) variables (with values)

    (c) preprocessor directives

    (d) expressions (that evaluate to a value)

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap5

    31/31

    Part I Functions 125

    (e) functions (that return value)

    Ans(a, b d and e)

    4. Write a program in C++ that prints out the larger of two numbers entered from the key-

    board. Use a function to do the actual comparison of the two numbers. Pass the two

    numbers to the function as arguments, and have the function return the answer.

    5. Write a program in C++ that asks the user to input length of the two sides of a right

    angled triangle. Make use of the built-in functionspowandsqrtfunctions to compute the

    length of the hypotenuse using the Pythagorean theorem.

    6. When do you use the keywordreturnwhile defining a function? When do you not use

    the keyword return when defining a function?

    7. Write a C++ program that asks for a distance in meters and converts it into feet.8. Write a program in C++ to call a function which returns the cube of a given number.

    9. Write a program to accept a binary number and convert it into a decimal number.


Recommended