SlideShare una empresa de Scribd logo
1 de 14
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

Más contenido relacionado

La actualidad más candente

La actualidad más candente (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
 

Destacado (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 a Unit 8

Similar a 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
 
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
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
 

Más de rohassanie

Course outline FP202 - Dis 2012
Course outline FP202 - Dis 2012Course outline FP202 - Dis 2012
Course outline FP202 - Dis 2012
rohassanie
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
rohassanie
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2
rohassanie
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
rohassanie
 
FP 202 - Chapter 5
FP 202 - Chapter 5FP 202 - Chapter 5
FP 202 - Chapter 5
rohassanie
 
Chapter 3 part 2
Chapter 3 part 2Chapter 3 part 2
Chapter 3 part 2
rohassanie
 
Chapter 3 part 1
Chapter 3 part 1Chapter 3 part 1
Chapter 3 part 1
rohassanie
 
FP 202 Chapter 2 - Part 3
FP 202 Chapter 2 - Part 3FP 202 Chapter 2 - Part 3
FP 202 Chapter 2 - Part 3
rohassanie
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3
rohassanie
 
FP 201 Unit 2 - Part 2
FP 201 Unit 2 - Part 2FP 201 Unit 2 - Part 2
FP 201 Unit 2 - Part 2
rohassanie
 
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 201
rohassanie
 
Labsheet 6 - FP 201
Labsheet 6 - FP 201Labsheet 6 - FP 201
Labsheet 6 - FP 201
rohassanie
 
Jadual Waktu Sesi JUN 2012
Jadual Waktu Sesi JUN 2012Jadual Waktu Sesi JUN 2012
Jadual Waktu Sesi JUN 2012
rohassanie
 
Chapter 2 part 1
Chapter 2 part 1Chapter 2 part 1
Chapter 2 part 1
rohassanie
 
FP 201 Unit 3
FP 201 Unit 3 FP 201 Unit 3
FP 201 Unit 3
rohassanie
 

Más de 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
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

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