Basic knowledge of C language [coming soon, recommended collection]

Basic knowledge of C language

1. Calculation

1. Calculate change~ Idea + code

【Thoughts】:
① There is a place to put the input numbers;
② There is a way to input the numbers;
③ The input numbers can participate in the calculation.
[Code]:

#include <stdio.h>

int main()
{
    
    
    int price = 0;      // 定义了整型变量price --- 变量是保存数据的地方;变量的名字是一种“标识符”
                            // 标识符只能由字母、数字和下划线组成,数字不能出现在第一个位置上
    printf("请输入金额(元):");
    scanf("%d", &price);    // 注意price前面的 & ;

    int change = 100 - price;

    printf("找您%d元。\n", change);

    return 0;
}

【Note:】
1. A variable is a place to save data; the name of a variable is a kind of "identifier";
2. An identifier can only be composed of letters, numbers and underscores, and numbers cannot appear in the first position;

2. scanf function

1. Function: input
2, eg.

scanf("%d",&price);

注意:
① In scanf, there is one before price &;
② "%d", indicating that scanf wants to read an integer and hand it over to the following variable;
"%lf", indicating that it wants to read a floating-point number;
③ The format string that appears in scanf The things in are things that must be entered.

3. Constants & variables

(1) Constants:

1. eg. main program:

	const int AMOUNT = 100;
    int price = 0;      
                           
    printf("请输入金额(元):");
    scanf("%d", &price);    // 注意price前面的 & ;

    int change = AMOUNT - price;

    printf("找您%d元。\n", change);

2. const is a modifier, added before int. After initialization, it cannot be modified, that is, it cannot be assigned again;

(2) Variables:

3. Let the user input the variable AMOUNT instead of using a fixed initial value
[main program]:

    int amount = 100;
    int price = 0;      // 定义了整型变量price --- 变量是保存数据的地方;变量的名字是一种“标识符”
                            // 标识符只能由字母、数字和下划线组成,数字不能出现在第一个位置上
    printf("请输入金额(元):");
    scanf("%d", &price);    // 注意price前面的 & ;

    printf("请输入票面:");
    scanf("%d",&amount);

    int change = amount - price;

    printf("找您%d元。\n", change);

【Operation result】:
Alt
4. Read in the values ​​of two variables and add them together to output the result:
【Code】:

    int a;
    int b;

    printf("请输入两个整数:");
    scanf("%d %d",&a,&b);
    printf("%d + %d = %d\n",a,b,a+b);

【operation result】:
Alt

4. Floating point numbers

(1) Program for calculating height

1. The operation result of two integers can only be an integer;
eg. 10/3*3 = 9
2. 浮点数——The decimal point is floating;
3. When an integer number and a floating point number are put together for operation, C will use the integer Convert to floating-point numbers, and then perform floating-point operations;

① Convert feet and inches to meters

[Code]:

#include <stdio.h>

int main()
{
    
    
	printf("请分别输入身高的英尺和英寸,"
		"如输入\"5 7\"表示5英尺7英寸:");

	int foot;
	int inch;

	scanf("%d %d", &foot, &inch);

	printf("身高是%f米。\n", 
		((foot + inch / 12.0) * 0.3048));

    return 0;
}

【operation result】:
Alt

② Convert centimeters to feet and inches

Alt

#include<stdio.h>

int main(){
    
    
    int foot,inch;
    int cm;
    float m,t;
    
    scanf("%d",&cm);
    m = cm/100.0;
    // foot + inch / 12 = m/0.3048;
    t = m/0.3048;
    // foot = t的整数部分;
    // inch = t的小数部分*12
    foot = t;
    inch = (t - foot)*12;
    printf("%d %d",foot,inch);
    
    return 0;
    
}

Alt

4. 双精度浮点数 double
[Code]:

#include <stdio.h>

int main()
{
    
    
	printf("请分别输入身高的英尺和英寸,"
		"如输入\"5 7\"表示5英尺7英寸:");

	double foot;
	double inch;

	scanf("%lf %lf", &foot, &inch); // lf 来表达输入的事 double 类型

	printf("身高是%f米。\n", 
		((foot + inch / 12) * 0.3048));

    return 0;
}

The running result is the same as above.

(2) Summary:

1. Integer int: used for both input and output %d;

printd("%d",...);
scanf("%d",...);

2. Numbers with decimal points:

double
printf("%f",...);
scanf("lf",...);

5. Expression

(1) Calculate the time difference:

【Thoughts】:
1. What variables should be in the program, how to read and express the data for these variables;
2. After having the data, how to calculate;
【Code】:

#include <stdio.h>

int main()
{
    
    
	int hour1,minute1;
    int hour2,minute2;
    int t1,t2,t;

    scanf("%d %d",&hour1,&minute1);
    scanf("%d %d",&hour2,&minute2);

    t1 = hour1 * 60 + minute1;  // 转换成以分钟为单位
    t2 = hour2 * 60 + minute2;

    t = t2 - t1;

    printf("时间差是%d小时%d分", t/60, t%60 );  // t/60 -- 小时部分, t%60 -- 分钟部分

	return 0;
}

【operation result】:
Alt

(2) Calculate the average of two numbers

【Thoughts】:
1. What kind of variables are there to save the read in;
2. How to calculate;

[Code]:

#include <stdio.h>

int main()
{
    
    
    int a,b;
    double c;

    scanf("%d %d",&a,&b);

    c = (a + b) / 2.0;

    printf("%d和%d的平均值=%lf\n",a,b,c);

	return 0;
}

【operation result】:
Alt

(3) Operator precedence

Alt
1. Monocular operation has only one operator. eg. -a;
2. Unary operators have higher priority than multiplication and division:
eg.

a*-b;	// 先算-b,再与a相乘;

3. Same priority - from left to right → combine;
[Exception]: unary operator, assignment operation - combine from right to left;

4. [Example]:

10 + 9 * ((8 + 7) % 6) + 5 * 4 % 3 * 2 + 3 	// 44

1 + 2 + (3 + 4) * ((5 * 6 % 7 / 8) - 9) * 10	//-627

5. Embedded assignment:

	int a = 6;
	int b;
	int c = 1 + (b=a);

Disadvantages: not conducive to reading; prone to errors;

6. Example:

result = a = b = c + 3; // 先算3+c,再赋给b,再赋给a,再赋给result;
result = (result = result * 2)*6*(result = 3+result);	//最好不要用嵌入式赋值!!要拆开几个表达式

(4) Exchange variables

【program】:

#include <stdio.h>

int main()
{
    
    
    int a,b;
    int c;

    printf("请输入a与b的值:");
    scanf("%d %d",&a,&b);

    c = a;
    a = b;
    b = c;

    printf("a=%d,b=%d\n",a,b);

	return 0;
}

【operation result】:
Alt

(5) Composite operators

① Compound assignment

1. Including +=, -=, *=, /=, %=.
2. eg.

total += 5;	// total = total + 5
total *= sum + 12;  // total = total * (sum + 12) --- 先把右侧算完,再与total计算

② Increment and decrement operators

1. Form: ++; --. is a unary operator.
2. Such as:

count ++;  // count += 1 ;即 count = count + 1
a++;	// a++的值是a加1以前的值
++a;	//++a 的值是加了1以后的值

3. Case procedure

#include <stdio.h>

int main()
{
    
    
    int a=10;

    printf("a++ =%d\n",a++);
    printf("a = %d\n",a);

    printf("++a = %d\n",++a);
    printf("a = %d\n",a);
    
	return 0;
}

Alt

6. Program case - three digits in reverse order

(1) Topic content:
Three-digit numbers in reverse order:
The program reads in a positive three-digit number each time, and then outputs the numbers in reverse order. Note that when the input number contains a trailing 0, the output should not have a leading 0. For example, if you input 700, the output should be 7.
Hint: Use %10 to get single digits, use /100 to get hundreds digits.... Combine the three numbers obtained in this way: hundreds of 100 + tens of 10 + ones, and the result is obtained.

[Code]:

#include <stdio.h>

int main()
{
    
    
    int a;

    printf("请输入一个三位数:");
    scanf("%d",&a);

    printf("逆序数 = %d\n", (a%10)*100+(((a-(a/100)*100)/10)*10)+a/100);
        // 得到十位数的方法也可以是:① a%100,再/10 ;或 ② a/10 再 %10
	return 0;
}

Alt
Alt

2. Judgment and cycle

1, judgment

(1) Introductory program

#include <stdio.h>

int main()
{
    
    
	int hour1,minute1;
    int hour2,minute2;
    int ih,im;

    scanf("%d %d",&hour1,&minute1);
    scanf("%d %d",&hour2,&minute2);

    ih = hour2 - hour1;
    im = minute2 - minute1;

    if(im<0){
    
    
        im = 60+im;
        ih --;
    }

    printf("时间差是%d小时%d分", ih, im );  
    
	return 0;
}

Alt
The running result is correct.

(2) C language provides six relational operators:

	==	相等
	!=	不相等
	>	大于
	>=	大于或等于
	<	小于
	<=	小于或等于

Note:
There are only two results of relational operations: if the relation is established, the result is 1; otherwise, it is 0.

① Priority

1. The priority of all relational operators is lower than that of arithmetic operations, but higher than that of assignment operations.

    printf("%d", 7>=3+4 );  	// 运行结果 = 1

2. The priority of judging whether they are equal ==or not is lower than that of others, and the continuous relational operations are combined [from left to right].!=

    printf("%d", 6>5>4 );  	// 运行结果 = 0
    printf("%d", 5>3 == 6>4 );  	// 运行结果 = 1
    printf("%d", a == b == 6 );  	//从左到右

(3) Change Calculator - Optimization

#include <stdio.h>

int main()
{
    
    
    // 初始化
	int price = 0;
    int bill = 0;
    //读入金额和票面
    printf("请输入金额:");
	scanf("%d", &price);
	printf("请输入票面:");
	scanf("%d", &bill);
	//	计算找零
    if(bill>=price)
	    printf("应该找您:%d\n", bill - price);  
    else
        printf("你的钱不够\n");
        
	return 0;
}

(4) Calculate salary:

#include <stdio.h>

int main()
{
    
    
	const double RATE = 8.25;  // 每小时的薪水
	const int STANDARD = 40;   // 一周的标准工作时间
	double pay = 0.0;
	int hours;

	printf("请输入工作的小时数: ");
	scanf("%d", &hours);
	printf("\n");
	if (hours > STANDARD)
   		pay = STANDARD * RATE + (hours-STANDARD) * (RATE * 1.5);
	else
   		pay = hours * RATE;
	printf("应付工资: %f\n", pay);

	return 0;
}

(5) Judging results

#include <stdio.h>

int main()
{
    
    
	const int PASS=60;
	int score;

	printf("请输入成绩: ");
	scanf("%d", &score);
	
	printf("你输入的成绩是%d.\n", score);
	if ( score < PASS )
		printf("很遗憾,这个成绩没有及格。");
	else {
    
    
		printf("祝贺你,这个成绩及格了。");
		printf("再见\n");
	}

	return 0;
}

2. Cycle

(1) Determine the number of digits

① Four digits and below:

#include<stdio.h>

int main()
{
    
    
    int x;
    int n = 1;

    scanf("%d",&x);

    if(x>999)
        n = 4;
    else if (x > 99)
        n = 3;
    else if(n > 9)
        n = 2;
    else
        n = 1;
    printf("%d\n",n);

    return 0;
}

② Optimization - loop statement

#include<stdio.h>

int main()
{
    
    
    int x;
    int n = 0;

    scanf("%d",&x);
    n++;
    x /= 10;

    while (x > 0){
    
    
        n++ ;
        x /= 10;
    }
    printf("%d\n",n);
    
    return 0;
}

【Note】:In the program, ++n; x/=10; cannot be completely written into the while loop statement. Since x = 0, n should = 1.

(2) do-while loop

	do
	{
    
    
		<循环体语句>
	}while(<循环条件>);

【note】:
1. Regardless of whether the conditions are met or not, do-while will definitely do it again; while while the conditions are not met, nothing will be done.

③ Do-while loop optimization

#include<stdio.h>

int main()
{
    
    
    int x;
    int n = 0;

    scanf("%d",&x);
    do
    {
    
    
        x /= 10;
        n++ ;
    } while(x > 0);
    printf("%d\n",n);

    return 0;
}

(3) for loop

① Factorial operation

1. while loop
#include<stdio.h>

int main()
{
    
    
    int n;
    int fact = 1;
    int i = 1;

    scanf("%d",&n);

    while(i <= n){
    
    
        fact *= i;
        i++;
    }
    printf("%d!=%d\n",n,fact);

    return 0;
}
2. for loop
#include<stdio.h>

int main()
{
    
    
    int n;
    int fact = 1;
    int i = 1;

    scanf("%d",&n);

    /* 从 1 乘到 n */
    //for(i=1; i<=n; i++ ){  // ① 初始条件;② 循环条件;③ 增加步长
    //    fact *= i;
    //}

    for(i=n; i>1; i--){
    
     // 从 n 乘到 1
        fact *= i;
    }
    printf("%d!=%d\n",n,fact);

    return 0;
}

The for statement can also be written as follows, but only C99 compilation can be used;

for( int i=1; i<=n; i++ ){
    
      
        fact *= i;
    }

【note】:Every expression in the for statement can be omitted; but the semicolon cannot be omitted! and

	for(;条件;) == while(条件)

(4) Three kinds of cycle selection tips:

  • If there is a fixed number of times, use for;
  • If it must be done once, use do_while;
  • For other situations while;

3. Further cycle and judgment

1. Logical types and operations

(1) bool type

head File:

	#include<stdbool.h>

Then you can use bool and true, false

(2) Logic operation

  • The result of logical operations is only 0 or 1;
  • Operators: Logical NOT; &&Logical AND; ||Logical OR;
  • priority! > && > ||
  • Such as: x∈[4,6], write the expression of x
	!age < 20;	// 单目运算符的优先级高于双目运算符,故 !age 只会 = 0 或1;一定 < 20.

a. Priority Summary

Alt

  • Assignment is always the lowest; and is a little higher than or;
  • Relational operations are higher than logical operations

(3) Conditional operator

	count = (count > 20)?count-10:count
	// 条件?条件满足时的值:条件不满足时的值
  • Conditional operators have higher precedence than assignment operators, but lower than other operators;
  • The conditional operator isright to leftcombined
  • It is best not to use nested conditional operation expressions, the readability is poor!

(4) comma operator

  • Used to concatenate two expressions with 右边the value of the other expression as its result.
  • The comma operator has the lowest precedence.
  • commaleft to rightcombine
  • often forused in
	for ( i=0,j=10; i<j; i++,j-- );

2. Judgment of cascading and nesting

(1) Nested if-else

eg. Program - Comparison of the size of three numbers

#include<stdio.h>
#include<stdbool.h>

int main(){
    
    
    int a,b,c,max;
    scanf("%d %d %d",&a,&b,&c);

    if(a>b){
    
    
        if(a>c)
            max = a;
        else
            max = c;
    }
    else{
    
    
        if(b>c)
            max = b;
        else
            max = c;
    }
    printf("The max is %d\n",max);
    
    return 0;
}

【Note】:

  1. indented format cannot imply elsea match;
  2. tips: Even if there is only one statement, use it after if and elsebig parantheses{ }! Easy to understand!

(2) Cascading if-else

eg. piecewise function

    int f;
    if(x < 0){
    
    
        f = -1;
    }else if(x == 0){
    
    
        f = 0;
    }else{
    
    
        f = x * 2;
    }

3. Multiple branches

(1)if - else if - else……

#include<stdio.h>

int main(){
    
    
    int type;
    scanf("%d",&type);
  
    if(type == 1)
        printf("你好");
    else if(type == 2)
        printf("早上好");
    else if(type == 3)
        printf("晚上好");
    else if(type == 4)
        printf("再见");
    else
        printf("啊,什么呀?");
    
    return 0;
}

(2)switch-case

#include<stdio.h>

int main(){
    
    
    int type;
    scanf("%d",&type);
  
    switch (type){
    
    
    case 1:             // type == 1 时
        printf("你好");
        break;
    case 2:
        printf("早上好");
        break;
    case 3:
        printf("晚上好");
        break;
    case 4:
        printf("再见");
        break;
    default:
        printf("啊,什么呀?");
        break;
    }
    
    return 0;
}

【Note】:

	switch(控制表达式){
    
    
	case 常量:
		语句
		……
	case 常量:
		语句
		……
	default:
		语句
		……
	}
  1. The control expression can only be the result of integer type int;
  2. A constant can be a constant or an expression calculated by a constant;
  3. will jump out when encountered break;

4. Cycle program case

(1) Loop calculation - calculate the logarithm of x with base 2

#include<stdio.h>

/* 计算log 以 2 为底,x 的对数*/
int main(){
    
    
    int x,t;
    int ret = 0;
    scanf("%d",&x);

    t = x;
    while( t > 1 ){
    
    
        t /= 2;
        ret ++;
    }
   
    printf("log2 of %d is %d.\n", x, ret);
      
    return 0;
}

(2) Calculate the average

[Requirements]: Input a series of positive integers, and finally input -1 to indicate the end of the input, then calculate the average of these numbers, and output the number and average of the input numbers.
[ideas]:

  • Variable —> Algorithm —> Flowchart —> Program
    [Code]:
#include<stdio.h>

/* 计算平均数 */
int main(){
    
    
    int number;
    int sum = 0;
    int count = 0;

    scanf("%d",&number);
    while(number != -1){
    
    
        sum += number;
        count ++;
        scanf("%d",&number);
    }

/*    do{
        scanf("%d",&number);
        if(number != -1){
            sum += number;
            count++;        // count 表明从程序中读入了多少个数据;
        } 
    }while (number != -1);
*/
    printf("输入的%d个数的平均数 = %f\n", count, 1.0*sum / count);
      
    return 0;
}

(3) guessing game

[Requirement]: The computer thinks of a number and lets the user guess it. Every time the user enters a piece of data, he is told whether it is too big or too small until the user guesses it right. Finally, tell him how many times he guessed.
[ideas]:

  1. The computer randomly thinks of a number and records it in the variable number;
  2. The variable count responsible for counting is initialized to 0;
  3. Let the user enter a number a;
  4. count++;
  5. Judge the size relationship between number and a, if a is large, output "big"; if a is small, output a "small";
  6. repeat cycle
  7. Otherwise, output "guess right" and the number of times, and end.

[Code]:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

/* 猜数游戏 */
int main(){
    
    
    srand(time(0));
    int number = rand()%100+1;  // 每次 召唤 rand() 就得到一个随机的整数;
                                // x % n 的结果是 [0,n-1] 的一个整数;
    int a = 0;
    int count = 0;

    printf("我已经想好了一个 1-100 之间的数。\n");
    do{
    
    
        printf("请猜这个 1-100 之间的数:");
        scanf("%d",&a);
        count ++;
        if (a > number){
    
    
            printf("你猜的数大了。");
        }else if(a < number){
    
    
            printf("你猜的数小了。");
        }
    }while (a != number);

    printf("太好了,你用了%d次就猜到了答案。\n", count);
      
    return 0;
}

【Note】:

  1. x % nThe result is an integer of [0,n-1];
  2. rand() Get a random integer every time you summon it ;

【operation result】:
Alt

(4) Integer inversion

[ideas]:

  • The operation on an integer %10can reach single digits;
  • The operation on an integer /10removes the single digit
  • ……

[Code]:

#include<stdio.h>

/* 整数求逆 */
int main(){
    
    
    int x,t;
    int digit;
    int ret = 0; // 初始时结果为0
    
/* 此时若输入为 700,则输出为 7 */
    scanf("%d",&x);
    t = x;
    while(x > 0){
    
    
        digit = x%10;
        // printf("%d\n",digit);
        ret = ret *10 + digit;
        printf("x=%d, digit=%d, ret=%d\n", x, digit, ret);
        x /= 10;
    }
    printf("整数%d的逆=%d。\n", t,ret);
      
    return 0;
}

Alt

/* 此时若输入为 700,则输出为 007 */
    scanf("%d",&x);
    t = x;
    while(x > 0){
    
    
        digit = x%10;
        printf("%d",digit);
        ret = ret *10 + digit;
        //printf("x=%d, digit=%d, ret=%d\n", x, digit, ret);
        x /= 10;
    }

4. Loop control

1. Loop control

(1) Routine: Determine whether a number is prime

[Requirement]: Read in a number x and judge whether x is a prime number.
Prime number: A number that is divisible only by 1 and itself, excluding 1.

[Code]:

#include<stdio.h>

/* 判断是否是素数 */
int main(){
    
    
    int x;
    int i;
    int isPrime = 1;    // isPrime = 1,则 x 是素数
    scanf("%d",&x);

    for (i=2; i<x; i++){
    
    
        if( x % i == 0){
    
         // 说明不是素数
            isPrime = 0;
            break;          //break; --- 跳出循环  ; continue; --- 跳过这一轮循环,进入下一轮
        }
    }
    if (isPrime == 1){
    
    
        printf("是素数。\n");
    } else {
    
    
        printf("不是素数。\n");
    }
     
    return 0;
}

【Note】:

  • break; ---- Jump out of the loop;
  • continue; ---- Skip the remaining statements in this cycle and enter the next cycle

【or】:

/* 判断是否是素数 */
int main(){
    
    
    int x;
    int i;
//    int isPrime = 1;    // isPrime = 1,则 x 是素数
    scanf("%d",&x);

    for (i=2; i<x; i++){
    
    
        if( x % i == 0){
    
         // 说明不是素数
//            isPrime = 0;
            break;          //break; --- 跳出循环  ; continue; --- 跳过这一轮循环,进入下一轮
        }
    }
//    if (isPrime == 1){
    
    
    if (i == x){
    
    
        printf("是素数。\n");
    } else {
    
    
        printf("不是素数。\n");
    }
  • Advantages: saves memory consumption of program variables.
  • Disadvantages: The program has two requirements, one is to be machine-readable, and the other is to be human-readable. This kind of smart approach, the logic is not clear, and other people will consume more brain cells when reading the program, which is not conducive to later program transplantation, maintenance and teamwork.

2. Multiple cycles

(1) Routine: output prime numbers within 100

[Code]:

#include<stdio.h>

/* 输出 1-100 的素数 */
int main(){
    
    
    int x;
    int i;
    int isPrime = 1;    // isPrime = 1,则 x 是素数
    //scanf("%d",&x);
    x = 6;

    for (x=2; x<100; x++)
    {
    
    
        for (i=2; i<x; i++){
    
    
            if( x % i == 0){
    
         // 说明不是素数
                isPrime = 0;
                break;          //break; --- 跳出循环  ; continue; --- 跳过这一轮循环,进入下一轮
            }
        }
        if (isPrime == 1){
    
    
            printf("%d ",x);
        } 
    }
    printf("\n");

    return 0;
}

(2) Routine ②: Output the first 50 prime numbers

[Code 1]:

#include<stdio.h>

/* 输出前50个素数 */
int main(){
    
    
    int x;
    int i;
    int isPrime = 1;    // isPrime = 1,则 x 是素数
    int cnt = 0;        // 计数器
    //scanf("%d",&x);
    x = 2;

//    for (x=2; x<100; x++)
    while (cnt < 50)
    {
    
    
        for (i=2; i<x; i++){
    
    
            if( x % i == 0){
    
         // 说明不是素数
                isPrime = 0;
                break;          //break; --- 跳出循环  ; continue; --- 跳过这一轮循环,进入下一轮
            }
        }
        if (isPrime == 1){
    
    
            printf("%d ",x);
            cnt++;
        } 
        x++;
    }
    printf("\n");

    return 0;
}

[Code 2]:

//    for (x=2; x<100; x++)
//    while (cnt < 50)
    for (x=2; cnt<50; x++)
    {
    
    
        for (i=2; i<x; i++){
    
    
            if( x % i == 0){
    
         // 说明不是素数
                isPrime = 0;
                break;          //break; --- 跳出循环  ; continue; --- 跳过这一轮循环,进入下一轮
            }
        }
        if (isPrime == 1){
    
    
            printf("%d ",x);
            cnt++;
        } 
    //    x++;
    }
    printf("\n");

(3) Make up coins_ Use 1 jiao, 2 jiao, 5 jiao coins to make up an amount below 10 yuan

【Code ①】:—— Relaybreak

#include<stdio.h>

/* 凑硬币 _ 用1角、2角、5角的硬币凑出10元以下的金额 */
int main()
{
    
    
    int x;
    int one,two,five;
    int exit = 0;

    scanf("%d",&x);
    for(one=1; one<x*10; one++){
    
        // 1角最多是 x*10个
        for(two=1; two < x*10/2; two++){
    
        // 2角最多是 x*10/2 个
            for(five=1; five < x*10/5;five++){
    
    
                if(one + two*2 + five*5 == x*10){
    
    
                    printf("可以用%d个1角+%d个2角+%d个5角得到%d元\n",one,two,five,x);
                    exit = 1;
                    break;              /* 【接力 break】*/
                }
            }
            if(exit)    break;  // 相当于 exit ==1;
        }
        if(exit)    break;
    }

    return 0;
}

【Note】:

  • break and continue can only be done to the loop where it is located;

[Code ②]: - gotostatement

  • The goto statement is very suitable for the inner loop of multiple nested loops to jump directly to the outermost situation.
#include<stdio.h>

/* 凑硬币 _ 用1角、2角、5角的硬币凑出10元以下的金额 */
int main()
{
    
    
    int x;
    int one,two,five;
    int exit = 0;

    scanf("%d",&x);
    for(one=1; one<x*10; one++){
    
        // 1角最多是 x*10个
        for(two=1; two < x*10/2; two++){
    
        // 2角最多是 x*10/2 个
            for(five=1; five < x*10/5;five++){
    
    
                if(one + two*2 + five*5 == x*10){
    
    
                    printf("可以用%d个1角+%d个2角+%d个5角得到%d元\n",one,two,five,x);
                    goto out;
                }
            }
        }
    }
out:
    return 0;
}

3. Circular application case

(1) Find the sum of the first n items

① f(n)=1+1/2+1/3+…1/n

[Code]:

#include<stdio.h>

/* 求前 n 项和 —— 1+1/2+1/3+…1/n */
int main()
{
    
    
    int n;
    int i;
    double sum = 0.0;

    scanf("%d",&n);
    for (i=1; i<=n; i++){
    
    
        sum += 1.0/i;
    }
    printf("f(%d)=%f\n",n,sum);

    return 0;
}

② f(n)=1-1/2+1/3-1/4+…+1/n

#include<stdio.h>

/* 求前 n 项和 _f(n)=1-1/2+1/3-1/4+…+1/n */
int main()
{
    
    
    int n;
    int i;
    double sum = 0.0;
    int sign = 1;

    scanf("%d",&n);
    for (i=1; i<=n; i++){
    
    
        sum += sign*1.0/i;
        sign = -sign;
    }
    printf("f(%d)=%f\n",n,sum);

    return 0;
}

[or]: put directlysign is defined as double type
Main program:

    int n;
    int i;
    double sum = 0.0;
    // int sign = 1;
    double sign = 1.0;

    scanf("%d",&n);
    for (i=1; i<=n; i++){
    
    
        sum += sign/i;
        sign = -sign;
    }
    printf("f(%d)=%f\n",n,sum);

(2) Find the greatest common divisor

Method ①: enumeration

[ideas]:

  1. Let t be 2;
  2. If both u and v are divisible by t, write down this t;
  3. After adding 1 to t, repeat the second step until t is equal to u or v;
  4. Then, the largest t ever recorded that can divide both u and v is gcd.

[Code]:

#include<stdio.h>

/* 求最大公约数 */
int main()
{
    
    
    int a,b;
    int min;
    int ret;
    int i;

    scanf("%d %d",&a,&b);
    if (a<b){
    
    
        min = a;
    }else {
    
    
        min = b;
    }
    for (i=1;i<min;i++){
    
            // 从 1 开始,到 a 和 b 的最小值
        if (a%i == 0){
    
              // a 能被 i 整除
            if ( b%i == 0){
    
         // b 能被 i 整除
                ret = i;    // 目前的公约数
            }
        }
    }
    printf("%d和%d的最大公约数是%d\n",a, b, ret);

    return 0;
}

Law ②:Roll and divide

[ideas]:

  1. If b is equal to 0, the calculation ends, and a is the greatest common divisor;
  2. Otherwise, computes the remainder of dividing a by b such that a equals b and b equals that remainder;
  3. Back to the first step;
    eg.
	a	b	t	// t—— 余数
	12	18	12
	18	12	6
	12	6	0
	6	0

[Code]:

#include<stdio.h>

/* 求最大公约数 */
int main()
{
    
    
    int a,b;
    int t;
    scanf("%d %d",&a, &b);

    while ( b!=0)
    {
    
    
        t = a%b;
        a = b;
        b = t;
        printf("a=%d,b=%d,t=%d\n",a, b, t);
    }
    printf("gcd=%d.\n", a);

    return 0;
}

【operation result】:
Alt

(3) Decompose integers in positive order

  • Input a non-negative integer, and output each digit of it in positive order;
  • Input: 13425
  • Output: 1 3 4 2 5

Method ①: Reverse order first, then reverse order

[Code]:

#include<stdio.h>

/* 求最大公约数 —— 先逆序,再逆序,—— 只适用于末尾不是0的数*/
int main()
{
    
    
    int x,d;
    int t = 0;

    scanf("%d",&x);
    do{
    
                 /* 做【逆序】 */
        d = x%10;
        t = t*10 + d;
        x /= 10;    // x 右移一位
    }while (x>0);
    printf("x=%d,t=%d\n",x,t);
    x = t;
    do{
    
                 /* 【再逆序】 */
        int d = x%10;   // 得到最右边的一位
        printf("%d",d);
        if (x>=10){
    
    
            printf(" ");    // 使最后一轮时不输出空格
        }
        x /= 10;        // x 右移一位
    } while( x>0 );
    printf("\n");

    return 0;
}

【operation result】:
Alt

Method ②: Positive sequence output

[ideas]:

eg.
		x = 13425;
		13425 / 10000	--> 1
		13425 % 10000	--> 3425
		10000 / 10		--> 1000
		3425 / 1000	 -->3
		3425 % 1000	 -->435
		1000 / 10	 -->100
		425 / 100  -->4
		425 % 100  -->25
		100 /10	   -->10
		25 / 10	-->2
		25 % 10	-->5
		10 /10	-->1
		5 / 1 -->5
		5 % 1 -->5
		1 /10 -->0
	 		

[Code]:

#include<stdio.h>

/* 求最大公约数 —— 正序输出 */
int main()
{
    
    
    int d,x;
    int mask = 1;
    int t = 0;
    int cnt = 0;
    x = 13425;

    t = x;
    while (x > 9){
    
                     // 可以知道 x 的位数
        x /= 10;
        mask *= 10;
        //cnt++;
    } 
    printf("mask = %d\n",mask);
    // mask = pow(10,cnt-1);   // mask=10^(cnt-1)
    do{
    
    
        d = t / mask;
        printf("%d",d);
        if( mask >9 ){
    
    
            printf(" ");
        }
        t %= mask;
        mask /= 10;
        // printf("x=%d,mask=%d,d=%d\n",x,mask,d);
    }while ( mask >0 );
    printf("\n");

    return 0;
}

5. Arrays and functions

1. Array:

(1) Example: How to write a program to calculate the average of the numbers entered by the user

① No need to record every number entered

#include<stdio.h>

int main(){
    
    
	int x;
	double sum = 0;
    int cnt = 0;
    scanf("%d",&x);	// 读入x
    while(x != -1){
    
    
        sum += x;
        cnt ++;
        scanf("%d",&x);	// 读下一个数
    }
    if(cnt > 0 ){
    
    
        printf("%f\n",sum / cnt);
    }

    return 0;
}

② Calculate the average of the input and output all numbers greater than the average

[ideas]:

  • Save the entered numbers
  • After the input is complete, calculate the average
  • Then judge whether each number should be output

【How to record a lot of numbers】:

	int num1,num2,num3……?

[Array]:

	int number[100];
	scanf("%d",&number[i]);

[Code]:

#include<stdio.h>

int main(){
    
    
	int x;
	double sum = 0;
    int cnt = 0;
    int number[100];    // 定义名为number的数组:数组里的每个单元都是 int;数组大小是100个。
    scanf("%d",&x);
    while(x != -1){
    
    
        number[cnt] = x;	// 对数组中的元素赋值 
        //
        {
    
    
        	int i;
        	for ( i=0; i<=cnt; i++){
    
    
        		printf("%d\t",number[i]);
			}
			printf("\n");
		}
		// 
        sum += x;
        cnt ++;
        scanf("%d",&x);
    }
    if( cnt > 0 ){
    
    
        // printf("%f\n", sum/cnt);
        int i;
        double average = sum/cnt;
        for( i=0; i<cnt; i++ ){
    
    
            if (number[i] > average) {
    
    	// 使用数组中的元素 
                printf("%d",number[i]);		// 遍历数组中的元素 
            }
        }
    }

    return 0;
}

(2) Define an array

	<类型> 变量名称[元素变量];
	如:	int grades[100];
		double weight[20];

【Note】:

  • The number of elements must be an integer;
  • Before C99: the number of elements must be a literal value determined at compile time
  • Arrays of length 0 - can exist, but are useless int a[0];

[Characteristics of the array]:

  • all elements have the same data type;
  • Once created, the size cannot be changed;
  • * (The elements in the array are arranged consecutively in memory)
  • can appear on the left or right side of an assignment;
  • On the left/right side of an assignment is called a left/right value
  • Each cell of the array is a variable of the array type;
  • When using an array, []the number placed in it is called a subscript or index, and the subscript starts counting from 0;
	int a[10];
	// 10个单元: a[0],a[1],……,a[9]
	a[2] = a[1] + 6;	// 把a[1]的值读出来,加上6后,写入到a[2]中去;

【Note】:
Valid subscript range:

  • Once the program is running, out-of-bounds array access can cause problems and cause the program to crash
  • segmentation fault

[Case Procedure]:

#include<stdio.h>

void f();

int main()
{
    
    
	f();

	return 0;
 } 
 
 void f()
 {
    
    
 	int a[10];
 	a[10] = 0;	// a[10] 不是有效下标 
 }
Program optimization:

Problem: The previous program is dangerous because the input data may be more than 100.
Optimization: If you first let the user input how many numbers to calculate, you can use the new function of C99 to achieve.

Alt

(3) Use arrays for hash calculations

[Case]:
Write a program, input an uncertain number of integers in the range [0,9], count the number of occurrences of each number, enter -1 to indicate the end

【program】:

#include<stdio.h>

int main(void)
{
    
    
	const int  number = 10;		// 数组的大小 
	int x;
	int count[number];	// count[i] 说明 i 这个数字出现了多少次 
	int i;
	
	for( i=0; i<number; i++) {
    
    	// 初始化数组 
		count[i] = 0;
	}
	scanf("%d",&x);
	while ( x!= -1 ){
    
    
		if ( x>=0 && x<=9 ){
    
    
			count[x] ++; 	// 运算 
		}
		scanf("%d",&x);
	}
	for ( i=0; i<number; i++){
    
    	// 遍历数组 
		printf("%d:%d\n", i, count[i] );	// i 这个数字出现了多少次 
	}
	return 0;
}

2. Definition and use of functions

(1) Find the sum of prime numbers

#include<stdio.h>

int main(void)
{
    
    
	int m,n;
	int sum = 0;
	int cnt = 0;
	int i;
	
	scanf("%d %d",&m,&n);
	// m=10,n=31;
	if(m==1) m=2;
	for ( i=m; i<=n; i++){
    
    	//判断 i是不是素数
		int isPrime = 1;
		int k;
		for(k=2; k<i-1;k++){
    
    
			if(i%k == 0){
    
    
				isPrime = 0;
				break;
			}
		}
		if(isPrime){
    
    
			sum += i;
			cnt++;
		}
	}
	printf("%d %d\n",cnt,sum);
	
	return 0;
}

Optimization: calling functions

#include<stdio.h>

int isPrime(int i )		// 定义的函数
{
    
    
	int ret = 1;
	int k;
	for(k=2; k<i-1;k++){
    
    
		if(i%k == 0){
    
    
			ret = 0;
			break;
		}
	}
	return ret;
}

int main(void)
{
    
    
	int m,n;
	int sum = 0;
	int cnt = 0;
	int i;
	
	scanf("%d %d",&m,&n);
	// m=10,n=31;
	if(m==1) m=2;
	for ( i=m; i<=n; i++){
    
    	//判断 i是不是素数		
		if(isPrime(i)){
    
    
			sum += i;
			cnt++;
		}
	}
	printf("%d %d\n",cnt,sum);
	
	return 0;
}

(2) Summing: Find the three sums of 1 to 10, 20 to 30 and 35 to 45

#include<stdio.h>
int main()
{
    
    
    int i;
    int sum;

    for( i=1,sum=0; i<=10; i++ ){
    
    
        sum += i;
    }
    printf("%d到%d的和是%d\n",1,10,sum);

    for( i=20,sum=0; i<=30; i++ ){
    
    
        sum += i;
    }
    printf("%d到%d的和是%d\n",20,30,sum);

    for( i=35,sum=0; i<=45; i++ ){
    
    
        sum += i;
    }
    printf("%d到%d的和是%d\n",35,45,sum);

    return 0;
}

注意:Code duplication is a sign of poor program quality.

Optimization: Sum function

#include<stdio.h>
void sum(int begin, int end)
{
    
    
    int i;
    int sum = 0;
    for( i=begin; i<=end; i++){
    
    
        sum += i;
    }
    printf("%d到%d的和是%d\n",begin,end,sum);
}

int main()
{
    
    
    sum(1,10);
    sum(20,30);
    sum(35,45);

    return 0;
}

(3) What is a function?

A function is a block of code that takes zero or more arguments, does one thing, and returns zero or one value.

  1. void sum(int begin, int end)—— function header
  2. {}Inside -- function body
  3. sum-- Function name
  4. void—— return type void type does not return a result
  5. ()Inside - parameter table
① Call function
  • function name(parameter value);
  • () plays an important role in representing function calls
  • require() even without arguments
  • The function knows where it is called each time and returns to the correct place.

(4) Return from the function

Example 1:

In the prime sum example above :

int isPrime(int i )		// 定义的函数
{
    
    
	int ret = 1;
	int k;
	for(k=2; k<i-1;k++){
    
    
		if(i%k == 0){
    
    
			ret = 0;
			break;
		}
	}
	return ret;
}

注意:

  • If the function returns a result, it needs to returnpass that result to the caller.
  • The above function isPrimewill return a intresult of type
Example 2:
int max(int a, int b)
{
    
    
    int ret;
    if (a>b){
    
    
        ret = a;
    }else (
        ret = b;
    )

    return ret;
}

Or: (but preferably the one above!)

int max(int a, int b)
{
    
    
    // int ret;
    if (a>b){
    
    
        return a;
    }else {
    
    
        return b;
    }

    // return ret;
}

Although the second type is not wrong, it does not conform to the concept of a single export;

注意:

  • Once encountered return, it will ①stop the execution of the function, ②and return a value;

  • Two ways of writing:

  • return;

  • return 表达式;

  • returnMultiple statements can appear in a function

like:

#include<stdio.h>

int max(int a, int b)
{
    
    
    int ret;
    if (a>b){
    
    
        ret = a;
    }else {
    
    
        ret = b;
    }

    return ret;
}

int main()
{
    
    
    int a,b,c;
    a = 5;
    b = 6;
    c = max(10,12);
    c = max(a,b);
    c = max(c, 23);
    printf("%d\n",max(a,b));

    return 0;
}
① Functions without return value:
  • void 函数名(参数表);
  • Can't use valuedreturn
  • can notreturn
  • You cannot assign a return value when calling
  • Notice: If the function returns a value, you must use thereturn

3. Function parameters and variables

(1) Function prototype

  • Write the function above main() - because the C compiler analyzes the code sequentially from top to bottom!
  • Or, to be more intuitive, you can change it like this:
#include<stdio.h>

void sum(int begin, int end);   // 函数的【原型声明declaration】

int main()
{
    
    
    sum(1,10);      // 如没有 声明,会猜测 int sum(int,int)
    sum(20,30);
    sum(35,45);

    return 0;
}

void sum(int begin, int end)    // 函数 定义
{
    
    
    int i;
    int sum = 0;
    for( i=begin; i<=end; i++){
    
    
        sum += i;
    }
    printf("%d到%d的和是%d\n",begin,end,sum);
}
  • The function header, ending with a semicolon, constitutes the prototype of the function;
  • The purpose of the function prototype is to tell the compiler what the function looks like ①name, ②parameters (number and type), ③return type;
  • The old standard used to write the function prototype in the function that called it;
  • Now it is generally written in front of the function
  • The name of the parameter may not be written in the prototype, but it is generally still written;

(2) Parameter passing

  • The value that can be passed to a function is the result of an expression, this includes
	① 字面量[eg.10]
	② 变量[eg.a]
	③ 函数的返回值[eg.max(23,45)]
	④ 计算的结果[eg.23+45]
  • If the function has parameters, it must be passed the correct number and type of value when calling the function;
  • When calling a function in C language,You can only pass values ​​to functions!
  • Each function has its own variable space, and the parameters are also located in this independent space, which has nothing to do with other functions!
  • In the past, the parameters in the function parameter table were called " 形式参数"; the value given when calling the function was called " 实际参数";
  • Now, we 形参call 参数; 实参call ;

(3) Local variables

  • Every time the function runs, an independent variable space is generated, and the variables in this space are unique to this running of the function, called 本地变量;
  • Variables defined inside a function are local variables;
  • Parameters are also local variables;
①Variable lifetime and scope
  • Lifetime: When does this variable start to appear, and when does it die;
  • Scope: In what scope of code can this variable be accessed (this variable can work);
  • For local variables, the answer to both questions is uniform:inside curly braces - block
② Rules for local variables
  • Local variables are defined within a block (within braces);
		1.它可以是定义在 函数的块 内;
		2.也可以定义在 语句的块 内
  • Before the program enters this block, the variables in it do not exist;
  • Leave the block and the variables in it disappear
  • Variables defined outside the block are still valid inside;
  • If a variable with the same name as the outside is defined inside the block, it will cover up the outside
  • A variable with the same name cannot be defined within a block
  • Local variables are not initialized by default
  • The parameters are initialized when entering the function!

(4) Other details

① When there is no parameter
void f(void);	// 在参数表里放了 void,明确的告诉编译器,这个函数不接收任何参数;
	还是?
	× void f();	// 在传统C中,它表示 f函数的参数表未知,并不表示没有参数
② comma operator
  • What is the difference between a comma and the comma operator when calling a function?
  • Commas in parentheses when calling a function are punctuation marks, not operators
	f(a,b)		// 是标点
	f((a,b))	// 是运算符
	// 二者区别:到底是传了2个还是1个参数进去
③ Functions within functions
  • C language does not allow function nested definition
  • You can put the [declaration] of another function in a function, but you cannot put the [definition] of another function

4. Two-dimensional array

(1) Two-dimensional array:

	int a[3][5];	// 通常理解为a是一个3行5列的矩阵
① Traversal of two-dimensional array
  • double loop
  • The outer layer traverses the row number; the inner layer traverses the column number
  • like:
for ( i=0; i<3; i++){
    
    
    for ( j=0; j<5; j++ ){
    
    
        a[i][j] = i*j;
    }
}
  • a[i][j]Indicates the cell at row i and column j
  • a[i,j]is an expression

(2) Initialization of two-dimensional array

	int a[][5] = {
    
    
	    {
    
    0,1,2,3,4},	// 看做 5个int的数组,作为 a[0];
    	{
    
    2,3,4,5,6},	// 5个int的数组,作为a[1];
	};
  • The number of columns is required, the number of lines can be counted by the compiler;
  • One {} per line, separated by commas
  • If it is omitted, it means padding with zeros
  • Orientation can also be used (*C99 ONLY)

(3) tic-tac-toe game (tic-tac-toe)

  • Read in a 3×3 matrix, the number in the matrix is ​​1, which means there is an X at the position, and 0 means O;
  • The program judges whether there is a winning party in this matrix, and outputs the character X or O representing the winning party, or outputs no one winning;
    const int size = 3;
    int board[size][size];  // 定义3×3 的棋盘
    int i,j;
    int numOfX;
    int numOfO;
    int result = -1;    // -1:没人赢,1:X赢,0:O赢

    // 读入矩阵
    for ( i=0; i<size; i++ ){
    
    
        for( j=0; j<size; j++){
    
    
            scanf("%d", &board[i][j]);  // 读入数组中的每一个元素
        }
    }

    // 检查行
    for ( i=0; i<size && result == -1; i++){
    
    
        numOfO = numOfX =0;             // 初始化最开始的数量为0
        for( j=0; j<size; j++){
    
             // 判断每一列
            if( board[i][j] == 1){
    
          //行号不变,列号从0到size
                numOfX ++;
            }else{
    
    
                numOfO ++;
            }
        }
        if( numOfO ==size ){
    
    
            result =0;
        }else if(numOfX == size){
    
    
            result = 1;
        }
    }

    // 检查列
    for ( result == -1 ){
    
    
        for( j=0; j<size && result == -1; j++){
    
             
            numOfO = numOfX =0;
            for( i=0; i<size; i++){
    
    
                if( board[i][j] == 1){
    
         
                    numOfX ++;
                }else{
    
    
                    numOfO ++;
                }
            }  
        }
        if( numOfO ==size ){
    
    
            result =0;
        }else if(numOfX == size){
    
    
            result = 1;
        }
    }

    // 检查对角线。。。。

6. Array operations

1. Array operation

(1) References:

  • In a given set of data, how to find out whether a certain data exists?

[Code]:
Alt
Alt

  • Integrated initialization of arrays:
	int a[] = {
    
    2,4,6,7,1,3,5,9,11,13,23,14,32};
	int a[13] = {
    
    2};
	// 2 0 0 0 0 0 0 0 0 0 0 0 0
  • Positioning during integration initialization:
	int a[10] = {
    
    
		[0] = 2, [2] = 3, 6,
		};
	// a[0]=2; a[2]=3; a[3]=6; 其它的都为0;

(2) The size of the array

  • sizeofGive the size of the content occupied by the entire array, in bytes;
	int a[] = {
    
    [1]=2,4,[5]=6};	// 0 2 4 0 0 6
	
	printf("%lu\n",sizeof(a));	// 24
	printf("%lu\n",sizeof(a[0]));	// 4
  • So, the size of the array = sizeof(a)/ sizeof(a[0]);
  • sizeof(a[0])Given the size of a single element in the array, the division gives the number of elements in the array;

(3) Assignment of array

	int a[] = {
    
    [1]=2,4,[5]=6};	// 0 2 4 0 0 6
(False):  int b[] = a;	// 大错特错!!!!不行!!!!
  • Array variables themselves cannot be assigned;
  • To transfer all the elements of one array to another, one must usetraverse
	int a[] = {
    
    [1]=2,4,[5]=6};	// 0 2 4 0 0 6
	
	for ( i=0; i<length; i++) {
    
    
		b[i] = a[i];
	}
  • forUsually a loop is used
  • common mistakes- to avoid:
  • ① The loop end condition is <= array length;×××
  • ② After leaving the loop, continue to use the value of i as the subscript of the array elements!×××
  • 注意:When an array is used as a function parameter, it is often necessary to use another parameter to pass in the size of the array!
  • Because when an array is used as a function parameter: ① the size of the array cannot be given in [ ]; ② sizeof can no longer be used to calculate the number of elements in the array!

2. Search

  • Find the position of a certain number in an array (or confirm whether it exists);
  • basic method:traverse

(1) Linear search - example ①:

#include<stdio.h>

int search(int key, int a[], int len)   // len 来表示数组有多大
{
    
    
    int ret = -1;
    for ( int i=0; i<len; i++)
    {
    
    
        if (key == a[i] )
        {
    
    
            ret = i;
            break;
        }
    }
    return ret;
}

int main()
{
    
    
    int a[] = {
    
    1,3,4,5,12,14,23,6,9,45};
    int r = search(12, a, sizeof(a)/sizeof(a[0]));
    printf("%d\n", r);
    
    return 0;
}

(2) Linear search - example ②:

#include<stdio.h>

int amount[] = {
    
    1,5,10,25,50};
char *name[] = {
    
    "penny","nickel","dime","quarter","half-dollar"};

int search(int key, int a[], int len)   // len 来表示数组有多大
{
    
    
    int ret = -1;
    for ( int i=0; i<len; i++)
    {
    
    
        if (key == a[i] )
        {
    
    
            ret = i;
            break;
        }
    }
    return ret;
}

int main()
{
    
    
    int k = 25;
    int r = search(k, amount, sizeof(amount)/sizeof(amount[0]));
    if ( r > -1)
    {
    
    
        printf("%s\n",name[r]);
    }
    
    return 0;
}
Improvement: put the denomination and name closer
#include<stdio.h>

int amount[] = {
    
    1,5,10,25,50};
char *name[] = {
    
    "penny","nickel","dime","quarter","half-dollar"};

struct {
    
    
    int amount;
    char *name;
} coins[] = {
    
    
    {
    
    1,"penny"},
    {
    
    5,"nickel"},
    {
    
    10,"dime"},
    {
    
    25,"quarter"},
    {
    
    50,"half-dollar"}
};

int search(int key, int a[], int len)   // len 来表示数组有多大
{
    
    
    int ret = -1;
    for ( int i=0; i<len; i++)
    {
    
    
        if (key == a[i] )
        {
    
    
            ret = i;
            break;
        }
    }
    return ret;
}

int main()
{
    
    
    int k = 10;
    // int r = search(k, amount, sizeof(amount)/sizeof(amount[0]));
    for ( int i=0; i<sizeof(coins)/sizeof(coins[0]); i++ )
    {
    
    
        if ( k == coins[i].amount ){
    
    
            printf("%s\n", coins[i].name);
            break;
        }
    }
    
    return 0;
}

(3) Binary search

  • Premise: sort it out!
  • Alt

[ideas]:
Alt

【program】:

#include<stdio.h>

int search(int key, int a[], int len)   // len 来表示数组有多大
{
    
    
    int ret = -1;
    int left = 0;
    int right = len-1;
    while ( left < right )
    {
    
    
        int mid = (left+right)/2;
        if( a[mid] == k )
        {
    
    
            ret = mid;
            break;
        } else if ( a[mid] > k)
        {
    
    
            right = mid-1;
        } else{
    
    
            left = mid+1;
        }
    }
    return ret;
}

int main()
{
    
    
    
    
    return 0;
}

3. Preliminary sorting - selection sorting

  • Given an unordered array, how to arrange it into order?

[ideas]:

  1. find the largest number
  2. The largest number is exchanged with the last digit, that isswap a[maxid],a[len-1];
  3. Then find the largest of the remaining
  4. do the same
  5. ……
  6. until the last two numbers are left

[Code]:

#include<stdio.h>

int max ( int a[], int len)
{
    
    
    int maxid = 0;
    for (int i=1; i<len ; i++ )
    {
    
    
        if( a[i]> a[maxid] )
        {
    
    
            maxid = i;
        }
    }
    return maxid;
}

int main()
{
    
    
    int a[] = {
    
    2,45,6,12,87,34,90,24,23,11,65};
    int len = sizeof(a)/sizeof(a[0]);

    for ( int i=len-1; i>0 ; i-- )
    {
    
    
        int maxid = max(a, i+1);
        // swap a[maxid],a[len-1]
        int t = a[maxid];
        a[maxid] = a[i];
        a[i] = t;
    }
    
    for (int i=0; i<len; i++)
    {
    
    
        printf("%d ",a[i]);
    }
    
    return 0;
}

7. Pointers and strings

1. Pointer

(1) Take the address operation: the & operator gets the address of the variable

sizeof
  • is an operator that gives the number of bytes a type or variable occupies in memory
#include<stdio.h>

int main()
{
    
    
    int a;
    a = 6;
    printf("sizeof(int) = %ld\n", sizeof(int));     // sizeof(int) = 4;int在内存中占4个字节,也就是32个bit
    printf("sizeof(a) = %ld\n", sizeof(a));         // sizeof(a) = 4
    printf("sizeof(double) = %ld\n", sizeof(double));   // sizeof(double) = 8
    
    return 0;
}
② operator&
  • scanf("%d",&i);inner&

(2) Pointer: A pointer variable is a variable that records an address

① Pointer - is the variable that holds the address
	int i;
	int* p = &i;	// 表示p是一个指针,它指向的是一个 int,把i的地址交给了指针p
	int* p,q;	// 表示p是一个指针;q是一个普通的 int类型的变量
	int *p,q;	// 表示p是一个指针;q是一个普通的 int类型的变量
	//【无论 * 是靠近 int 还是 p,都是一样的!!】

[Whether * is close to int or p, it is the same! !

② pointer variable
  • The value of the variable is the address of the memory
  • The value of an ordinary variable is the actual value;
  • The value of the pointer variable is the address of the variable with the actual value;
③ pointer as parameter
  • void f(int *p);The f function expects a pointer to an int
  • When it is called, it gets the value of a variableaddressint i=0;f(&i);
  • In the function, you can access the external i through this pointer
#include<stdio.h>

void f(int *p);
void g(int k);

int main(void)
{
    
    
    int i=6;
    printf("&i=%p\n", &i);
    f(&i);
    g(i);
    
    return 0;
}

void f(int *p)
{
    
    
    printf(" p=%p\n", p);
}

void g(int k)
{
    
    
    printf("k=%d\n", k);		// k = 6
}
④ Access the variable at that address*
  • * is a unary operator used to access the variable at the address represented by the value of the pointer
  • It can be an rvalue or an lvalue—that is, * can be placed on the right side of the assignment number to read its value, or it can be placed on the left side of the assignment number to write its value.
#include<stdio.h>

void f(int *p);
void g(int k);

int main(void)
{
    
    
    int i=6;
    printf("&i=%p\n", &i);
    f(&i);
    g(i);
    
    return 0;
}

void f(int *p)
{
    
    
    printf(" p=%p\n", p);
    printf("*p=%d\n", *p);  // 把 *p 看做一个整体,是int  —— *p = 6;
    *p = 26;        // 此时,k = 26 —— 说明在经历了f函数的调用之后,i的值被改了
}

void g(int k)
{
    
    
    printf("k=%d\n", k);
}

(3) Pointers and arrays: Why is sizeof incorrect after the array is passed into the function?

  • The array in the function parameter list is actuallypointer!
void minmax( int a[], int len, int *min, int *max)
		// 上面的 int a[] ———— 指针!
		// 也可以写成 int *a;
  • sizeof(a) == sizeof(int*);
  • But you can use array operators []to perform operations
  • The following four function prototypes appear in the parameter list and are equivalent:
		int sum(int *ar, int n);
		int sum(int *, int);
		int sum(int ar[], int n);
		int sum(int [], int);
① Array variables are special pointers
  • Array variables themselves express addresses, so:
  1. int a[10];int *p=a; // no need to use & to get the address
  2. But the unit of the array expresses a variable, you need to use & to get the address
  3. a == &a[0];
  • []Operators can be done on arrays as well as on pointers:
  1. p[0] <==> a[0]
  • *Operators can be done on pointers as well as on arrays:
	*a = 25;
  • Array variables are const pointers, so they cannot be assigned
	int b[]; 	// 可以看做是 int * const b;

2. Character type

(1) Character type

  • char is an integer and a special type: character.

This is because:

  1. Character literals denoted by single quotes: 'a','1'
  2. "is also a character;
  3. Use %c in printf and scanf to input and output characters
① Character input and output:
#include<stdio.h>

int main()
{
    
    
    char c;
    char d;
    c = 1;
    d = '1';
    if ( c==d ){
    
                // 不相等
        printf("相等\n");
    } else{
    
    
        printf("不相等\n");
    }
    printf("c=%d\n", c);    // c=1
    printf("d=%d\n", d);    // d=49

    return 0;
}
  • How to input the character '1' to char c?
	scanf("%c", &c); -->1
	scanf("%d", &i); c=i; -->49
  • The ASCII code of '1' is 49, so when c==49, it represents '1';
#include<stdio.h>

int main()
{
    
    
    char c;
    //scanf("%c",&c);         // 输入: 1
    //printf("c=%d\n", c);    // c=49
    //printf("c='%c'\n", c);  // c='1'

    int i;
    scanf("%d",&i);         // 输入: 1 or [49]
    c = i;
    printf("c=%d\n", c);    // c=1 or  [49]
    printf("c='%c'\n", c);  // c=' ' or  ['1']

    return 0;
}
② Mixed input:
  • What is the difference?
	scanf("%d %c",&i,&c);
	scanf("%d%c",&i,&c);
  • scanf(“%d %c”,&i,&c); :
#include<stdio.h>

int main()
{
    
    
    char c;
    int i;
    scanf("%d %c",&i,&c);
    printf("i=%d, c=%d, c='%c'\n", i, c, c);

    return 0;
}

Alt

  • scanf(“%d%c”,&i,&c); :
#include<stdio.h>

int main()
{
    
    
    char c;
    int i;
    scanf("%d%c",&i,&c);
    printf("i=%d, c=%d, c='%c'\n", i, c, c);

    return 0;
}

Alt

  • That is, after %d, if there is no space, it means that the integer is only read until the end of the integer, and the latter one is given to the following;
  • If there is a space, after the integer reads the space, all the spaces after it must be read!
  • Therefore, it makes a difference whether there is a space or not!
③ Case conversion
  • a+'a'-'A'You can convert uppercase letters to lowercase letters;
  • a+'A'-'a'Lowercase letters become uppercase!

(2) escape characters

  • Used to express control characters or special characters that cannot be printed. It “/”starts with a backslash followed by another character. These two characters match to form a character;
	printf("请分别输入身高的英尺和英寸,"
		"如输入\"5 7\"表示5英尺7英寸:");
character significance
\b Back one space
\t to the next table slot
\n new line
\r carriage return
\" Double quotes
\' apostrophe
\\ the backslash itself
\b
  • Go back one grid, let the next output go back to this position
  • But if it doesn't output something, nothing changes
  • If you output something, just overwrite the thing just now
  • Usually it is to go back to Ang, but not to delete;
  • But it is undeniable that there may be terminal software, which will be deleted when running
\t
  • fixed position for each row
  • A \t causes the output to start at the next tab stop
  • Use \t to align the upper and lower lines

3. String

(1) string

  • Strings in C language arecharacter arrayexisting in form;
  • Operators cannot be used to operate on strings
  • Strings can be iterated through an array
  • The only exception is that string literals can be used to initialize character arrays
  • and the standard library provides a series of string functions
① character array
	char word[] = {
    
    'H','e','l','l','o','!'};
	// 但 这不是C语言的字符串,因为不能用字符串的方式做计算!!
	char word[] = {
    
    'H','e','l','l','o','!','\0'}; // 是字符串!
② String
  • A string of characters terminated with 0 (integer 0)
  • 0 or '\0' are the same, but different from '0'
  • 0 marks the end of the string, but it is not part of the string
  • Do not include this 0 when calculating the length of the string
  • string witharrayexists in the form ofarray or pointerform access. More in the form of pointers
  • There are many functions in string.h to deal with strings
③ String variable
	char *str = "hello";
	char word[] = "hello";
	char line[10] = "hello";	// 占据6个字节的line空间 —— 因为还有个结尾的0
④ String constant
  • “hello”
  • "hello" will be turned into a character array and placed somewhere, the length of this array is 6, and there is a 0 at the end to indicate the end;
  • Two adjacent string constants will be automatically concatenated;

(2) Character array

4. String calculation

Guess you like

Origin blog.csdn.net/weixin_48820458/article/details/128078043