C Language Study Notes (9) -- Functions

Source: Internet
Author: User

1 program modularization

 

In the process of program design, most programs are much more complex than the ones we previously designed. The traditional design method is the process of "customizing down and improving gradually. In this process, a major problem is divided into multiple small problems that can be easily solved by layers until each functional module can be independently designed for each individual functional module, finally, all functional modules are organically integrated into a complete program.

 

Example: Calculate the day of the year.

 

The problem can be broken down into: getting input; determining a year or a leap year; determining the total number of days of each month; and obtaining the total number of days;

 

Sample Code:

 

 

# Include "stdio. h"

/* (1) determine the leap year */

Int leap (int year)

{Int flag;

If (year % 4 = 0 & amp; year % 100! = 0 | year % 400 = 0)

Flag = 1;

Else flag = 0;

Return flag;

}

/* (2) calculate the number of days in a month */

Int month_days (int year, int month ){

Int d;

Switch (month ){

Case 1:

Case 3:

Case 5:

Case 7:

Case 8:

Case 10:

Case 12: d = 31; break;

Case 2: d = leap (year )? 29:28; break;/* by calling function compute, the leap year is 29 days, and the year is 28 days */

Default: d = 30; break;

}

Return d;

}

/* (3) Calculate the sum of days. */

Int days (int year, int month, int day ){

Int I, ds = 0;

For (I = 1; I <month; I ++)

Ds = ds + month_days (year, I);/* function days calls the month_days function to calculate the number of days of each month */

Ds = ds + day;

Return ds;

}

/* The main program calls each module to calculate the sum of days */

Void main ()

{Int year, month, day, t_day;

Printf ("input year-month-day: \ n ");

Scanf ("% d-% d", & year, & month, & day );

/* The scanf function is defined by the system as the input module,

The main function can be called directly */

T_day = days (year, month, day);/* calculate the number of days and */

Printf ("% d-% d is % dth day of the year! N ", year, month, day, t_day );

/* The printf function is also defined by the system as the output module,

The main function can be called directly */

}

2. Function Definition

 

2.1 function Introduction: a function is the basic module of a C language program. functions can be classified from the 3 aspects:

 

Function Definition:

 

1. database functions: these functions are provided by the C system and can be called directly without being defined.

 

2. User-Defined Functions: A function compiled by the user can be used only when the type of the called function is described.

 

From the perspective of return values:

 

1. Functions with return values: a function with return values will return an execution result to the caller after being called. This result is the return value. When defining such a function, you should specify the return value type.

 

2. No return value function: A non-return value function is used to complete a specific function. After the function is executed, no function value is returned. If you define a function, the return value of the function is null, that is, void.

 

Data transmission:

 

1. No Parameter Function: no parameters are included in the definition and call of a function. No parameter is transferred between the called and called functions.

 

2. parameter functions: parameters include formal parameters and actual parameters. The parameters in function definition and description are called form parameters. The functions provided during the call are called real parameters.

 

2.2 Function Definition

 

The general format of definition:

 

Type specifier function name (type name format parameter 1, type name format parameter 2 ,.....)

 

{

 

Function body

 

}

 

Function Name: it is a identifier. The name must be meaningful and short. It cannot be duplicated in the same source program file.

 

Type Description: Return Value Type of a value function. void is used to specify that the function has no return value. The return value type can be basic or pointer, struct, or user-defined type.

 

Formal parameters: the parameters used to define a function are called formal parameters. The parameter list describes the type and number of parameters. either of the two methods is correct:

 

Int max (int a, intb ){

 

Return 0;

 

}

 

Int max (a, B)

 

Int a, B ;{

 

Return 0;

 

}

 

Function body: the implementation of specific functions of a function.

 

Sample Code for determining prime numbers by calling a function:

 

 

# Include "math. h"

Main (){

Int n;

Int flag;

Printf ("input n: \ n ");

Scanf ("% d", & n );

Flag = prime (n);/* function call */

If (flag)/* determine the return value */

Printf ("% d is prime. \ n ");

Else printf ("% d is not prime. \ n ");

}

Int prime (int n ){

Int m;

For (m = 2; m <= sqrt (n); m ++)

If (n % m = 0) return 0;

Return 1;

}

3. function call

 

3.1 General Form of function call:

 

Function Name (parameter list );

 

1. function calls with return values:

Int max (int x, int y ){

 

Return x> y? X: y;

 

}

 

Call this function:

 

A = max (a, B );

 

2. Call without return values

 

Void printstart (int n) {// output n asterisks

 

Int I;

 

For (I = 1; I <n; I ++ ){

 

Printf ("*");

 

}

 

}

 

Call this function:

 

Pirntstart (5); // output 5 asterisks

 

3.2 description and prototype of the called Function

 

Except scanf and printf, all system standard functions must be called at the beginning of this file by using the compile preprocessing command # include to include the header file information of the function to this file. Example: # include "stdio. h"

 

If the called function is a user-defined function, in addition to defining the function, the called function should also be declared in the source file where the main call function or the main call function is located, the purpose is to indicate the type of the returned value and the number and type of parameters of the called function, so that the system can check this function when it is called.

 

The general format of declared functions is:

 

Type identifier function name (parameter Type 1, parameter type 2 ,...);

 

The positional relationship between the calling function and the main calling function is divided into three types:

 

1. The call function is in the same file as the main call function, and the main call function is in front of the call function.

 

2. The call function is in the same file as the main call function, and the main call function is behind the call function.

 

3. The called function and the main called function are not in the same file.

 

Example code of three positional relationships

 

1. The called function is located after the main function:

 

 

# Include "stdio. h"

Main () {/* (1) main () before sum */

Int n;

Long p;

Long sum (int);/* function declaration */

Scanf ("% d", & n );

P = sumt (n);/* function call */

Printf ("\ n % ld", p );

}

Long sum (int m) {/* function definition */

Int I;

Long s = 0;

For (I = 1; I <= m; I ++)

S + = I;

Return (s);/* function return */

}

2. The called function is before the main function:

# Include "stdio. h"

Long sum (int m) {/* function definition */

Int I;

Long s = 1;

For (I = 1; I <= m; I ++)

S + = I;

Return (s );

}

Main (){

Int n;

Long p;/* function declaration not required */

Scanf ("% d", & n );

P = sum (n);/* function call */

Printf ("\ n % ld", p );

}

3. The called function is stored in another file. First, we set the sum () function to be stored in fun. c. Compile the declaration of the called function using the include command:

 

# Include "fun. c"

 

Main (){

 

Int n = 7;

 

N = sum (n );

 

}

 

4. parameter transfer

 

4.1 form parameters and actual parameters

 

Data changes in parameter transfer:

 

 

# Include "stdio. h"

Void fun (int num ){

Num = 20;

Printf ("% d \ n", num );

}

Main (){

Int x;

X = 10;

Fun (x);/(call a function that does not return a value */

Printf ("% d \ n", x );

}

Running result:

 

20

 

10

 

Function fun has a parameter variable num. When the main function is called, the value of the real parameter x is transferred to num. In the fun function, although num is changed to 20, the value of x is not affected.

 

The program starts running from main. This is the storage space of x. The initial value is 10. When the fun function is called, it allocates space for the form parameter and accepts the value of the real parameter, the process is transferred to the call function fun for execution, and the variable num is re-assigned to 20. The value of the number of times does not affect the real parameters, and the real parameters are not available in the fun function. After the function call is completed, the parameter space is revoked and the process is returned. This is the value transfer.

 

When a function has multiple parameters, the order in which values of the real parameter list are called is unknown. Different systems may be different, if you want to know the order of evaluation of your system, you can use auto-increment or auto-increment to test the order:

 

 

# Include "stdio. h"

Int f (int a, int B, int c)

{

Int z;

Z = a + B * c;

Return z;

}

Main ()

{

Int x = 3, y;

Y = f (x, x ++, x ++);/* evaluate the real parameters from right to left */

Printf ("% d \ n", y );

}

Running result: 17.

 

4.2 return value of a function: the implementation of a function contains specific functions. Sometimes, after the function is executed, the execution result must be returned to the called function. The result can be expressed by the return value, the return value is implemented using the return statement. The specific format is:

 

Return expression; or return (expression );

 

The function of this statement is to return a value to the main call function, release all space allocated during the execution of the function, end the operation of the called function, and control the process to the main call function.

 

If no return value is returned, use urn; instead.

 

Float fun (int n ){

 

Return n;

 

}

 

Main (){

 

Float x;

 

X = f (20 );

 

Printf ("% f", x );

 

}

 

5. array as a function parameter

 

When an array is passed as a parameter, the system will pass the first address of the array element as a real parameter to the array name represented by the form parameter, that is, the address when the parameter is passed.

 

5.1 One-dimensional array as a parameter: one-dimensional array name indicates the starting address of the element marked as 0 in the array in memory. Assume that array a is stored in the memory starting from the 2000 address, then the value of a is 2000. 2000 is the address value and pointer type data.

 

Sample Code for passing an array as a parameter:

 

 

# Include "stdio. h"

Void input (int a [10], int n) {/* input Function */

Int I;

For (I = 0; I <n; I ++)

Scanf ("% d", & a [I]);

Printf ("\ n ");

}

Int maxa (int a [10], int n) {/* calculate the maximum function */

Int I;

Int m;

M = a [0];

A [1] = 100;

For (I = 1; I <n; I ++)

If (m <a [I]) m = a [I];

Return m;

}

Void print (int a [10], int n) {/* output function */

Int I;

For (I = 0; I <n; I ++)

Printf ("% 4d", a [I]);

Printf ("\ n ");

}

Void main (){

Int B [10];

Int max;

Input (B, 10 );

Max = maxa (B, 10 );

Printf ("array max is % d \ n", max );

Printf ("the array is: \ n ");

Print (B, 10 );

}

Address Transfer means that the form parameter and the real parameter both point to the same address and modify the data on the storage unit.

 

6 nested function call

 

Nested function definitions are not allowed in C language, but nested function calls are allowed, that is, other functions are called in the called function.

 

Program Structure of nested calls:

 

 

Example code:

 

 

# Include "stdio. h"

# Include "math. h"

Int prime (int);/* function declaration */

Void even (int );

Main (){

Int n;

Printf ("Enter n even number (> = 6 ):");

Scanf ("% d", & n );

If (n % 2 = 0 & n> = 6)

Even (n);/* function call statement */

Else

Printf ("The % d isn't even number \ n", n );

}

Void even (int x) {/* Find the prime number function */

Int I;

For (I = 2; I <= x/2; I ++)

If (prime (I)/* call the function to determine the prime number */

If (prime (x-I )){

Printf ("% d = % d + % d \ n", x, I, x-I );}

}

Int prime (int n)/* function for determining prime numbers */

{Int I, k = sqrt (n );

For (I = 2; I <= k; I ++)

If (n % I = 0) return 0;

Return 1;

}

7. recursive call of functions

 

7.1 recursion: directly or indirectly calling a function is recursion.

 

For example:

 

Int f (int x ){

 

Int y;

 

Z = f (y );

 

Return z;

 

}

 

This function is called recursively, but it will run endlessly. This is obviously incorrect. When writing code, you should give the program an exit to exit recursion.

 

8. Exercise

 

1 recursion factorial

 

2. Use the function to compare the size of 4 numbers.

 

3. Implement the print feature.

 

From letthinking's column

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.