[Regaining C Language] 4. Loop programming (post-judge conditional loops, first-judge conditional loops, multiple loops; typical examples: calculating average grades, printing prime numbers, hundred money and hundred chickens problem)

Table of contents

Preface

4. Cycle programming

4.1 Calculate the average grade - round-robin procedure

4.1.1 Loop of post-judgment conditions        

a. Grammar

b. Typical example

4.1.2 Loop that first determines the condition

a. Grammar

b. Typical example

4.1.3 for statement

a. Grammar

b. Typical example

4.2 Calculate the average score of each person in the class - multiple cycles

4.2.1 Print prime numbers within 100

4.2.2 Hundred Money and Hundred Chickens Problem 


Preface

ChatGPT

        C is a general-purpose, procedural computer programming language developed by Dennis Ritchie at Bell Labs in the early 1970s. It is designed to be a simple, efficient and portable language for system-level programming and application development.

The following are some of the main features of C language:

1. Structured programming : C language supports structured programming, which provides sequential execution, conditional statements (such as if-else and switch) and loop structures (such as for and while), making the program easier to read, understand and maintain.

2. Intermediate language : C language has the characteristics of both high-level language and low-level language. It provides rich control structures and operators, can directly access memory and hardware, and allows programmers to perform low-level operations, such as bit operations and pointer operations.

3. Portability : Programs written in C language are highly portable because its syntax and features remain basically the same on different computer systems. This allows programs to be compiled and executed on different platforms without requiring too many modifications to the code.

4. Powerful standard library : C language provides a rich standard library, which contains various functions and tools for processing input and output, string operations, memory management, mathematical operations, etc. These functions can improve the efficiency of program development and can be used across platforms.

5. System-oriented programming : Because C language has the ability to directly access memory and hardware, it is often used to develop underlying software such as operating systems, embedded systems, and drivers. The C language also provides features such as bit operations and pointers, allowing programmers to better control system resources.

6. Extensibility : C language allows programmers to write custom functions and libraries to extend the functionality of the language. This makes the C language very suitable for the development of large projects, where code can be organized into a modular structure and reused through function calls.

        Although the C language is relatively low-level, it is still a very important and widely used programming language. It provides programmers with powerful control capabilities and performance advantages, and has been widely used in various fields, such as system programming, embedded development, game development, etc. Many modern programming languages, such as C++, Java, and Python, have been influenced by the C language and have been extended and improved on it.

4. Cycle programming

4.1 Calculate the average grade - round-robin procedure

C has three different repetitive statements:

  • do-while statement──loop that determines the condition after
  • while statement── A loop that first determines the condition
  • for statement──a loop that first determines the condition

4.1.1 Loop of post-judgment conditions        

a. Grammar

        A loop that determines conditions later means executing a loop in the loop body first, and then checking whether the loop conditions are met. If the condition is true, the loop continues until the condition is false. Its basic syntax is as follows:

do {
    // 循环体
} while (condition);

        A do-while loop guarantees that the loop body is executed at least once , even if the condition is false initially.

b. Typical example
#include <stdio.h>

int main() {
    int total = 0;  // 总分
    int count = 0;  // 人数
    int grade;      // 成绩

    printf("请输入成绩,输入负数表示结束输入:\n");

    do {
        printf("请输入成绩:");
        scanf("%d", &grade);

        if (grade >= 0) {
            total += grade;
            count++;
        }
    } while (grade >= 0);

    if (count > 0) {
        float average = (float) total / count;
        printf("平均成绩为:%.2f\n", average);
    } else {
        printf("没有输入成绩!\n");
    }

    return 0;
}

4.1.2 Loop that first determines the condition

a. Grammar

        A loop that determines the condition first means that the loop body first checks whether the loop condition is met. If the condition is true, the loop body is executed, and then the condition is rechecked. The loop only ends when the condition is false. Its basic syntax is as follows:

while (condition) {
    // 循环体
}

b. Typical example
#include <stdio.h>

int main() {
    int total = 0;  // 总分
    int count = 0;  // 人数
    int grade;      // 成绩

    printf("请输入成绩,输入负数表示结束输入:\n");

    while (1) {
        printf("请输入成绩:");
        scanf("%d", &grade);

        if (grade < 0) {
            break;
        }

        total += grade;
        count++;
    }

    if (count > 0) {
        float average = (float) total / count;
        printf("平均成绩为:%.2f\n", average);
    } else {
        printf("没有输入成绩!\n");
    }

    return 0;
}

4.1.3 for statement

a. Grammar

        The for statement is a commonly used loop structure that executes the loop body when specified conditions are met. The for statement is usually used when the number of loops is known. Its basic syntax is as follows:

for (initialization; condition; update) {
    // 循环体
}
  • initialization is used to initialize loop variables;
  • condition is used to determine whether the loop continues to execute;
  • update is used to update the value of the loop variable;
  • At the beginning of each loop, `initialization` is first executed, and then it is judged whether the value of `condition` is true. If it is true, the code in the loop body is executed, and then `update` is executed, and the condition is judged again until the condition is false. End the cycle.
b. Typical example
#include <stdio.h>

int main() {
    int count = 0;
    int total = 0;
    int score = 0;

    printf("请输入学生的成绩(输入负数表示结束):\n");

    for (;;) {
        printf("请输入成绩:");
        scanf("%d", &score);

        if (score < 0) {
            break;
        }

        total += score;
        count++;
    }

    if (count > 0) {
        float average = (float) total / count;
        printf("平均成绩为:%.2f\n", average);
    } else {
        printf("未输入有效成绩!\n");
    }

    return 0;
}

4.2 Calculate the average score of each person in the class - multiple cycles

        In this section, you learn how to use a multiple loop structure to calculate the average grade for everyone in the class. Multiple loops refer to the inclusion of another or more loop structures within the loop body.

#include <stdio.h>

int main() {
    int numStudents, numCourses;
    printf("请输入学生人数:");
    scanf("%d", &numStudents);
    printf("请输入课程数:");
    scanf("%d", &numCourses);

    int scores[numStudents][numCourses];

    // 输入每个学生的成绩
    for (int i = 0; i < numStudents; i++) {
        printf("请输入第 %d 个学生的成绩:\n", i + 1);
        for (int j = 0; j < numCourses; j++) {
            printf("请输入第 %d 门课程的成绩:", j + 1);
            scanf("%d", &scores[i][j]);
        }
    }

    // 计算每个学生的平均成绩
    for (int i = 0; i < numStudents; i++) {
        int sum = 0;
        for (int j = 0; j < numCourses; j++) {
            sum += scores[i][j];
        }
        float average = (float)sum / numCourses;
        printf("第 %d 个学生的平均成绩为:%.2f\n", i + 1, average);
    }

    return 0;
}

4.2.1 Print prime numbers within 100

        This example question may be an example of how to use a loop to print out prime numbers within 100. The specific content of the example questions can be determined based on the context.

#include <stdio.h>

int main() {
    printf("100以内的素数有:\n");

    for (int i = 2; i <= 100; i++) {
        int isPrime = 1;

        for (int j = 2; j < i; j++) {
            if (i % j == 0) {
                isPrime = 0;
                break;
            }
        }

        if (isPrime == 1) {
            printf("%d ", i);
        }
    }

    printf("\n");

    return 0;
}

4.2.2 Hundred Money and Hundred Chickens Problem 

        The problem of hundreds of coins and hundreds of chickens is a classic mathematical problem that can be solved by the exhaustive method. The description of the problem is as follows: Suppose there are 100 coins and 100 chickens. Each rooster costs 5 coins, each hen costs 3 coins, and three chickens cost 1 coin. Now I want to buy 100 chickens for 100 money. How many roosters, hens and chicks are there?

#include <stdio.h>

int main() {
    printf("公鸡数量\t母鸡数量\t小鸡数量\n");

    for (int x = 0; x <= 20; x++) {
        for (int y = 0; y <= 33; y++) {
            int z = 100 - x - y;
            if (5 * x + 3 * y + z / 3 == 100 && z % 3 == 0) {
                printf("%d\t\t%d\t\t%d\n", x, y, z);
            }
        }
    }

    return 0;
}

Guess you like

Origin blog.csdn.net/m0_63834988/article/details/133554967
Recommended