Function and Recursion

Function and Recursion

Function

Function --> the purpose is modular programming. To divide the program into several sub-program.

The syntax is : 

<return value type> function_name (parameter(s))
{
   statement(s);
}

Example (to find A + B):

#include <stdio.h>

int sum (int A, int B)
{
    int tambah;
    
    tambah = A + B;
    
    return tambah;
}

int main ()
{    
    int A, B, res;    
    A = 2;    
    B = 2;       
    res = sum(A, B);

    printf("%d\n", res);

    return 0;
}

Recursion

Recursion is a function that calls itself.

Example (to find n factorial):

#include <stdio.h>

int factor (int F)
{
    if (F == 0)
   {
       return 1;
    }
    else if(F == 1)
    {
       return 1;
     }
    
     return F * factor(F-1);
}    

int main ()
{
    int F, res;       
    F = 5;

    res = factor(F);

    printf("%d\n", res);

    return 0;}


Also can use void. Void didn't return any value.

void(parameter(s))
{
   statement(s);
}

Use int if you want to return value.



Princess Jesslyn Lorenza
2201750036

binus.ac.id
skyconnectiva.com

Comments