C programming summary

Posted by tallberg on Fri, 15 Oct 2021 20:53:03 +0200

C programming

Computer program and C language

program

A set of instructions that a computer can recognize and execute;

Each instruction corresponds to a specific operation of the computer;

All operations of the computer are controlled by a program.

language

Machine language: binary languages (0 and 1) that can be directly recognized by the computer
Symbolic language (assembly language or symbolic assembly language): assembly language cannot be directly recognized by the computer. It needs to be converted through the assembly program to convert symbolic language instructions into machine instructions. The conversion process is called "assembly" or "generation", so it is called assembly language. The machine language and assembly language of different types of computers are not interlinked, so machine language and assembly language are completely machine oriented languages.
High level language: it is far away from the specific machine, so it is called high level language. The high-level language can not be directly recognized and executed by the computer. It is necessary to convert the high-level language program (source program) into the machine language instruction program (object program) through the compiler, and then the computer executes the machine instruction program.

Development of high-level languages:
1. Unstructured language
The process in the program can jump freely
2. Structured language
The process in the program is not allowed to jump at will;
The basic structure (sequence structure, branch structure and loop structure) that specifies that the program must have good characteristics;
The program is executed from top to bottom.
C language is a structured language

Both unstructured language and structured language are process oriented languages

3. Object oriented language
Java, C + +, c# etc. are object-oriented languages

Simple program

// Character count
#include <stdio.h>

int main(int argc, const char * argv[]) {
    int nc;
    nc = 0;
    while ((getchar()) != EOF) {
        ++nc;
    }
    printf("%d\n", nc);
}
// symbolic constants 
// Celsius and Fahrenheit temperature conversion table
#include <stdio.h>
#define LOWER 0
#define UPPER 300
#define STEP 20

int main(){
    int fahr;
    for(fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP)
        printf("%3d\t%6.1f\n", fahr, (5.0/9.0)*(fahr - 32));
}
// Print out in the form of one word per line 
 #include <stdio.h>
 int main(){
     int c;
     while ((c = getchar()) != EOF) {
         if(c == ' ' || c == '\n' || c == '\t')
             printf("\n");
         putchar(c);
     }
 }
// Sum two numbers
 #include<stdio.h>
 int main(){
     int a, b, sum;
     a = 123;
     b = 456;
     sum = a + b;
     printf("sum is %d\n", sum);
     return 0;
 }
/**
 sum is 579
 Program ended with exit code: 0
 */
// Find the larger of two integers
 #include <stdio.h>
 int main(){
     int a, b, c;
     int max(int x, int y);
     scanf("%d, %d", &a, &b);// Specify the format of input data in "", & A and & b represent the addresses of variables A and b; Using the scanf function, read in two numbers, send them to the addresses of a and b, and then assign these two variables to a and b.
     c = max(a, b);
     printf("max= %d\n", c);
     return 0;
     
 }

 int max(int x, int y){
     int z;
     if (x > y) {
         z = x;
         return z;
     } else{
         z = y;
         return z;
     }
 }

structure

A C program can include three parts: preprocessing instructions, global declarations (before the main function), and defining functions.

A function consists of two parts: the function head and the function body. Write void or no parameter.

int max (int x, int y) { }

Function type function name function parameter type function parameter function parameter type function parameter function body

Algorithm -- the soul of program

A procedure consists of two parts:

Description of data (data structure):

Description of operation (algorithm): steps requiring computer operation. Generalized algorithm, the method and steps taken to solve a problem is the algorithm.

Algorithm + data structure = Program

Characteristics of algorithm

  • Poor again
  • certainty
  • There are zero or more inputs
  • There are zero or more outputs
  • Effectiveness

Represents an algorithm

  • natural language

  • flow chart

  • Three basic structures

    1. Sequential structure

    2. Select structure

    3. Cyclic structure
      while loop structure
      util loop structure

  • N-S flow chart representation algorithm

  • The algorithm is represented by pseudo code

    // Means 5!
    begin			(Algorithm start)
    1=>t
    2=>i
    while i<=5
    {
    t * i => t
    i + 1 = i
    }
    print t
    end				(Algorithm end)
    
  • Representing algorithms in computer language

    // Means 5!
    #include <stdio.h>
    int main() {
      int t=1, i = 2;
      while(i<=5){
        t = t * i;
        i = i + 1;
      }
      printf("%d\n", t);
      return 0;
    }
    
    
    // Find the value of 1x2x3x4x5
     # include <stdio.h>
     int main(){
         int t = 1;
         int i = 2;
         while (i <= 5) {
             t = t * i;
             i ++;
         }
         printf("%d\n", t);
     }
     
      120
      Program ended with exit code: 0
     
     // Implementation of for loop
     # include <stdio.h>
     int main() {
         int p = 1;
         for (int i = 2; i <= 5; i ++) {
             p = i * p;
         }
         printf("%d\n", p);
     }
    
    
    // Find 1 x 3 x 5 x 7 x 9 x 11
     # include <stdio.h>
     int main(){
         int p, i;
         p = 1;
         i = 3;
         while (i <= 11) {
             p = i * p;
             i = i + 2;
         }
         printf("%d\n", p);
         return 0;
     }
    
     10395
     Program ended with exit code: 0
     
     // Implementation of for loop
     #include <stdio.h>
     int main() {
         int p = 1;
         for (int i = 3; i <= 11; i = i + 2) {
             p = i * p;
         }
         printf("%d\n", p);
     }
    
    
    // There are 50 students who are required to output the student number and grades of students with scores above 80.
    // Structure defines an array of students, taking 5 groups of students as an example
     # include <stdio.h>
     struct student{
         int num;
         float score;
     }stu[5];
      
     int main()
     {
         for (int i=0;i<5;i++)
         {
             printf("Please enter page%d Student information\n",i+1);
             scanf("%d %f",&stu[i].num,&stu[i].score);
         }
         for (int i=0;i<5;i++)
         {
             if (stu[i].score>80)
                 printf("%d, %.2f\n",stu[i].num,stu[i].score);
         }
         
         return 0;
         
      }
    
    
    // Judge whether it is a leap year, every year between 2000 and 2500
    /**
     *1,Y%4==0 And Y%100= 0 is a leap year
     *2,Y%400==0 It's a leap year
     *Leap years do not meet these two conditions.
     */
     #include <stdio.h>
     int main(){
         int y = 2000;
         while (y<=2500) {
             // scanf("%d", y);
             if (y%4==0 && y%100!=0) {
                 printf("%d:It's a leap year\n",y);
             } else if (y%400==0) {
                 printf("%d:It's a leap year\n",y);
             } else{
                 printf("%d:Not a leap year\n",y);
             }
             y = y + 1;
         }
         
     }
    
    
    // Find 1 - 1 / 2 + 1 / 3... + 1 / 99 - 1 / 100
     #include <stdio.h>
     int main() {
         int sign = -1;
         int sum = 1;
         int deno = 2;
         while (deno <= 100) {
             int term = sign * (1/deno);
             sum = sum + term;
             sign = (-1) * sign;
             deno = deno + 1;
         }
         printf("%d\n", sum);
         return 0;
     }
    

Sequential programming

// Convert Fahrenheit to Celsius
#include <stdio.h>
int main() {
    float f, c;
    f = 65;
    c = (5.0 / 9)*(f - 32);
    printf("Convert to degrees Celsius:%f\n", c);
    return 0;
}
Conversion to Celsius: 18.333334
Program ended with exit code: 0

Data representation and operation

Constant, variable

constant

  • integer constants

  • Real constant

    Decimal form (1.34), exponential form (12.34e3).

  • character constants

    Ordinary characters' a ',' b ', escape characters.

  • string constant

    "abc", "boy"

  • symbolic constants

    #define PI 3.1416 / / there is no semicolon at the end of the line. Defining symbolic constants

variable

Define before use

Constant variable (named invariant)

Similarities and differences between constant variables and variables: the same as variables have types, occupy storage units, but are not allowed to change values.

const float pi = 3.1416; // Define constant variables

identifier

data type

Integer data

#include <stdio.h>
int main() {
    int a = sizeof(short);       // 2
    int b = sizeof(int);         // int type takes 4 bytes
    int c = sizeof(long);        // 8
    int d = sizeof(long long);   // 8
    printf("%d, %d, %d, %d\n", a, b, c, d);
}

Basic integer (int)

Storage method:

Positive numbers are stored as binary complements (that is, they are still in binary form, and negative numbers are different)

Calculation of numerical range of accommodation:

If 2 bytes are allocated to an integer variable

The first 0 of the stored maximum value 01111111 is the sign bit, indicating a positive number, and the last 15 bits are all 1
most large value : 2 15 − 1 ; most Small value : − 2 15 ; because this Model around by : − 2 15 ~ 2 15 − 1 Maximum: 2 ^ {15}-1; Minimum: - 2 ^ {15}; Therefore, the range is: - 2 ^ {15} ~ 2 ^ {15}-1 Maximum value: 215 − 1; Minimum: − 215; Therefore, the range is: − 215 ~ 215 − 1
The minimum stored value is 10000000 0000000. The first 1 is the sign bit, indicating a negative number, and the last 15 bits are all 0

Beyond this range, overflow will occur and the input data will be reported as error ❌.

short int

long int

Double long int

character

Characters are stored in memory units in the form of decimal numbers (ASCII code of characters):

Capital letter 'A': ASCII code of is decimal number 65

Lowercase 'a': ASCII code of is decimal number 97

Numeric character '1': ASCII code of is decimal number 49

  • be careful ‼️

    The character '1' is different from the integer 1, '1' is only a symbol with the shape of 1. If necessary, it will be output as is and stored in the memory in the format of an ASCII code, occupying one byte;

    1 is stored in integer running script (in the form of binary complement), occupying 2 or 4 bytes.

    Integer operation 1 + 1 equals 2, but '1' + '1' is not equal to integer 2 or character '2'

float

Format character

%d: Signed integer

%c: Character

%f: Floating point number

%s: String

Character data input and output

In addition to using scanf() and printf() to input and output characters, you can also use getchars() and put char() to input and output characters;

// Output the received characters.
#include<stdio.h>
int main() {
  char a, b, c;			// Defining characters a, b, c
  a = putchar();		// keyboard entry
  b = putchar();
  c = putchar();
  getchar(a);
  getchar(b);
  getchar(c);
  putchar('\n');			// Line feed
  return 0;
}

# include <stdio.h>
int main() {
    putchar(getchar());
    putchar(getchar());
    putchar(getchar());
    putchar('\n');
    return 0;
}

Select programming

Two selection statements

1. if statement

Implement the selection structure of two branches
seek a x 2 + b x + c = 0 of square Course root . false set up a , b , c of value let meaning . Find the root of the equation ax^{2} + bx + c = 0. Suppose the values of a, b, c are arbitrary. Find the root of the equation ax2+bx+c=0. Suppose the values of a,b,c are arbitrary.

#include <stdio.h>
#Include < math. H > / / the program needs to call the disc square function sqrt
int main() {
    double a, b, c, disc, x1, x2, p, q;
    scanf("%lf,%lf,%lf", &a, &b, &c);			// ⚠️ The format character is followed by "," and no "," in different ways
    disc = b * b - 4 * a * c;
    if (disc < 0) {			
        printf("This equation has no solution");
    } else {
        p = -b/(2.0*a);
        q = sqrt(disc)/(2.0*a);
        x1 = p + q;
        x2 = p - q;
        printf("%lf, %lf", x1, x2);
    }
    return 0;
}
/**
2,4,1						// ⚠️
  -0.29,   -1.71
Program ended with exit code: 0
*/

#include <stdio.h>
#Include < math. H > / / the program needs to call the disc square function sqrt
int main() {
    double a, b, c, disc, x1, x2, p, q;
    scanf("%lf%lf%lf", &a, &b, &c);			// ⚠️
    disc = b * b - 4 * a * c;
    if (disc < 0) {			
        printf("This equation has no solution");
    } else {
        p = -b/(2.0*a);
        q = sqrt(disc)/(2.0*a);
        x1 = p + q;
        x2 = p - q;
        printf("%lf, %lf", x1, x2);
    }
    return 0;
}
/**
2 4 1				⚠️
  -0.29,   -1.71
Program ended with exit code: 0
*/
// Enter two real numbers and output them in the order of the generation value from large to small.
#include <stdio.h>
int main(){
    double a, b, temp;
    scanf("%lf%lf", &a, &b);
    if (a > b) {
        // Swap the values of a and B
        temp = a;
        a = b;
        b = temp;
    }
    printf("%2.4f, %2.4f\n", a, b);
    return 0;
}
/**
 4 2
 2.0000, 4.0000
 Program ended with exit code: 0
 */
// Enter 3 real numbers and output them in the order from large to small.
#include <stdio.h>
int main(){
    double a, b, c, temp;
    scanf("%lf%lf%lf", &a, &b, &c);
    if (a > b) {
        temp = a;
        a = b;
        b = temp;
    }
    if (a > c) {
        temp = a;
        a = c;
        c = temp;
    }
    if (b > c) {
        temp = b;
        b = c;
        c = temp;
    }
    printf("Sorted order:%4.2f,%4.2f,%4.2f\n", a, b, c);
    return 0;
}
/**
 4 2 1
 Sorted order: 1.00,2.00,4.00
 Program ended with exit code: 0
 */

Logical operator, logical expression, logical variable

There are three logical operators: & & (logical AND), | (logical OR)! (logical non NOT)

Logical expression: 1 is true; 0 is false, that is, a value other than 0 is considered true.

​ a = 4,! A is true; a = 4, b = 5, a & & B is true.

Logical variable:

// Logical variable
/**
 Use_ Bool representation
 */
#include <stdio.h>
int main()
{
    float score;
    scanf("%f", &score);
    _Bool a, b;																// Define a and B as logical variables
    a = score >= 60;													// Assign the value of relational expression score > = 60 to logical variable a
    b = score <= 69;													// Assign the value of relational expression score < = 69 to logical variable b
    if (a && b) printf("this grade is C\n");  // If both a and b are true, this grade is C is output
    return 0;
}
/**
 69
 this grade is C
 Program ended with exit code: 0
 */

Conditional operator, conditional expression

Applicable conditions: when a conditional statement is executed, whether true or false, it is finally assigned to the same variable.

Expression 1? Expression 2: expression 3;

if (a > b){
	max = a;
} else {
	max =b;
}
// Equivalent to
max = (a > b) ? a : b;
// Enter a character to determine whether it is an uppercase letter. If it is uppercase, convert it to lowercase.
#include <stdio.h>
int main() {
    char ch;
    scanf("%c", &ch);
//    if (ch >= 'A' && ch <= 'Z') {
//        ch = ch + 32;
//    }
    ch = (ch >= 'A' && ch <= 'Z') ? (ch + 32) : ch;
    printf("%c\n", ch);
}
/*
 A
 a
 Program ended with exit code: 0
 */

2. switch statement

Implement the selection structure of multiple branches

// switch implements multi branch selection structure
// Grade
# include <stdio.h>
int main() {
    char grade;
    scanf("%c", &grade);
    printf("Your grade:");
    switch (grade) {
        case 'A':
            printf("85~100\n");
            break;
        case 'B':
            printf("60~85\n");
            break;
        case 'C':
            printf("0~60\n");
            break;
            
        default:
            printf("Input data error!!!\n");
            break;
    }
    return 0;
}
/*
 A
 Your grade: 85 ~ 100
 Program ended with exit code: 0
 */

// The switch statement implements the menu processing command.
#include<stdio.h>
int main() {
    void action1(int, int), action2(int, int);
    char ch;
    int a = 32, b = 15;
    ch = getchar();             // Enter a character
    switch (ch) {
        case 'a':
        case 'A':               // Enter a or a to execute the action1 function
            action1(a, b);      // Execute operation A and call action1 function
            break;
        case 'b':
        case 'B':               // Enter B or B to execute the action2 function
            action2(a, b);      // Execute operation B and call action2 function
            break;
            
        default:
            putchar('\a');      // Output warning ⚠️
            break;
    }
    return 0;
}

void action1(int x, int y) {        // A function that performs addition
    printf("x + y = %d\n", x + y);
}

void action2(int x, int y){         // A function that performs multiplication
    printf("x * y = %d\n", x * y);
}
/*
 Ax + y = 47
 Program ended with exit code: 0
 */

practice

// Select structure nesting use
// Write a program to determine whether a year is a leap year.
#include <stdio.h>
int main() {
    int y, leap;
    scanf("%d", &y);
    if (y%4==0) {
        if (y%100==0) {
            if (y%400==0) {
                leap = 1;
            } else {
                leap = 0;
            }
        } else {
            leap = 1;
        }
    } else {
        leap = 0;
    }
    if (leap == 1) {
        printf("%d is leap year\n", y);
    } else if (leap == 0) {
        printf("%d is not leap year\n", y);
    }
}
/*
 2021
 2021 is not leap year
 Program ended with exit code: 0
 
 2020
 2020 is leap year
 Program ended with exit code: 0
 */

// Use logical expressions to achieve the above problems
#include <stdio.h>
int main(){
    int y, leap;
    scanf("%d", &y);
    
    if ((y%4==0&&y%100!=0) || (y%400==0)) {		// The above selection structure nesting is realized by using logical expressions
        leap = 1;
    } else {
        leap = 0;
    }
    
    if (leap == 1) {
        printf("%d is leap year\n", y);
    } else if (leap == 0) {
        printf("%d is not leap year\n", y);
    }
    
}

// Implementation using logical variables and logical constants true and false
#include <stdio.h>
#include <stdbool.h>
int main() {
    int y;
    _Bool leap;
    scanf("%d", &y);
    if (y%4==0) {
        if (y%100==0) {
            if (y%400==0) {
                leap = true;
            } else {
                leap = false;
            }
        } else {
            leap = true;
        }
    } else {
        leap = false;
    }
    
    if (leap == true) {
        printf("%d is leap year\n", y);
    } else if (leap == false) {
        printf("%d is not leap year\n", y);
    }
}

Loop programming

while Loop

do... while loop

for loop

Change the execution state of the loop

  • break

    break statement terminates the loop in advance (jump out of the loop body and make the process jump out of the loop)

  • continue

    continue statement ends the loop ahead of time (you want to end the loop ahead of time)

  • Comparison of break and continue

continue is to end only this cycle, not the whole cycle. break ends a loop.

Processing batch data with arrays

  • An array is a collection of ordered data. The data in the array is regular.

  • Each element in the array belongs to the same data type.

Define and reference one-dimensional arrays

int a[10] / / defines a one-dimensional array with 10 elements

You cannot temporarily enter the size of an array in a program

#include<stdio.h>
int main(){
  scanf("%d", &n);
  int a[n];				// An attempt to temporarily determine the size of an array is incorrect
}

You can pass values to the formal parameters of the calling function through the arguments to determine the array size.

void func(n) {
  ...
  int a[2*n];
  ...
}
  • Reference one-dimensional array: through subscript forms a[0], a[7];
// Assign values to 10 array elements from 0 to 9 and output them in reverse order
#include<stdio.h>
int main(){
  int i, a[10];
  for (i = 0; i < 10; i++) {		// Assign a value to each array element
      a[i] = i;
  }
  
  for (i = 9; i >=0; i--) {			// Cyclic output in reverse order
      printf("%d,", a[i]);
  }
  printf("\n");
  return 0;
}
/*
9,8,7,6,5,4,3,2,1,0,
Program ended with exit code: 0
*/

One dimensional array initialization

When defining an array, assign values to each element of the array (to make the program more concise), or assign values to some elements,

One dimensional array example

// Processing fiboracci sequences with arrays
#include <stdio.h>
int main(){
    int f[20] = {1, 1};                // Set the initial value of the first two elements to 1
    for (int i = 2; i < 20; i++) {        // Loop through each array element and assign a value
        f[i] = f[i - 1] + f[i - 2];
    }
  
    for (int i = 0; i <= 20; i++){
        if (i%5==0) printf("\n");           // Line feed of 5 numbers
        printf("%12d,", f[i]);              // Output a number
    }
    
    printf("\n");                       // Last line feed
    return 0;
}
/*
 1,           1,           2,           3,           5,
 8,          13,          21,          34,          55,
89,         144,         233,         377,         610,
987,        1597,        2584,        4181,        6765,
-730267627,
Program ended with exit code: 0
 */
// There are 10 areas, which are output from small to large
// Bubble sorting
#include <stdio.h>
int main(){
    int a[10];
    int i, j, k;
    // Cycle input 10 numbers
    for (i = 0; i < 10; i++) {
        scanf("%d", &a[i]);
    }
    printf("\n");
    
    // Changing j from 0 to 9 requires 9 cyclic comparisons
    for (j = 0; j < 9; j++){
        // Each cycle needs to be compared (9 - j) times [9-j times because there are 0]
        for (i = 0; i < 9 - j; i++) {
            if (a[i] > a[i+1]) {
                k = a[i];a[i] = a[i+1];a[i+1] = k;
            }
        }
    }
    printf("The sorted number: \n");
    
    // The for loop outputs the sorted order
    for (i = 0; i < 10; i++){
        printf("%d ", a[i]);
    }
    printf("\n");
    return 0;
    
}
/*
 18 29 90 199 28 1 79 28 11 0

 The sorted number:
 0 1 11 18 28 28 29 79 90 199
 Program ended with exit code: 0
 */

Define and reference 2D arrays

Define a 2D array

float pay[3][6];   

Two dimensional arrays are stored in rows, that is, the elements of the first row are stored in memory, and then the elements of the second row are stored in order. Storage in memory is linear, not two-dimensional, which is only logical for convenience of memory.

// Define 3D array
float a[2][3][4];		// It defines a three-dimensional array with 2 pages, 3 rows and 4 columns
/*
The arrangement of multi-dimensional array elements in memory is the first dimension, which changes the slowest, and the more to the right, the faster
*/

Initialization of two-dimensional array

// 1. Initialize the two-dimensional array
int a[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};

// 2. Assign initial values to array elements according to the order of array elements in memory
int b[3][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};

// 3. Initial values of some elements
int a[3][4] = {{1}, {5}, {9}};

// 4. When defining an array, the elements of the first dimension can not be assigned, and the elements of the second dimension must be assigned.
int a[][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};

Two dimensional array program example

// Swap the rows and columns of a two-dimensional array and save it to another two-dimensional array
/**
a[2][3] = {1, 2, 3, 4, 5, 6};
b[3][2] = {1, 4, 2, 5, 3, 6};
*/
#include <stdio.h>
int main(){
    int a[2][3] = {{1, 2, 3}, {4, 5, 6}}, b[3][2], i, j;
    printf("array a:\n");
    for (i = 0; i <= 1; i++) {
        for (j = 0; j <= 2; j++) {
            printf("%5d", a[i][j]);     // Output a array elements
            b[j][i] = a[i][j];          // Swap rows and columns of a and B arrays
        }
        printf("\n");
    }
    
    printf("array b:\n");
    for (i = 0; i <= 2; i++) {
        for (j = 0; j <=1; j++) {
            printf("%5d", b[j][i]);
        }
        printf("\n");
    }
    
}
/*
 array a:
     1    2    3
     4    5    6
 array b:
     1    2
     4    5
     2    3
 Program ended with exit code: 0
 */
// A 3 X 4 matrix, find its maximum value, and output the row and column number.
#include <stdio.h>
int main(){
    int i, j, row = 0, colum = 0, max;
    int a[3][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
    max = a[0][0];
    for (i = 0; i <= 2; i++) {
        for (j = 0; j <= 3; j++) {
            if (a[i][j] > max) {
                max = a[i][j];
                row = i;
                colum = j;
            }
        }
    }
    printf("max:%d\nrow:%d\ncolum:%d\n", max, row, colum);
    return 0;
}
/*
 max:12
 row:2
 colum:3
 Program ended with exit code: 0
 */

Character array

// Character array
#include <stdio.h>
int main() {
    char a[8] = {'I',' ', 'a', 'm', ' ', 'b', 'o', 'y'};
    int i;
    for (i = 0; i <= 7; i++) {
        printf("%c", a[i]);
    }
    printf("\n");
    return 0;
}
/*
 I am boy
 Program ended with exit code: 0
 */

Function (program modularization)

The program has many functions and large scale. Writing it in a main function makes the program bloated and difficult to maintain.

A function is a function. Each function is used to implement a specific function.

Function classification

From the perspective of function form, it can be divided into two types: parametric and nonparametric.

From the perspective of users, functions are divided into library functions and user-defined functions.

Function definition

  • Specify the type of function: the type of the return value of the function;
  • Specify the name of the function: convenient to call;
  • Specify the parameter name and parameter type of the function: call the function to facilitate parameter transfer;
  • Specifies the functionality of the function.

Definitions and declarations are different. Declaration is to put the basic information package of the function to the compiler.

Function example

// Enter two integers to find their maximum value. It is required to find a larger value with a function.
#include<stdio.h>

int max(int x, int y){      // Defines a function that has two formal parameters and receives the arguments assigned to it
//    if (x > y) {
//        return x;
//    } else {
//        return y;
//    }
    int z;
    z = x>y?x:y;
    return z;
}

int main() {
    int max(int x, int y);  // Declarative function
    int a, b, c;
    scanf("%d%d", &a, &b);
    c = max(a, b);				// The calling function has two arguments, which are assigned to the formal parameters of the max function
    printf("The larger of the two is:%d\n", c);
    
}
/*
 4 5
 The larger of the two is: 5
 Program ended with exit code: 0
 */
// Output:
// *******************
// Hello World!!
// *******************

/*
 When defining two functions, it is void, which means no type (no function value). That is, no value will be returned to the main function after the function is executed.
 No return value.
 
 After defining the function in the main function, when the main function needs to be used, it is necessary to declare "function type, function name (parameter and parameter type)"
 */
 #include<stdio.h>
 int main(){
     void print_star(void);  // Declare print_star function
     void print_message(void); // Declare print_message function
     print_star();           // Call function
     print_message();        // Call function
     print_star();
     return 0;
 }

 void print_star(void){  // Define function print_star
     printf("*******************\n");
 }

 void print_message(void) {  // Define function prin_message
     printf("Hello World!!\n");
 }
/*
 *******************
 Hello World!!
 *******************
 Program ended with exit code: 0
 */

Procedure of function call

  • The formal parameters in the defined function will not allocate memory when there is no function call. Temporary memory is allocated only when the function is called.

  • The value corresponding to the argument is passed to the formal parameter. Then you can use formal parameters for operations.

  • Return the value of the function to the calling function through the return statement.

  • After the call, the formal parameter unit will be released. The argument unit remains the original value. In function calls, formal parameters and arguments use different storage units, so the value of the argument will not change when the value of the formal parameter changes.

// Enter two integers to find their maximum value. It is required to find a larger value with a function.
// Requirement: the type of the value returned to the calling function in the max function is float, which is inconsistent with the specified function type ⚠️

#include<stdio.h>

int max(int x, int y){      // Defines a function that has two formal parameters and receives the arguments assigned to it
    float z;
    z = x>y?x:y;
    return z;
}

int main() {
    int max(int x, int y);  // Declarative function
    int a, b, c;
    scanf("%d%d", &a, &b);
    c = max(a, b);                // The calling function has two arguments, which are assigned to the formal parameters of the max function
    // Note here ⚠️:  The value returned by the max function here is of float type, and here is of int type, which is handled according to the assignment rules.
    // Convert z to type int, which is the final return value.
    printf("The larger of the two is:%d\n", c);
    
}
⚠️
/*
 1.2 3.4
 The larger of the two is: 1 
 Program ended with exit code: 0
 */
// Enter two numbers and find the sum of the two numbers
#include<stdio.h>
int main() {
    float add(float x, float y);
    float a, b, c;
    printf("Please enter a and b:");
    scanf("%f,%f", &a, &b); // ⚠️: % f followed by \ n, and scanf is an input function. Double quotation marks do not need anything else directly.
    c = add(a, b);
    printf("The sum of the two numbers is:%f\n", c);
    return 0;
}

float add(float x, float y) {
    float z;
    z = x+y;
    return z;
}
/*
 Please enter a and b:2.1, 2.1
 The sum of the two numbers is 4.200000
 Program ended with exit code: 0
 */

Recursive call of function

When a function is called, an indirect or direct call to the function itself is called a recursive call to the function

// This is a non terminating recursive call
#include<stdio.h>
int f(int x){
  	int y, z;
  	z = f(y);
  	return (2*z);	
}

give an example

// There are five students. The fifth student is 2 years older than the fourth student, the fourth is 2 years older than the third, the third is 2 years older than the second, and the second is 2 years older than the first. The first classmate is ten years old. Ask the fifth student how old he is.
/*
 Two stages of recursive problem: backtracking and recursion
 */
    
#include <stdio.h>
int main() {
    int age(int n);
    printf("NO.5, age:%d\n", age(5));
    return 0;
    
}


int age(int n) {
    int c;
    if (n == 1) {
        c = 10;
    }else{
        c = age(n - 1) + 2;
    }
    return c;
}
/*
 NO.5, age:18
 Program ended with exit code: 0
 */
// Find the factorial of n.
#include <stdio.h>

int fac(int n){
    int c;
    if (n < 0) {
        printf("This data error!");
    } else if (n == 0 || n == 1) {
        c = 1;
    } else {
        c = n * fac(n - 1);
    }
    return c;
}

int main(){
    int fac(int n);
    int n;
    scanf("%d", &n);
    printf("%d! = %d\n", n, fac(n));
    return 0;
}

/*
 5
 5! = 120
 Program ended with exit code: 0
 */

Array as function parameter

// Taking an array as a function argument
// Input 10 numbers, and output the element with the largest value, and what number is this number
#include <stdio.h>
int main()
{
    int max(int x, int y);
    int a[10], i, m, n;
    for (i = 0; i < 10; i++) {      // Enter 10 numbers as array elements
        scanf("%d", &a[i]);
    }
    
    
    for (i = 0, m = a[0], n = 0; i < 10; i++) {
        if (max(m, a[i] > m)) {     // Take the array as the argument of the function. If a[i] is greater than m (assumed to be the maximum value), assign a[i] to m and I to the sequence of the original maximum value.
            m = a[i];
            n = i;
        }
    }
    
    printf("The maximum value in the array is:%d,Position in row:%d\n", m, n+1);
    
}


int max(int x, int y) {     // Find the maximum value
    return x>y?x:y;
}
/*
 1 2 3 4 5 6 7 8 9 10
 The maximum value in the array is: 10, and the position in the row is: 10
 Program ended with exit code: 0
 */

Pointer

A variable is defined in the program. When the program is compiled, the system allocates the corresponding memory length space according to the type of variable. int takes 4 bytes, single precision floating-point type 4 bytes and character type 1 byte. Each byte of the memory area has a number called an address. Data is stored in the memory unit marked by the address.

The variable unit can be found through the address, that is, the address points to the variable unit. That is, the address is the "pointer". (the memory unit with its address can be found through the pointer)

Direct access to memory space (the way to access memory cells by variable name is called direct access):

printf("%d", i);   // The address of the storage unit is found through the variable name i, so as to access the storage unit. After the program is compiled, the variable name is already the memory address of the variable. Variables are accessed through addresses.

scanf("%d", j);		// The value entered by the keyboard is sent to the integer storage unit whose address starts from 2004.

k = i + j;				// Take the value of i from 2000 ~ 2003 memory cells, take the value of j from 2004 ~ 2006 memory cells, and store the added sum in 2008 ~ 2010 memory cells occupied by k.

Indirect access to memory space ():

Is to store the address of the i variable in another variable, and access the address of the i variable through this variable, so as to access the i variable.

// Pointer variable 		 Define a variable i_ The address where the pointer stores the i variable
i_pointer = &i;				// Store the address of the I variable in i_pointer variable, i.e. variable I_ The value of pointer is the starting address of memory occupied by I variable (2000)
// There are two ways to access the I variable: direct access and indirect access (get the starting address of the I variable from the i_pointer variable, and then find the I variable from the memory space starting from 2000 bytes)

*i_pointer = 3;				// Send variable 3 to I_ The storage unit to which the pointer variable points* i_pointer refers to I_ The storage unit to which the pointer variable points.

/*
The pointing is reflected by the address (the i_pointer variable stores the address 2000 and points to the storage unit with the address 2000)
Pointer: he can find the memory unit with his address.
*/

Pointers and pointer variables

Pointer to integer data (int *) is read as: int pointer; Pointer to int.

Two meanings of the pointer of a variable: 1. The address of the variable (the address represented by the storage unit number)
2. Type of variable (data type of memory unit pointed to)

  • Pointer: Address

  • Pointer variable: the variable that stores the address

Define pointer variables

Variable type * Variable name
int c = 10;
int * a_pointer, * b_pointer, * c_pointer = &c;	// The * in front of the pointer variable indicates that the variable is a pointer type variable. The pointer variable name is a_pointer,
// b_pointer,c_pointer is not * a_pointer, * b_pointer, * c_pointer

Reference pointer variable

1) Assign values to pointer variables:

p = &a; // Assign the address of a to the pointer variable p, P points to the value of a, P pointer variable, which is the address of a variable.

2) The variable pointed to by the reference pointer variable

p = &a; // Pointer variable points to integer variable a

printf("%d", *p); // Output the value of the variable pointed to by the pointer variable as an integer, that is, the value of a.

*p = 1; // Indicates that 1 is assigned to the variable pointed to by the pointer variable P.

3) Reference the value of the pointer variable

printf("%o", p);

//The function is to output the value of pointer variable in octal running script. If p points to a, the address of a will be output.

Examples of pointer variables

// Accessing integer variables through pointer variables
# include <stdio.h>
int main() {
    int a = 10, b = 5;
    int * a_pointer, * b_pointer;     // Defines a pointer variable a that points to integer data_ pointer,b_ pointer
    a_pointer = &a;     // Assign the address of a to the pointer variable a_pointer
    b_pointer = &b;     // Assign the address of b to the pointer variable b_pointer
  	// This is a_ Pointer = & A, not * a_ pointer = &a
  	// Because the address of a is assigned to the pointer variable a_pointer, not * a_pointer (i.e. variable a)
    
    printf("a = %d,b = %d\n", a, b);    // Direct access
    
    printf("* a_pointer = %d,* b_pointer = %d\n", * a_pointer, * b_pointer); // Indirect access
}
/*
 a = 10,b = 5
 * a_pointer = 10,* b_pointer = 5
 Program ended with exit code: 0
 */
// Reference pointer variable
// Enter two integers a and b. Output in the order of first large and then small.
/*
 ⚠️It should be noted here that the memory units pointed to by p1 and p2 are exchanged (that is, the values of p1 and p2 have changed), and the values of a and b are not exchanged. It's actually output b, a.
 */
#include <stdio.h>
int main() {
    int *p1, *p2, *p, a, b;
    scanf("%d,%d", &a, &b);
    p1 = &a;    // Point p1 to variable a
    p2 = &b;    // Point p2 to variable b
    if (a < b) {    // When a < B, the values of p1 and p2 are exchanged
        p = p1;
        p1 = p2;
        p2 = p;
    }
    printf("a = %d, b = %d\n", a, b);   // Output the values of a and B
    printf("max = %d, min = %d\n", * p1, * p2);    // Output the variable value pointed to by P1 and P2
    return 0;
}
/*
 1,3
 a = 1, b = 3
 max = 3, min = 1
 Program ended with exit code: 0
 */
// Deal with the above problem in another way.
// With function processing, and with pointer type data as function parameters.
#include <stdio.h>
int main() {
    void swap(int *p1, int *p2);
    int a, b;
    int *pointer_1, *pointer_2;
    scanf("%d, %d", &a, &b);
    pointer_1 = &a;
    pointer_2 = &b;
    if (a < b) swap(pointer_1, pointer_2);
    printf("a = %d, b = %d\n", a, b);
    printf("max = %d, min = %d\n", *pointer_1, *pointer_2);
    
}

void swap(int *p1, int *p2) { // Exchange the variable values pointed to by * P1 and * P2
    int temp;
    temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}
/*
 1, 3
 a = 3, b = 1
 max = 3, min = 1
 Program ended with exit code: 0
 */
// Change the exchange function and exchange the values of pointer variables
#include <stdio.h>
int main() {
    void swap(int *p1, int *p2);
    int a, b;
    int *pointer_1, *pointer_2;
    scanf("%d, %d", &a, &b);
    pointer_1 = &a;
    pointer_2 = &b;
    if (a < b) swap(pointer_1, pointer_2);
    printf("Max = %d, Min = %d\n", a, b);   // a. B no exchange
    return 0;
}

void swap(int *p1, int *p2) {
    int *temp;
    temp = p1;
    p1 = p2;
    p2 = temp;
}
/*
 1, 2
 Max = 1, Min = 2
 Program ended with exit code: 0
 */

// Input three numbers, a, B and C, and output them in the order from large to small.
// Swap the values of two variables with swap
// Change the values of three variables with exchange
#include <stdio.h>
int main() {
    void exchange(int *q1, int *q2, int *q3);
    int a, b, c;
    int *p1, *p2, *p3;
    scanf("%d,%d,%d", &a, &b, &c);
    p1 = &a; p2 = &b; p3 = &c;
    exchange(p1, p2, p3);   // The value passed in here is not the value pointed to by the pointer variable, but the address corresponding to a, B and C.
    printf("a = %d, b = %d, c = %d\n", a, b, c);
    return 0;
    
}

void swap(int *pt1, int *pt2){             // Defines a function that exchanges the values of two variables
    int temp;
    temp = *pt1;
    *pt1 = *pt2;
    *pt2 = temp;
}

void exchange(int *q1, int *q2, int *q3){   // Defines a function that exchanges the values of three variables
    void swap(int *pt1, int *pt2);
    if (*q1 < *q2) swap(q1, q2);
    if (*q1 < *q3) swap(q1, q3);
    if (*q2 < *q3) swap(q2, q3);
}
/*
 1,2,3
 a = 3, b = 2, c = 1
 Program ended with exit code: 0
 */

Pointer reference array

The pointer to the array element is the address of the array element.

// You can use pointer variables to point to array elements
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *p; 		// Definition p is a pointer variable to an integer variable
p = &a[0];	// Assign the address of the a[0] element to the pointer variable p
// Using pointers can make the target program occupy less memory space and run faster.
// Array name in c language, which represents the first element in the array
p = &a; 		// Indicates that the address of a[0] (the first element of array a) element is assigned to the p pointer variable.

int *p1;
p1 = &a[1];
// The above two lines are equivalent to
int *p1 = &a[1];

If the pointer variable p points to any element of the array, p+1 points to the next element of the same array; p-1 points to the previous element of the same array. (here, ± is simply the addition and subtraction of the value (address) of P, rather than adding or subtracting the number of bytes occupied by an array element). If the array is of type int, then p is 2000 and p+1 is 2004.

  • be careful ⚠️ If the initial value of the pointer variable p is & A [0], p+i, and a+i are the addresses of the array element a[i]. Or, in other words, they point to the elements of array a with sequence number I

  • be careful ⚠️ A represents the address of the first element of the array element, and a+i is the address with the sequence number of the array element as i.

  • be careful ⚠️*** (a + i) and (p + i) represent the array elements pointed to by (a + i), (p + i). For example: (a + 5) indicates a[5]

  • be careful ⚠️ If the pointer variables p1 and p2 point to the same array, execute p2 - p1, and the result is the value of p2 - p1 divided by the length of the array elements. int type array, p1(2000),p2(2020), the result is (2020 - 2000) / 4 = 5, indicating the array element with a difference of 5 between the array elements pointed to by p2 and p1.

Reference array elements through pointers

There are two ways to reference array elements:

  • Subscript method a[i]
  • Pointer method * (a + i); or * (p + i) where a is the array name and P is the pointer to the array element. Initial value p = a
// An integer array a has ten elements. It is required to output all the elements in the array and use the subscript method.
// subscripts 
#include <stdio.h>
int main() {
    int a[10];
    int i;
    for (i = 0; i < 10; i++)
        scanf("%d", &a[i]);
    
    
    for (i = 0; i < 10; i++)
        printf("%d ", a[i]);
    
    printf("\n");
    return 0;
}
/*
 1 2 3 4 5 6 7 8 9 10
 1 2 3 4 5 6 7 8 9 10
 Program ended with exit code: 0
 */
// Calculate the address of the array element through the array name and find out the value of the element.
#include <stdio.h>
int main() {
    int a[10];
    int i;
    for (i = 0; i < 10; i++)
        // scanf("%d", &a[i]);
      	scanf("%d", a + i);
    
    for (i = 0; i < 10; i++)
        printf("%d ", *(a + i));
    printf("\n");
    
    return 0;
    
}
/*
 1 2 3 4 5 6 7 8 9 10
 1 2 3 4 5 6 7 8 9 10
 Program ended with exit code: 0
 */
// Reference array elements with pointer variables
#include <stdio.h>
int main() {
    int *p, i;
    int a[10];
    for (i = 0; i < 10; i++)
        scanf("%d", &a[i]);
    
    for (p = a; p < a + 10; p++){
        printf("%d ", *p);   // Pointer to the current array element
    }
    printf("\n");
    return 0;
}
/*
 1 2 3 4 5 6 7 8 9 1
 1 2 3 4 5 6 7 8 9 1
 Program ended with exit code: 0
 */

// adopt ⚠️ Pointer variables output ten elements of an integer array a.
// ⚠️ Note that int a[10], *p = a; / / indicates that the initial value of p is a (i.e. the address of a[0]), pointing to a[0] (the first element of the array element)
#include <stdio.h>
int main() {
    int a[10], *p, i;
    p = a;      // The initial value of p is a, pointing to a[0]
    for (i = 0; i < 10; i++) {
        scanf("%d", p++);
    }
    
    p = a;      // Re point the pointer variable p to the first element a[0] of array a
    // for (i = 0; i < 10; i++, p++) {
    //    printf("%d ", *p);
    // }
  	// It is equivalent to the above program. * it has the same priority as + + and is executed from right to left.
    for (i = 0; i < 10; i++) {
        printf("%d ", *p++);
    }
    printf("\n");
    return 0;
}
/*
 0 1 2 3 4 5 6 7 8 9
 0 1 2 3 4 5 6 7 8 9
 Program ended with exit code: 0
 */
// adopt ⚠️ The array name calculates the element address and finds the value of the element
#include <stdio.h>
int main() {
    int a[10], i;
    for (i = 0; i < 10; i++) {
        scanf("%d", &a[i]);
    }
    
    for (i = 0; i < 10; i++) {
        printf("%d ", *(a + i));        // The difference from the above is that the element address is calculated by element name + element sequence number, and then the element is found
    }
    printf("\n");
}
/*
 0 1 2 3 4 5 6 7 8 9
 0 1 2 3 4 5 6 7 8 9
 Program ended with exit code: 0
 */

Array name as function parameter

fun(int arr[], int n)

fun(int *arr, int n) are equivalent. When the function is called, the system will create a pointer variable arr in the fun function to store the address of the first element of the argument array passed from the calling function.

// Store the 10 elements in array a in reverse order
#include<stdio.h>
int main() {
    void inv(int x[], n);
    int i, a[10] = {2, 9, 10, 7, 8, 3, 5, 23, 12, 22};
    for (i = 0; i < 10; i++) {
        printf("%d ", a[i]);		// Outputs the values of the elements of the array in the non swapped order
    }
    printf("\n");
    
    inv(a, 10);			// Calling function exchange order
    for (i = 0; i < 10; i++) {
        printf("%d ", a[i]);	// Output the value of each element of the array after the exchange order
    }
    printf("\n");
    return 0;
    
}

void inv(int x[], int n){												// Parameter x is the array name
    int temp, i, j, m = (n - 1)/2;
    for (i = 0; i < m; i++) {
        j = n - 1 - i;
        temp = x[i]; x[i] = x[j]; x[j] = temp;	// Swap x[i] and x[j]
    }
    return;
}
/*
 2 9 10 7 8 3 5 23 12 22
 22 12 23 5 8 3 7 10 9 2
 Program ended with exit code: 0
 */

Change the above program. Change the formal parameter to a pointer variable.

// Change the above program. Change the formal parameter to a pointer variable.
#include <stdio.h>
int main() {
    void inv(int *x, int n);
    int i, a[10] = {2, 9, 10, 7, 8, 3, 5, 23, 12, 22};
    for (i = 0; i < 10; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");
    
    inv(a, 10);
    for (i = 0; i < 10; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");
    return 0;
    
}

void inv(int *x, int n){
    int *p, temp, *i, *j, m = (n - 1)/2;
    i = x; j = x + n - 1; p = x + m;
    for (; i<= p; i++, j--) {
        temp = *i; *i = *j; *j = temp;
    }
}
/*
 2 9 10 7 8 3 5 23 12 22
 22 12 23 5 3 8 7 10 9 2
 Program ended with exit code: 0
 */

Custom data type

File input and output

There are two main types of documents:

  • Program files: source file (. c file), target file (. obj), executable file (. exe)
  • Data file: a file for programs to read and write.

error analysis

Topics: C