Page 287 - Computer_Science_F5
P. 287

Computer Science  Note:   There are two ways to call functions, which are function call by value (pass
                   by value) and function call by reference (pass by reference).
                   (a)   Call by value involves copying the values of actual parameters into the
                       formal parameters.
          FOR ONLINE READING ONLY
                   (b) Call by reference involves copying the address of the arguments into
                       actual parameters within the function.


           Program examples 30 and 31 demonstrate call by value and call by reference. Program
           Example 4.29 demonstrates a C++ program that finds cube of the number. The output
           is shown in Figure 4.58.


                   Program Example 4.29:

              Finding the cube of the number using function

                        #include<iostream>
                        using namespace std;
                        int cube(int x)
                        {
                               x=x*x*x;
                               return x;

                        }
                        int main()
                        {
                               int a;
                               cout<<”Enter number to find its cube “;
                               cin>>a;
                               cout<<”Cube of “<<a<<” is “<<cube(a);// call by value
                        }


              Output:







                                     Figure 4.58: Output of the program


           You can use the following program example to learn on program that interchanges
           values entered by a user. The following Program Example 4.30 demonstrates a
           C++ program that interchanges value entered by the user. The output is shown in
           Figure 4.59.


                                                 278
                                                                for Advanced Secondary Schools



     Computer Science Form 5.indd   278                                                     23/07/2024   12:34
   282   283   284   285   286   287   288   289   290   291   292