# #C Programming (II) - 3 ## Function English: Lei KuoLiang nicolaslouis@mail.fcu.edu.tw Chinese(TW): Wang M.H --- ### This week's course catalog 0. Review Function     * Function announcement     * parameters     * Return value 2. C standard library (C standard library)     * math.h --- ## Last week's course review ---- ### 2D Array Declare an int array a of size 3x4 And preset values ```c int a[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; ``` ---- The size of the first dimension can also be omitted when declaring The computer will automatically detect ```c int a[][4] = {{1, 2, 3}, {5, 6, 7, 8}, {9, 10}}; //At this time, a is a 3x4 array. ``` But can't omit the size of the second dimension ```c int a[][] = {{1, 2}, {3, 4}, {5, 6}}; //ERROR!! int b[3][] = {{1, 2}, {3, 4}, {5, 6}}; //ERROR!! ``` ---- Enter the values into the array in sequence, and then output them sequentially ```c int a[5][6]; //Enter in order for(int i = 0; i < 5; i++) for(int j = 0; j < 6; j++) scanf("%d", &a[i][j]); //Sequential output for(int i = 0; i < 5; i++) { for(int j = 0; j < 6; j++) printf("%d ", a[i][j]); printf("\n"); } ``` ---- ### Two-dimensional character array ```c //Declare char str[3][10] = {"Jim", "Hello", "Brian"}; //Enter in order for(int i = 0; i < 3; i++) scanf("%s", str[i]); //Sequential output for(int i = 0; i < 3; i++) printf("%s", str[i]); ``` ---- ### Bubble sorting ```c int num[N]; //After entering the value for(i = N - 1; i > 0; i--) { for(j = 0; j < i; j++) { if(num[j] > num[j + 1]){ //num[j]、num[j + 1]Numerical exchange int tmp = num[j]; num[j] = num[j + 1]; num[j + 1] = tmp; } } } ``` --- ## Function You can use it many times after writing it. ---- Using the function can solve the following problems: 1. The main program is too long 2. Many repetitive program blocks 3. Length is not conducive to debug 4. I want to change the name and think about it. ... ---- Give an example of a homework: ![](https://i.imgur.com/UqDlE36.png) ---- Write a subroutine **print_player** ![](https://i.imgur.com/VU7BJ8S.png) ---- After modification: ![](https://i.imgur.com/4ijhggk.png) --- ### Function Declaration ```c Return value type function name (incoming parameter) { //Calculation...... return Return value; } ``` E.g: ```c int add(int a, int b) { int c = a + b; return c; } ``` ---- In fact, the main program we wrote is a function. ```c int main(void) { //...... return 0; } ``` Compared to the main program, other functions are called subprograms. ---- The subroutine needs to be declared in front of the main program. ```c int add(int a, int b) { int c = a + b; return c; } int main(void) { printf("%d\n", add(3, 4)); return 0; } ``` ---- You can also declare the function first, then define it later. ```c int add(int, int); //Can also add variable names int add (int a, int b); int main(void) { printf("%d\n", add(3, 4)); return 0; } int add(int a, int b) { int c = a + b; return c; } ``` --- ### Parameter ![](https://i.imgur.com/dwJdEtL.png) ---- Parameters can be no, there can be only one, there can be many ---- Case without parameters ```c void printHelloWorld() { printf("Hello World\n"); } ``` Or ```c void printHelloWorld(void) { printf("Hello World\n"); } ``` ---- There is only one parameter ```c int isLeapYear(int year) { //(is a multiple of 4 and not a multiple of 100) or (a multiple of 400) is a leap year if ((!(year % 4) && (year % 100)) || !(year % 400)) return 1; //Otherwise it is a normal year return 0; } ``` ---- Multiple parameters ```c double power(double val, int n) { double result = 1; if(n > 0) for(int i = 0; i < n; i++) result *= val; else for(int i = 0; i > n; i--) result /= val; return result; } ``` ---- The parameters can also be arrays, don't forget to tell the size of the function array (or handle the boundaries of the data) ```c void bubbleSort(int num[], int n) { for(i = n - 1; i > 0; i--) for(j = 0; j < i; j++) if(num[j] > num[j + 1]){ //num[j]、num[j + 1]Numerical exchange int tmp = num[j]; num[j] = num[j + 1]; num[j + 1] = tmp; } } ``` ---- When the parameter is a multi-dimensional array, the size of the array after the second dimension is written (same as the declaration rule of the multi-dimensional array) ```c void functionA(int data[][5]); ``` ```c void functionB(int data[][6][4]); ``` ---- #### Call by value If the argument is a numeric value (int, float, double, char...), then ++ does not affect the value of the original variable when doing a function operation. ```c int add(int a, int b) { a += b;//Will not affect the val1 in main return a; } int main() { int val1 = 5, val2 = 6, val3; val3 = add(val1, val2); printf("val1 = %d\n", val1); printf("val3 = %d\n", val3); } ``` Operation result ``` val1 = 5 val3 = 11 ``` ---- #### Call by reference If the argument is an array, ++ will affect the value of the original variable when doing a function operation. ```c void zeroing(int a[], int n) { for(int i = 0; i < n; i++) a[i] = 0; } int main() { int arr[5] = {1, 2, 3, 4, 5}; zeroing(arr, 5); for(int i = 0; i < 5; i++) printf("%d ", arr[i]); } ``` Operation result ``` 0 0 0 0 0 ``` --- ### Return value ![](https://i.imgur.com/dwJdEtL.png) ---- If the function has a return value (type is not void), add "`return passback value;`" at the end of the function or where you want to end. ```c int isPrime(int num){ if (num == 1) return 0; //End function, return 0 else for (int i = 2; i * i <= num; i++) { if (num % i == 0) return 0; //End function, return 0 } return 1; //End function, return 1 } ``` ---- If the function has no return value (type void), add "`return;`" at the end of the function or where you want to end, or automatically return the braces at the end of the function. ```c //Continue the code of the previous page void printPrime(int max) { if (max < 2) return; //End function for (int i = 2; i <= max; i++) { if(isPrime(i)) printf("%d\n", i); } } //End function ``` ---- Receive return value ```c int square(int n){ return n * n; } int main(){ int a = square(2); int b = square(a); printf("%d\n", square(b)); if(square(b) == 16) printf("4 * 4 = 16\n"); } ``` ---- In fact, EOF is the return value of scanf. ```c while(scanf("%d", %a) != EOF){ //.... } ``` The following is the virtual code of scanf ```c int scanf(const char * Read format,...) { Read the data of the stdin data stream; if(Read the end of the material) return EOF; Store data in variables; return Number of variables stored; } ``` --- ### Exercise one Please complete a subroutine called **maximum** Call maximum(a, b, c), return the largest number after judgment (all use int variables) ``` Sample input: 3 1 2 7 9 9 5 -2 4 Sample output: 3 9 5 ``` --- ## C standard library C standard library ---- ++C Standard Library ++ is a collection of all standard-compliant header files in C programming, as well as commonly used library implementations (such as input and output and string control). ---- Common header | Header | Description | | -------- | -------- | | <stdio.h> | Define input and output functions. | | <stdlib.h> | Define numerical conversion functions, pseudo-random number generation functions, dynamic memory allocation functions... | | <math.h> | Define the C language math function. | | <time.h> | Defines the time and date of the acquisition, the time and date data manipulation functions, and formatting. | ---- Common header | Header | Description | | -------- | -------- | | <ctype.h> | A character classification function is defined to test whether a character belongs to an alphabetic character, a control character, and so on. | | <string.h> | Defines the C language string processing routine. | | <limits.h> | Some limit values for integer types (such as INT_MIN, INT_MAX) are defined. | | <float.h> | Defines some limit values for floating point types (such as FLT_MIN, FLT_MAX). | ---- Of course, there are many libraries~~ Interested to go to [here] (http://www.cplusplus.com/reference/clibrary/), or go to Google or wiki. --- ## math.h a library of mathematical functions Before use #`include <math.h>` ---- ### Trigonometric function ||| | -------- | -------- | | double sin (double); | sine | | double cos (double); | cosine | | double tan (double); | Tangent | | double asin (double); | arcsin (arcsin)| | double acos (double); | inverse cosine (arccos) | | double atan (double); | arctangent (arctan) | ---- ### Index logarithm ||| | -------- | -------- | Double exp (double);|exponential function (exp(n) = *e*^n^) Double sqrt (double);|open square root Double log (double);|natural logarithm (log(n) = ln n = log~e~ n) Double log10 (double);|base-10 logarithm (log10(n) = log~10~ n) Double pow(double x, double y);|calculates the power of y with base x (pow(x, y)=x^y^) ---- ### Take integer, absolute value ||| | -------- | -------- | Double ceil (double);| take the whole (unconditional entry) Double floor (double);|take down the whole (unconditionally rounded) Double round (double);|rounded up (after version C99) Int abs(int);| Find the absolute value of the integer Double fabs (double);|for absolute value --- ### Exercise 2 * We know that the formula for the proportional series is $\displaystyle\sum_{x=0}^{n-1}ar^x=\dfrac{a(1-r^n)}{1-r}$ * Please write a function **float geometricSeries (float a, float r, int n)**,    Return the value calculated by $a\times n$ when `r = 1.0`.    Otherwise return the value calculated by $\dfrac{a(1-r^n)}{1-r}$. ---- * Input has a lot of measurement, each line of measurement is one line, the measurement has 2 floating point numbers a, r, and 1 integer n. * Call `geometricSeries(a, r, n)` in the main program and print out the return value. ``` Sample input: 2.0 1.0 10 2.0 3.0 5 1.5 0.5 6 Sample output: 20.000000 242.000000 2.953125 ``` ---- * HINT:    If the floating point number is equal to whether the two numbers are equal, do not use `==`,    Although there is nothing wrong with the grammar, because ++ may have a slight error relationship with ++, it is recommended to use "when the difference is less than a certain value, it is considered equal", for example: ```c if (fabs(r - 1.0) < 0.000001) { //... } ``` --- ### Homework ---- * The first week of homework * This program does not add new features, simply modify the program structure * Add at least the following function in the code ++ at least ++:    * EditNewChar()    * PrintCharData()    * SelectAndBattle()    * Battling() * Battling() must be called by SelectAndBattle() ---- ![](https://i.imgur.com/86kXFBE.png =600x620) --- ###### tags: `1082 Ai-Mod-Eng-LKL`
{"metaMigratedAt":"2023-06-15T01:56:39.242Z","metaMigratedFrom":"YAML","title":"W3 - Function","breaks":true,"slideOptions":"{\"transition\":\"slide\"}","contributors":"[{\"id\":\"befaa4d9-75b6-4c05-baa7-7949e0ffa1e2\",\"add\":14434,\"del\":3116}]"}
    249 views