SlideShare a Scribd company logo
F1001 PROGRAMMING FUNDAMENTALS




  UNIT

    8

FUNCTION

 Concepts of Functions
 User-defined Functions




                                            105
F1001 PROGRAMMING FUNDAMENTALS


  INTRODUCTION


  So far, in the previous unit, students only use one function in their program which is the main function
  main(). But, when writing larger programs, we have to divide the program into smaller units which are
  called functions whereby this units will solve only a particular problem in the program. This will make the
  coding and the error correction process more easier.


  In this unit, students will be given detailed explanation on functions, where and how the series of execution
  can be controlled in the functions.


                  /*
                       Using functions in programs
                  */

                  #include <stdio.h>
                  #include<conio.h>
Function
Prototype         float kira_cal(int);

                  main()
                  {
                            clrscr();                 Constant argument
                            int j;
                            float luas_area1;
                            float luas_area2;                                                       Calling a Function

                            luas_area1 = kira_cal(5);
                            printf("Luas bulatan / Circle area            : %.fn", luas_area1);

                            printf("Masukkan nilai jejari / Enter radius : ");
                            scanf("%d", &j);                                                        Variable argument
                            luas_area2 = kira_cal(j);

                            printf("Luas bulatan / Circle area            : %.fn", luas_area2);
                  }
Called Function
                  float kira_cal(int jejari_radius)
                  {
                         float luas_area;
                         luas_area = 3.142 * jejari_radius * jejari_radius;
                         return luas_area;

                  }




  •    The above program shows how a function is called to do a specific task..
  •    In the program the function kira_cal(int) is used to calculate the area of a circle.
  •    The program shows two ways of passing the value to the function which is, using constant argument
       and variable parameter.
  •    Function kira_cal(int) will receive this value and do the mathematical operation and find the area of a
       circle. This value will then be returned to main() function to be displayed.




                                                                                                             106
F1001 PROGRAMMING FUNDAMENTALS


Introduction To Functions


Functions
•   It is also known as program block
•   A function is a self-contained program segment that carries out specific, well-defined task such as
    calculations or displaying records..

•   Some functions are built-in routines similar to library function that manipulates number, strings and
    output such as scanf(), printf(), putchar() and so on.

•   User-defined functions are the functions that the user writes.


Example of functions

        Main function                  main()
        Library Function               stdio.h stdlib.h math.h conio.h string.h
        User-defined function          void print()     char *process() int calculate (float a, int b)




Function basics
•   A function definition has two principle components:
    Example:
                                           main()                          head
                                           {
                                                                           body
                                           }

    Head
    •     function name and a set of parentheses [ ( ) ].
    •     The parentheses may or may not contain parameters.

    Body

    •     starts immediately after the closing parentheses of function name must be enclosed by braces
          [ { } ].
    •     Contains one or more statement.


•   Every function must have a name.
•   Function name is created and assigned by the user based on similar rule that is used for naming
    variables.
•   All function names have one set of parentheses immediately after the function name. This helps you
    differentiate them from variables. The parentheses may or may not contain any parameters.



                                                                                                          107
F1001 PROGRAMMING FUNDAMENTALS


•   Braces must enclose the body of each function, starting immediately after the closing parentheses of
    the function name.



User Defined Functions:

Defining User Defined Functions

•   Is a function that is created by the user.
             Syntax:      ReturnDataType functionName(ParameterList)
                          {
                                   /*Any C statements/
                          }



             Where:
                              FunctionName the function’s name
                                       it is
                                        Similar rules for naming the variable will be used for
                                                          naming functions.
                              returnDataType type of the item returned by the function.
                                        data
                              ParameterList           • represents the data type and variable name of the
                                                          parameters.

    1.   Function that does not receive or return any values

         •    The void keyword is optional for user-defined function, which does not returnDataType and
              parameterList.


                      Syntax :

                                                 FunctionName()
                                                 {
                                                         /*function body*/
                                                 }

                      Example :


                          void message ()                               void message (void)
                          {                                       OR    {
                                 printf(“WELCOME”);                            printf(“WELCOME”);
                          }                                             }




    2.   Function that does not receive a value but returns a value.




                                                                                                      108
F1001 PROGRAMMING FUNDAMENTALS


              Syntax :


                                         ReturnDataType functionName( )
                                         {
                                                 /*function body*/
                                                 return value;
                                         }


              Example :


                                  int count ()
                                  {
                                         int a, b, total;

                                          printf(“Enter first number : ”);
                                          scanf(“%d”, &a);
                                          printf(“Enter second number : ”);
                                          scanf(“%d”, &b);

                                          total = a +b;
                                          return total;
                                  }




3.   Function that receives values but returns nothing.


              Syntax :

                                      FunctionName(parameterList)
                                      {
                                              /*function body*/
                                      }

              Example :

                                  void print (int age)
                                  {
                                         printf(“My age is %d years old”, age);
                                  }




4.   Function that receives and returns values.




                                                                                  109
F1001 PROGRAMMING FUNDAMENTALS


                   Syntax :

                                  ReturnDataType functionName(parameterList)
                                  {
                                          /*Function body*/
                                          return value;
                                  }


                   Example :

                                             int count (int a, int b)
                                             {
                                                    int total;
                                                    total = a + b;
                                                    return total;
                                             }




Function Prototype

•   Sometimes the word prototype is refered to as a model.

•   Function prototypes are used to define the user-defined functions before it can be used.


                  Syntax :        ReturnDataType functionName(ParameterList);




•   The simplest way is to rewrite your head of user-defined functions place it before the main() dunction
    and end it with a semicolon ( ; ).


                  Example :              /*function prototype*/
                                         #include <stdio.h>

                                         void message (); /*function
                                         prototype*/

                                         main ()
                                         {
                                                /*main function body*/
                                         }

                                         void message ()
                                         {
                                                /*function body*/
                                         }


•   All functions must match their prototype.
•   Prototype can avoid programming errors.
•   It will be more structured and therefore easier for us to read the code.



                                                                                                      110
F1001 PROGRAMMING FUNDAMENTALS


•   It allows the C compiler to check the syntax of function calls.

•   If you break any prototyping rules, the compiler will show you the syntax errors and you can correct
    it.

•   You should prototype every function in your program except main(). It is done in order to define
    which function that will be executed, their return types and their parameter types.
•   If you write a user defined functions after function main(), you have to declare the function prototype
    before function main().
•   If you write a user defined functions before function main(), the function prototype is not needed.


          Example :
                           /*Usage of functions without function prototype*/

                           #include <stdio.h>

                           void message ()
                           {
                                  /*badan fungsi*/
                           }


                           main ()
                           {
                                     /*badan fungsi main*/
                           }



Calling function and called function
•   The name of your user-defined function must be called following the order of the statements inside the
    body that will be executed first.

•   Generally the primary function that controls functions order calls is named as a calling function.

•   The functions controlled by the calling function is named as the called function.


    Example:

                 #include <stdio.h>

                 void message ();           /*function prototype*/

                 main ()
                 {
                        message ();         /*calling function*/
                 }

                 void message ()     /*called function*/
                 {
                        /*function body*/
                 }




                                                                                                          111
F1001 PROGRAMMING FUNDAMENTALS


•   We can also call function from another function.

    Example :

                    #include <stdio.h>

                    void call();              /*function prototype*/
                    void message ();

                    main ()
                    {
                           call();                     /*calling function*/
                           message();
                    }

                    void call()               /*called function*/
                    {
                           message();         /*calling function*/
                    }

                    void message ()     /* called function*/
                    {
                           /*function body*/
                    }




Passing Values


•   Needed when the value of a local variable need to be transferred to another function.

•   When a local variable is passed from one function to another, this means that you pass an argument
    from the first function to the next.

•   The called function receives a parameter from the function that sends it.



              Function that sends one or           VALUES:                 Function that
                more arguments (local              Local variables         receives the
              variables) to the receiving          or constants            parameters from the
                       function
                                                                           calling function

                 Calling Function                                            Called Function
                 Send : Argument                                             (Receiving Function)
                                                                             Receive : Parameter




                                                                                                    112
F1001 PROGRAMMING FUNDAMENTALS



Passing by Value (by copy)


•   Describes how the arguments are passed to receiving function.

•   When an argument (local variable) is passed by value, the data item is copied to the function.

•   Any alteration made to the data item within the function, will not give any changes to the calling
    function.
    Example :

            /*Passing by values*/
            #include <stdio.h>

            void addition (int, int);          /*function prototype consists by return parameter
                                                                List*/

            main()                       /*calling function*/
            {
                      int A = 3, B = 2;
                      addition (A, B);       /*calling function with argument*/
            }

            void addition (int first, int second) /*called function with parameter*/
            {
                   int product;
                   product = first + second;
                   printf(“%d + %d = %d”, first, second, product);
            }




                  Output :




•   In the above example value A and B are arguments that are sent too the called function (void addition).
    The called function (void addition) will receive int first and int second as parameter.
•   The number of arguments used to call a function must be similar to the number of parameters listed in
    the function prototype.
•   The order of arguments in the list shows the correspondence. The first argument corresponds to the
    first parameter; the second argument corresponds to the second parameter, and so on.
•   Each argument must be of data type that of the parameter that corresponds to it.
•   The argument data type (calling function) must be the same as the parameters’ data type ( called
    function ).




                                                                                                         113
F1001 PROGRAMMING FUNDAMENTALS


Examples of Passing By Value

Passing by value is a method of passing an argument in which the original value is left unaltered no matter
how it is changed inside the function.
From the example below, note that passing by value method will not change the original value of A and B,
after the swap function is executed.

 #include <stdio.h>

 void swap(int x, int y)
 {
   int temp = x;
   x = y;
   y = temp;
 }

 int main()
 {
   int A, B;
   printf("nA ? :");
   scanf("%d",&A);
   printf("nB ? :");
   scanf("%d", &B);
   printf("The value of       A before calling swap() : %dn", A);
   printf("The value of       B before calling swap() : %dn", B);
   swap(A, B);
   printf("The value of       A after calling swap() : %dn", A);
   printf("The value of       B after calling swap() : %dn", B);
   return 0;
 }




We declare the variables A and B. Therefore in memory we have space to retain two pieces of information.
        A                      B


We take input from the keyboard.

        A           2          B          3



When A and B are passed to the swap() function copies are made for x and y.

        A           2          B          3

        x           2          y          3



We then perform the statements in the body, swapping the copies.

        A           2          B          3               Note that after the swap has
                                                          occurred, the original values of A
        x           3                     2               and B are retained.
                               y




                                                                                                       114
F1001 PROGRAMMING FUNDAMENTALS


Passing by Address (by reference)


•   When an argument (local variable) is passed by address, the address of a data item is passed to the
    called function.
•   The contents of that address can be accessed freely.
•   Any change made to the data item will be recognized in both the called function and the calling
    function. This means that the user have an ability to change the value in the called function and keep
    those changes in effect in the calling function.


        Example :

          /*Penghantaran dengan alamat*/
          #include <stdio.h>

          void change (int *);

          void main ()
          {                                                                              Must be declared
                 int local = 3;                                                          with an asterisk
                 change (&local);
          }

          void change (int *p)
          {
                 printf (“The value that you send is %d”, *p);
          }




                                 Output :




                                                                                                       115
F1001 PROGRAMMING FUNDAMENTALS


Example of Passing By Reference

Passing by reference is a method of passing an argument that allows the called function to refer to the
memory holding the original value of the argument. This means that values changed in the called function
will alter the original value in the calling function.

  #include <stdio.h>

  void swap(int *x, int *y)
  {
    int temp = *x;
    *x = *y;
    *y = temp;
  }

  int main()
  {
    int A, B;
    printf("nA ? :");
    scanf("%d",&A);
    printf("nB ? :");
    scanf("%d", &B);
    printf("The value of       A before calling swap() : %dn", A);
    printf("The value of       B before calling swap() : %dn", B);
    swap(&A, &B);
    printf("The value of       A after calling swap() : %dn", A);
    printf("The value of       B after calling swap() : %dn", B);
    return 0;
  }



With this example we see that the actual values are swapped within the function. Note how we indicate
that we want to pass by reference: we do so with the ampersand (&) between the data type and the variable
name. We declare the variables A and B. Therefore in memory we have space to retain two pieces of
information just as before.
                                  A                          B

We take input from the keyboard.
                             A                2              B       3



When A and B are passed to the swap() function x and y point to the same space in memory.
                                        x                      y


                                  A           2              B       3

We then perform the statements in the body, swapping the originals.
                                              x                      y


                                  A           3              B       2

After we return from the function, we are left with:

                                                                             The result is that the values are
                              A           3              B       2
                                                                             swapped appropriately.

                                                                                                          116
F1001 PROGRAMMING FUNDAMENTALS



Return Values


•   Returns data from a receiving function (called function) to its calling function by putting the return
    value after the return statement.


                  Syntax :              return value;



                                               Returns Value

                        Calling                                               Called



                  Example :


                          #include <stdio.h>

    Value which is        float cal (int, int);
    returned from
                          void main()
      the called
                          {
      function is                int s, t;
     assigned to a               float a;

                                    printf(“Please Enter Two Number ”);
                                    scanf(“%d %d”, &s, &t);
                                    a = cal(s, t);
                                    printf(“Average of two numbers is : %.2f”, a);
                          }

    Return Data           float cal (int num1, int num2)
                          {
    Type
                                 float avg;

                                    avg = (float)(num1 + num2) / 2;
                                    return avg;                                        Returns a value
                          }




                               Output :




                                                                                                         117
F1001 PROGRAMMING FUNDAMENTALS




                                        #include <stdio.h>

                                        char* change ();

                                        void main ()
NOTES                                   {
                                               char *a;
           Return value is assigned
                                                  a = change ();
1.     Do not a
           to return global variables because their values are already known through the code.
                                                  printf("The word is : %s ", a);
                                      }
     Even though a function can receive more than one parameter, it can return one single value to the
       calling function. IfType want to return more than a ()
             Return Data you             char* change value, you must pass the value by address.
                                        {
      Example :                                  char *word = "Love";
                                                                                             Returns the
                                                 return (word);                             value“Love”
                                        }




                                                 Output :




                                                                                                           118

More Related Content

What's hot

C function presentation
C function presentationC function presentation
C function presentation
Touhidul Shawan
 
C functions
C functionsC functions
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functions
Swapnil Yadav
 
Function in c
Function in cFunction in c
Function in c
savitamhaske
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
imtiazalijoono
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
Praveen M Jigajinni
 
Functions1
Functions1Functions1
Functions1
DrUjwala1
 
functions in C and types
functions in C and typesfunctions in C and types
functions in C and types
mubashir farooq
 
Python functions
Python functionsPython functions
Python functions
Prof. Dr. K. Adisesha
 
Recursion in c
Recursion in cRecursion in c
Recursion in c
Saket Pathak
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
4. function
4. function4. function
4. function
Shankar Gangaju
 
All About ... Functions
All About ... FunctionsAll About ... Functions
All About ... Functions
Michal Bigos
 
Pointers and call by value, reference, address in C
Pointers and call by value, reference, address in CPointers and call by value, reference, address in C
Pointers and call by value, reference, address in C
Syed Mustafa
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
Harendra Singh
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
v_jk
 
User defined functions
User defined functionsUser defined functions
User defined functions
Rokonuzzaman Rony
 

What's hot (20)

Functions
FunctionsFunctions
Functions
 
C function presentation
C function presentationC function presentation
C function presentation
 
C functions
C functionsC functions
C functions
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functions
 
Function in c
Function in cFunction in c
Function in c
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
 
Functions1
Functions1Functions1
Functions1
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
functions in C and types
functions in C and typesfunctions in C and types
functions in C and types
 
Python functions
Python functionsPython functions
Python functions
 
Recursion in c
Recursion in cRecursion in c
Recursion in c
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
4. function
4. function4. function
4. function
 
All About ... Functions
All About ... FunctionsAll About ... Functions
All About ... Functions
 
Pointers and call by value, reference, address in C
Pointers and call by value, reference, address in CPointers and call by value, reference, address in C
Pointers and call by value, reference, address in C
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
User defined functions
User defined functionsUser defined functions
User defined functions
 

Viewers also liked

Innerproductspaces 151013072051-lva1-app6892 (1)
Innerproductspaces 151013072051-lva1-app6892 (1)Innerproductspaces 151013072051-lva1-app6892 (1)
Innerproductspaces 151013072051-lva1-app6892 (1)
Himanshi Upadhyay
 
Inner product
Inner productInner product
Inner product
Dhrupal Patel
 
How to use url parameters in webmaster tools
How to use url parameters in webmaster toolsHow to use url parameters in webmaster tools
How to use url parameters in webmaster tools
CgColors
 
Lecture 9 dim & rank - 4-5 & 4-6
Lecture 9   dim & rank -  4-5 & 4-6Lecture 9   dim & rank -  4-5 & 4-6
Lecture 9 dim & rank - 4-5 & 4-6
njit-ronbrown
 
Inner product spaces
Inner product spacesInner product spaces
Inner product spaces
gidc engineering college
 
Inner product spaces
Inner product spacesInner product spaces
Inner product spaces
gidc engineering college
 
Lecture 13 gram-schmidt inner product spaces - 6.4 6.7
Lecture 13   gram-schmidt  inner product spaces - 6.4 6.7Lecture 13   gram-schmidt  inner product spaces - 6.4 6.7
Lecture 13 gram-schmidt inner product spaces - 6.4 6.7
njit-ronbrown
 

Viewers also liked (7)

Innerproductspaces 151013072051-lva1-app6892 (1)
Innerproductspaces 151013072051-lva1-app6892 (1)Innerproductspaces 151013072051-lva1-app6892 (1)
Innerproductspaces 151013072051-lva1-app6892 (1)
 
Inner product
Inner productInner product
Inner product
 
How to use url parameters in webmaster tools
How to use url parameters in webmaster toolsHow to use url parameters in webmaster tools
How to use url parameters in webmaster tools
 
Lecture 9 dim & rank - 4-5 & 4-6
Lecture 9   dim & rank -  4-5 & 4-6Lecture 9   dim & rank -  4-5 & 4-6
Lecture 9 dim & rank - 4-5 & 4-6
 
Inner product spaces
Inner product spacesInner product spaces
Inner product spaces
 
Inner product spaces
Inner product spacesInner product spaces
Inner product spaces
 
Lecture 13 gram-schmidt inner product spaces - 6.4 6.7
Lecture 13   gram-schmidt  inner product spaces - 6.4 6.7Lecture 13   gram-schmidt  inner product spaces - 6.4 6.7
Lecture 13 gram-schmidt inner product spaces - 6.4 6.7
 

Similar to Unit 8

Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
KhurramKhan173
 
Function
FunctionFunction
Function
Saniati
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
SangeetaBorde3
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
UMA PARAMESWARI
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
ArshiniGubbala3
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
sangeeta borde
 
Functions
FunctionsFunctions
Functions in c
Functions in cFunctions in c
Functions in c
SunithaVesalpu
 
Function
Function Function
Functions
Functions Functions
Functions
Dr.Subha Krishna
 
Function C programming
Function C programmingFunction C programming
Function C programming
Appili Vamsi Krishna
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
Sampath Kumar
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
sameermhr345
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
vekariyakashyap
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
Venkatesh Goud
 
C function
C functionC function
C function
thirumalaikumar3
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptx
KarthikSivagnanam2
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
NirmalaShinde3
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
kavitha muneeshwaran
 

Similar to Unit 8 (20)

Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 
Function
FunctionFunction
Function
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
Functions
FunctionsFunctions
Functions
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Function
Function Function
Function
 
Functions
Functions Functions
Functions
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
C function
C functionC function
C function
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptx
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
 

More from rohassanie

Course outline FP202 - Dis 2012
Course outline FP202 - Dis 2012Course outline FP202 - Dis 2012
Course outline FP202 - Dis 2012rohassanie
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6rohassanie
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2rohassanie
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2rohassanie
 
FP 202 - Chapter 5
FP 202 - Chapter 5FP 202 - Chapter 5
FP 202 - Chapter 5rohassanie
 
Chapter 3 part 2
Chapter 3 part 2Chapter 3 part 2
Chapter 3 part 2rohassanie
 
Chapter 3 part 1
Chapter 3 part 1Chapter 3 part 1
Chapter 3 part 1rohassanie
 
FP 202 Chapter 2 - Part 3
FP 202 Chapter 2 - Part 3FP 202 Chapter 2 - Part 3
FP 202 Chapter 2 - Part 3rohassanie
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3rohassanie
 
FP 201 Unit 2 - Part 2
FP 201 Unit 2 - Part 2FP 201 Unit 2 - Part 2
FP 201 Unit 2 - Part 2rohassanie
 
Chapter 2 (Part 2)
Chapter 2 (Part 2) Chapter 2 (Part 2)
Chapter 2 (Part 2) rohassanie
 
Labsheet 7 FP 201
Labsheet 7 FP 201Labsheet 7 FP 201
Labsheet 7 FP 201rohassanie
 
Labsheet 6 - FP 201
Labsheet 6 - FP 201Labsheet 6 - FP 201
Labsheet 6 - FP 201rohassanie
 
Jadual Waktu Sesi JUN 2012
Jadual Waktu Sesi JUN 2012Jadual Waktu Sesi JUN 2012
Jadual Waktu Sesi JUN 2012rohassanie
 
Chapter 2 part 1
Chapter 2 part 1Chapter 2 part 1
Chapter 2 part 1rohassanie
 
FP 201 Unit 3
FP 201 Unit 3 FP 201 Unit 3
FP 201 Unit 3 rohassanie
 

More from rohassanie (20)

Course outline FP202 - Dis 2012
Course outline FP202 - Dis 2012Course outline FP202 - Dis 2012
Course outline FP202 - Dis 2012
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
FP 202 - Chapter 5
FP 202 - Chapter 5FP 202 - Chapter 5
FP 202 - Chapter 5
 
Chapter 3 part 2
Chapter 3 part 2Chapter 3 part 2
Chapter 3 part 2
 
Chapter 3 part 1
Chapter 3 part 1Chapter 3 part 1
Chapter 3 part 1
 
FP 202 Chapter 2 - Part 3
FP 202 Chapter 2 - Part 3FP 202 Chapter 2 - Part 3
FP 202 Chapter 2 - Part 3
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3
 
FP 201 Unit 2 - Part 2
FP 201 Unit 2 - Part 2FP 201 Unit 2 - Part 2
FP 201 Unit 2 - Part 2
 
Lab ex 1
Lab ex 1Lab ex 1
Lab ex 1
 
Chapter 2 (Part 2)
Chapter 2 (Part 2) Chapter 2 (Part 2)
Chapter 2 (Part 2)
 
Labsheet 7 FP 201
Labsheet 7 FP 201Labsheet 7 FP 201
Labsheet 7 FP 201
 
Labsheet 6 - FP 201
Labsheet 6 - FP 201Labsheet 6 - FP 201
Labsheet 6 - FP 201
 
Jadual Waktu Sesi JUN 2012
Jadual Waktu Sesi JUN 2012Jadual Waktu Sesi JUN 2012
Jadual Waktu Sesi JUN 2012
 
Labsheet 5
Labsheet 5Labsheet 5
Labsheet 5
 
Labsheet 4
Labsheet 4Labsheet 4
Labsheet 4
 
Chapter 2 part 1
Chapter 2 part 1Chapter 2 part 1
Chapter 2 part 1
 
FP 201 Unit 3
FP 201 Unit 3 FP 201 Unit 3
FP 201 Unit 3
 

Recently uploaded

Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 

Recently uploaded (20)

Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 

Unit 8

  • 1. F1001 PROGRAMMING FUNDAMENTALS UNIT 8 FUNCTION  Concepts of Functions  User-defined Functions 105
  • 2. F1001 PROGRAMMING FUNDAMENTALS INTRODUCTION So far, in the previous unit, students only use one function in their program which is the main function main(). But, when writing larger programs, we have to divide the program into smaller units which are called functions whereby this units will solve only a particular problem in the program. This will make the coding and the error correction process more easier. In this unit, students will be given detailed explanation on functions, where and how the series of execution can be controlled in the functions. /* Using functions in programs */ #include <stdio.h> #include<conio.h> Function Prototype float kira_cal(int); main() { clrscr(); Constant argument int j; float luas_area1; float luas_area2; Calling a Function luas_area1 = kira_cal(5); printf("Luas bulatan / Circle area : %.fn", luas_area1); printf("Masukkan nilai jejari / Enter radius : "); scanf("%d", &j); Variable argument luas_area2 = kira_cal(j); printf("Luas bulatan / Circle area : %.fn", luas_area2); } Called Function float kira_cal(int jejari_radius) { float luas_area; luas_area = 3.142 * jejari_radius * jejari_radius; return luas_area; } • The above program shows how a function is called to do a specific task.. • In the program the function kira_cal(int) is used to calculate the area of a circle. • The program shows two ways of passing the value to the function which is, using constant argument and variable parameter. • Function kira_cal(int) will receive this value and do the mathematical operation and find the area of a circle. This value will then be returned to main() function to be displayed. 106
  • 3. F1001 PROGRAMMING FUNDAMENTALS Introduction To Functions Functions • It is also known as program block • A function is a self-contained program segment that carries out specific, well-defined task such as calculations or displaying records.. • Some functions are built-in routines similar to library function that manipulates number, strings and output such as scanf(), printf(), putchar() and so on. • User-defined functions are the functions that the user writes. Example of functions Main function main() Library Function stdio.h stdlib.h math.h conio.h string.h User-defined function void print() char *process() int calculate (float a, int b) Function basics • A function definition has two principle components: Example: main() head { body } Head • function name and a set of parentheses [ ( ) ]. • The parentheses may or may not contain parameters. Body • starts immediately after the closing parentheses of function name must be enclosed by braces [ { } ]. • Contains one or more statement. • Every function must have a name. • Function name is created and assigned by the user based on similar rule that is used for naming variables. • All function names have one set of parentheses immediately after the function name. This helps you differentiate them from variables. The parentheses may or may not contain any parameters. 107
  • 4. F1001 PROGRAMMING FUNDAMENTALS • Braces must enclose the body of each function, starting immediately after the closing parentheses of the function name. User Defined Functions: Defining User Defined Functions • Is a function that is created by the user. Syntax: ReturnDataType functionName(ParameterList) { /*Any C statements/ } Where: FunctionName the function’s name it is Similar rules for naming the variable will be used for naming functions. returnDataType type of the item returned by the function. data ParameterList • represents the data type and variable name of the parameters. 1. Function that does not receive or return any values • The void keyword is optional for user-defined function, which does not returnDataType and parameterList. Syntax : FunctionName() { /*function body*/ } Example : void message () void message (void) { OR { printf(“WELCOME”); printf(“WELCOME”); } } 2. Function that does not receive a value but returns a value. 108
  • 5. F1001 PROGRAMMING FUNDAMENTALS Syntax : ReturnDataType functionName( ) { /*function body*/ return value; } Example : int count () { int a, b, total; printf(“Enter first number : ”); scanf(“%d”, &a); printf(“Enter second number : ”); scanf(“%d”, &b); total = a +b; return total; } 3. Function that receives values but returns nothing. Syntax : FunctionName(parameterList) { /*function body*/ } Example : void print (int age) { printf(“My age is %d years old”, age); } 4. Function that receives and returns values. 109
  • 6. F1001 PROGRAMMING FUNDAMENTALS Syntax : ReturnDataType functionName(parameterList) { /*Function body*/ return value; } Example : int count (int a, int b) { int total; total = a + b; return total; } Function Prototype • Sometimes the word prototype is refered to as a model. • Function prototypes are used to define the user-defined functions before it can be used. Syntax : ReturnDataType functionName(ParameterList); • The simplest way is to rewrite your head of user-defined functions place it before the main() dunction and end it with a semicolon ( ; ). Example : /*function prototype*/ #include <stdio.h> void message (); /*function prototype*/ main () { /*main function body*/ } void message () { /*function body*/ } • All functions must match their prototype. • Prototype can avoid programming errors. • It will be more structured and therefore easier for us to read the code. 110
  • 7. F1001 PROGRAMMING FUNDAMENTALS • It allows the C compiler to check the syntax of function calls. • If you break any prototyping rules, the compiler will show you the syntax errors and you can correct it. • You should prototype every function in your program except main(). It is done in order to define which function that will be executed, their return types and their parameter types. • If you write a user defined functions after function main(), you have to declare the function prototype before function main(). • If you write a user defined functions before function main(), the function prototype is not needed. Example : /*Usage of functions without function prototype*/ #include <stdio.h> void message () { /*badan fungsi*/ } main () { /*badan fungsi main*/ } Calling function and called function • The name of your user-defined function must be called following the order of the statements inside the body that will be executed first. • Generally the primary function that controls functions order calls is named as a calling function. • The functions controlled by the calling function is named as the called function. Example: #include <stdio.h> void message (); /*function prototype*/ main () { message (); /*calling function*/ } void message () /*called function*/ { /*function body*/ } 111
  • 8. F1001 PROGRAMMING FUNDAMENTALS • We can also call function from another function. Example : #include <stdio.h> void call(); /*function prototype*/ void message (); main () { call(); /*calling function*/ message(); } void call() /*called function*/ { message(); /*calling function*/ } void message () /* called function*/ { /*function body*/ } Passing Values • Needed when the value of a local variable need to be transferred to another function. • When a local variable is passed from one function to another, this means that you pass an argument from the first function to the next. • The called function receives a parameter from the function that sends it. Function that sends one or VALUES: Function that more arguments (local Local variables receives the variables) to the receiving or constants parameters from the function calling function Calling Function Called Function Send : Argument (Receiving Function) Receive : Parameter 112
  • 9. F1001 PROGRAMMING FUNDAMENTALS Passing by Value (by copy) • Describes how the arguments are passed to receiving function. • When an argument (local variable) is passed by value, the data item is copied to the function. • Any alteration made to the data item within the function, will not give any changes to the calling function. Example : /*Passing by values*/ #include <stdio.h> void addition (int, int); /*function prototype consists by return parameter List*/ main() /*calling function*/ { int A = 3, B = 2; addition (A, B); /*calling function with argument*/ } void addition (int first, int second) /*called function with parameter*/ { int product; product = first + second; printf(“%d + %d = %d”, first, second, product); } Output : • In the above example value A and B are arguments that are sent too the called function (void addition). The called function (void addition) will receive int first and int second as parameter. • The number of arguments used to call a function must be similar to the number of parameters listed in the function prototype. • The order of arguments in the list shows the correspondence. The first argument corresponds to the first parameter; the second argument corresponds to the second parameter, and so on. • Each argument must be of data type that of the parameter that corresponds to it. • The argument data type (calling function) must be the same as the parameters’ data type ( called function ). 113
  • 10. F1001 PROGRAMMING FUNDAMENTALS Examples of Passing By Value Passing by value is a method of passing an argument in which the original value is left unaltered no matter how it is changed inside the function. From the example below, note that passing by value method will not change the original value of A and B, after the swap function is executed. #include <stdio.h> void swap(int x, int y) { int temp = x; x = y; y = temp; } int main() { int A, B; printf("nA ? :"); scanf("%d",&A); printf("nB ? :"); scanf("%d", &B); printf("The value of A before calling swap() : %dn", A); printf("The value of B before calling swap() : %dn", B); swap(A, B); printf("The value of A after calling swap() : %dn", A); printf("The value of B after calling swap() : %dn", B); return 0; } We declare the variables A and B. Therefore in memory we have space to retain two pieces of information. A B We take input from the keyboard. A 2 B 3 When A and B are passed to the swap() function copies are made for x and y. A 2 B 3 x 2 y 3 We then perform the statements in the body, swapping the copies. A 2 B 3 Note that after the swap has occurred, the original values of A x 3 2 and B are retained. y 114
  • 11. F1001 PROGRAMMING FUNDAMENTALS Passing by Address (by reference) • When an argument (local variable) is passed by address, the address of a data item is passed to the called function. • The contents of that address can be accessed freely. • Any change made to the data item will be recognized in both the called function and the calling function. This means that the user have an ability to change the value in the called function and keep those changes in effect in the calling function. Example : /*Penghantaran dengan alamat*/ #include <stdio.h> void change (int *); void main () { Must be declared int local = 3; with an asterisk change (&local); } void change (int *p) { printf (“The value that you send is %d”, *p); } Output : 115
  • 12. F1001 PROGRAMMING FUNDAMENTALS Example of Passing By Reference Passing by reference is a method of passing an argument that allows the called function to refer to the memory holding the original value of the argument. This means that values changed in the called function will alter the original value in the calling function. #include <stdio.h> void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } int main() { int A, B; printf("nA ? :"); scanf("%d",&A); printf("nB ? :"); scanf("%d", &B); printf("The value of A before calling swap() : %dn", A); printf("The value of B before calling swap() : %dn", B); swap(&A, &B); printf("The value of A after calling swap() : %dn", A); printf("The value of B after calling swap() : %dn", B); return 0; } With this example we see that the actual values are swapped within the function. Note how we indicate that we want to pass by reference: we do so with the ampersand (&) between the data type and the variable name. We declare the variables A and B. Therefore in memory we have space to retain two pieces of information just as before. A B We take input from the keyboard. A 2 B 3 When A and B are passed to the swap() function x and y point to the same space in memory. x y A 2 B 3 We then perform the statements in the body, swapping the originals. x y A 3 B 2 After we return from the function, we are left with: The result is that the values are A 3 B 2 swapped appropriately. 116
  • 13. F1001 PROGRAMMING FUNDAMENTALS Return Values • Returns data from a receiving function (called function) to its calling function by putting the return value after the return statement. Syntax : return value; Returns Value Calling Called Example : #include <stdio.h> Value which is float cal (int, int); returned from void main() the called { function is int s, t; assigned to a float a; printf(“Please Enter Two Number ”); scanf(“%d %d”, &s, &t); a = cal(s, t); printf(“Average of two numbers is : %.2f”, a); } Return Data float cal (int num1, int num2) { Type float avg; avg = (float)(num1 + num2) / 2; return avg; Returns a value } Output : 117
  • 14. F1001 PROGRAMMING FUNDAMENTALS #include <stdio.h> char* change (); void main () NOTES { char *a; Return value is assigned a = change (); 1. Do not a to return global variables because their values are already known through the code. printf("The word is : %s ", a); } Even though a function can receive more than one parameter, it can return one single value to the calling function. IfType want to return more than a () Return Data you char* change value, you must pass the value by address. { Example : char *word = "Love"; Returns the return (word); value“Love” } Output : 118