Programming C: Posts 8 – Functions in C

1. At the beginning of the function

Enter and run 2 examples, observe the results and comments.

Example 1:

// e.g 1 about function in C - code by nguyenvanquan7826

#include <stdio.h>

void loiKhuyen()
{
    printf("Neu hoc nghiem tuc va cham chi thi ban se thay:\n");
    printf("Khong co viec gi kho\n");
    printf("Chi so long khong ben\n");
    printf("Dao nui va lap bien\n");
    printf("Quyet chi at lam nen\n");
    printf("\n");
}

int main()
{
    printf("Hoc bai nay kho qua!\n");
    loiKhuyen();

    printf("Hoc C kho qua!\n");
    loiKhuyen();

    return 0;
}

Result:

Lessons learned through this warehouse!
Neu serious study and hard work, you will see:
Nothing warehouse
Chi ben so long khong
Lap great dao va bien
Determined at nen lam

Hoc C storage over!
Neu serious study and hard work, you will see:
Nothing warehouse
Chi ben so long khong
Lap great dao va bien
Determined at nen lam

Example 2:

// e.g 2 about function in C - code by nguyenvanquan7826

#include <stdio.h>

void vechu(char chu, int soluong)
{
    int i;
    for (i = 0; i < soluong; i++) {
        printf("%c", chu);
    }
    printf("\n");
}

int main()
{
    vechu('h', 20);
    vechu('a', 30);
    vechu('h', 12);
    vechu('a', 5);
    vechu('p', 10);

    return 0;
}

Result:

gggggggggggggggggg
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
hhhhhhhhhhhh
AAAAA
pppppppppp

If the program has a number of command, or jobs that have the same or similar form to repeated several times in different positions, to avoid wasting time and effort to copy the command sequence that we should organize and build it into a piece of command, where the program needs to do the job that they just call that command only segment. The paragraph that called the function command.

Ham is a piece of implementing a block command job is repeated several times while running the program, or use a separate block specific work to support complex programs.

In the example 1: Have 2 program, 1 main program: main and 1 additional programs: loiKhuyen no parameters and returns no value to the data type of the function is declared as void. Both the main and loiKhuyen are called function. The main function is the function executed and run our entire program. Ham loiKhuyen done some work (output 5 the words above). In the main function we have 2 place call loiKhuyen();

In the example 2: Similar examples 1, it includes 2 jaw, 1 The main function is main and 1 subroutine, but subroutine is Vecht(chu char, int soluong); have 2 parameter form is cycle of type char and soluong of type int. Ham vechu no return value data type of the function should be declared as void. In the main function we have 3 vechu function calls with parameters actually turn as the program on.

2. The operating principle of the function

  • When the machine meets function calls anywhere in the function that is performed starting, will immediately leave the area to go to the function is called.
  • If the function parameters, the machine will perform real communication parameters for the corresponding formal parameter in the function.
  • Machine began performing in turn the statements in the function body until reuturn order or check } of the jaw, stop escape function returns the program to call it and make statements of this program.
  • If the function returns a value, the value of the expression in the function's return value of the function.

Noted: The function declaration void vechu(chu char, int soluong) then cycle and quantity parameters form, even when calling Vecht(‘h’, 20); then ‘h’ and 20 parameters really.

3. The structure of the jaw

We have structured the following function declaration:

KieuTraVe TenHam(Cac tham so)
{
    ThanHam;
}

The function name is set in the variable naming rules.

4. Examples of functions

Example 1: The function does not return value

Above we have 2 for example the opening are not a function returns a value and declared return type is void.

Example 2: Valuable function returns

Construction of functions n! and few expressions factorial. know n! = 1.2.3…n

// e.g about function in C - code by nguyenvanquan7826

#include <stdio.h>

long giaiThua(int n) 
{
    long gt = 1;
    int i;
    for (i = 2; i <= n; i++)
    {
        gt *= i; // <=> gt = gt * i
    }
    return gt;
}

int main()
{
    printf("5! = %ld \n", giaiThua(5));
    printf("6! + 1 = %ld \n", giaiThua(6) + 1);
    return 0;
}

Result:

5! = 120
6! + 1 = 721

Do n! can be a fairly large integer function returns a value of type long (greater than type int – Review the data types in C). Order return gt ie variable returns gt, gt must have the same type of data with the data type of the function (and the dragon).

In this example giaiThua function returns the factorial of the number n is passed on so it can be considered as 1 variables and used in the expression, always used to print the results. When meeting functions anywhere, it will transmit 1 parameters corresponding to the function and returns the return value of the last command.

Example 3: Function test

Building inspection function there are some nice some not? Beautiful number is the number divisible 2 and divisible 5.

To do this, we need to determine is this function check a number is something, therefore, we need to return the correct value (1) or wrong (0). So the function returns integer.

// e.g about function in C - code by nguyenvanquan7826
#include <stdio.h>

int kiemTraChiaHet(int n)
{
    if(n % 2 == 0 && n % 5 == 0)
    {
        return 1;
    }
    return 0;
}

int main()
{
    int x;

    printf("Nhap x = ");
    scanf("%d", &x);

    if( kiemTraChiaHet(x) == 0)
    {
        printf("day khong phai so dep @@\n");
    } else {
        printf("day la so dep !!!\n");
    }

    return 0;
}

In function kiemTraChiaHet, when n is divisible 2 and 5, it will execute the command return 1, While executing this function ie end, do not do anything in this function again whether or not the command left behind. If the number n is not divisible 2 and 5 it will execute the command return 0.

Example 4: These functions call each other

// e.g about function in C - code by nguyenvanquan7826

#include <stdio.h>

int max2(int a, int b) 
{
    return a > b ? a : b;
}

int max3(int a, int b, int c) 
{
    return max2( max2(a, b), c);
}

int main()
{
    int a = 7, b = 13, c = 4;
    printf("So lon nhat la %d \n", max3(a, b, c));
    return 0;
}

Result:

Highest 13

In this example we build 2 function to find the largest number of 2 number and 3 number. In MAX2 function we use Conditional operators to find the largest number of 2 number. In MAX3 function was to call MAX2 2 time to find the largest number in a, b and took some finding was compared to c find the largest number.

Attention: The function declaration after the function is called before it was declared, but the function is not declared before calling the function declarations. Ie in the example above, if we build MAX2 function in later levels, the machine will error MAX3. To remedy this we usually declare the function in the program then we define functions anywhere in the program are an example to us:

Example 5: Function declaration before the function definition

// e.g about function in C - code by nguyenvanquan7826
#include <stdio.h>

// khai bao cac ham max2, max3, max4
int max2(int a, int b);
int max3(int a, int b, int c);
int max4(int a, int b, int c, int d);

int max3(int a, int b, int c) {
    return max2( max2(a, b), c);
}

int max2(int a, int b) {
    return a > b ? a : b;
}

int main() 
{
    int a = 7, b = 13, c = 4, d = 16;
    printf("So lon nhat trong a, b, c la %d\n", max3(a, b, c));
    printf("So lon nhat trong a, b, c, d la %d\n", max4(a, b, c, d));
    return 0;
}

int max4(int a, int b, int c, int d) 
{
    return max2( max2(a, b), max2(c, d) );
}

Result:

The largest number in a, b, the c 13
The largest number in a, b, c, of the 16

When working we should declare the function like this before, and define the following. Thus we will avoid some errors when we want to use the functions in each.

I already know the function can call each other and function can also call itself, that we use recursive function.

Example 6: Recursive function

I knew the formula n! = 1.2.3…n. However one can also write n! = (A-1)!.n. In this notation to calculate n! we need calculation (A-1)!. So it could be called the expression and function recursively, too, callback function itself is called a recursive function.

// e.g about function in C - code by nguyenvanquan7826
#include <stdio.h>

int giaiThua(int n) 
{
    if(n == 0) return 1; // dieu kien dung
    return giaiThua(n-1) * n; // loi goi chinh no
}

int main() {
    int n = 5;
    printf("%d! = %d",n, giaiThua(n));
    return 0;
}

Noted in recursive functions always 2 factor is the condition stops and calls itself.

Example 7: Use the navigation #define to define a simple function

#include <stdio.h>

#define tong(x, y) x + y

int main() 
{
    int a = 5, b = 8;
    printf("%d + %d = %d",a, b, tong(a, b));
    return 0;
}

At this point we have the basic understanding of the function, but there are many more things to say about the function, especially concerning the function arrays and pointers. We will continue to find out them in the next post with arrays and pointers.

Exercise

  1. Write a function to sum S = 1 + 2 +….+n.
  2. Write the check function primes, perfect number.
  3. Enter a sequence of n numbers and announcements should primes, perfect number or not.