Skip to content

[C] Introduction of Functions

Function is an important concept in programming. A function is not a formula (of course it may be), but a block of code that completes a specific function.

Generally, function is a bit like formula: we input something, and the executed result will be generated.

c_function

The advantage of using a function is that if the function we want to achieve will be used repeatedly, then this code only needs to be written a function once, and then if it is necessary to use, just call it.

In addition, dividing different functions into different functions can even improve the readability of the code and make the structure clearer.


Example

The format of function declaration is usually:

return-type function-name(parameter declarations ...) {
    declarations
    statements;
    return result;
}

The following is a function to calculate the power of a numerical value.

#include <stdio.h>


// Function
int power(int base, int n) {
    int ans = base;

    for (int i=0; i<n; ++i) {
        ans = ans * base;
    }

    return ans;
}


// Main
int main() {
    // Init
    int base, n, ans;

    // Case 1
    base = 3;
    n = 3;
    ans = power(base, n);
    printf("Case 1: %d^%d=%d\n", base, n, ans);

    // Case 2
    base = 2;
    n = 10;
    ans = power(base, n);
    printf("Case 2: %d^%d=%d\n", base, n, ans);

    return 0;
}


Output:

Case 1: 3^3=81
Case 2: 2^10=2048

References


Read More

Leave a Reply