Learn C language in seven days - Day 4 (array)

Insert image description here

1. Define one-dimensional array

In C language, a one-dimensional array is an ordered collection of elements with the same data type. The basic syntax for defining a one-dimensional array is as follows:

data_type array_name[array_size];

in:

  • data_typeIs the data type of the array element, which can be integer, floating point number, character, etc.
  • array_nameis the name of the array, you can customize it.
  • array_sizeis the size of the array, specifying the number of elements the array can hold.

Example 1: Assign the values ​​0, 1, 2, 3, 4, 5, 6, 7, 8, 9 to 10 array elements in sequence and output them in reverse order.

#include <stdio.h>

int main() {
    
    
    int i;
    int a[10];  // 定义一个包含10个整数的数组

    // 使用循环为数组元素赋值
    for (i = 0; i < 10; i++) {
    
    
        a[i] = i; // 数组的每个元素赋值为它的索引
    }

    // 倒序输出数组元素
    for (i = 9; i >= 0; i--) {
    
    
        printf("%d\t", a[i]); // 输出数组元素的值
    }
    printf("\n");

    return 0;
}

operation result:

Insert image description here

Example 2: Input the areas of 10 regions (areas are integers), sort them from small to large and output the sorted results.

Use two different sorting algorithms, one is selection sort and the other is bubble sort.

Selection method (selection sort):

#include<stdio.h>

int main()
{
    
    
    int a[10];
    int i, j, t;

    // 输入10个面积值
    printf("请输入10个面积:\n");
    for (i = 0; i < 10; i++)
        scanf("%d", &a[i]);

    // 选择排序算法
    for (i = 0; i < 9; i++) {
    
    
        for (j = i + 1; j < 10; j++) {
    
    
            if (a[i] > a[j]) {
    
    
                // 交换元素
                t = a[i];
                a[i] = a[j];
                a[j] = t;
            }
        }
    }

    // 输出排序后的面积值
    printf("排序后的面积依次是:\n");
    for (i = 0; i < 10; i++)
        printf("%d\t", a[i]);
    printf("\n");

    return 0;
}

operation result:

Insert image description here

Bubble method (sinking method, bubble sort):

#include<stdio.h>

int main()
{
    
    
    int a[10];
    int i, j, t;

    // 输入10个面积值
    printf("请输入10个面积:\n");
    for (i = 0; i < 10; i++)
        scanf("%d", &a[i]);

    // 冒泡排序算法
    for (j = 0; j < 9; j++) {
    
    
        for (i = 0; i < 9 - j; i++) {
    
    
            if (a[i] > a[i + 1]) {
    
    
                // 交换元素
                t = a[i];
                a[i] = a[i + 1];
                a[i + 1] = t;
            }
        }
    }

    // 输出排序后的面积值
    printf("排序后的面积依次是:\n");
    for (i = 0; i < 10; i++)
        printf("%d\t", a[i]);
    printf("\n");

    return 0;
}

operation result:

Insert image description here

The principle of selection sort is to find the minimum value from the unsorted part, then exchange it with the first element of the unsorted part, and then shrink the unsorted part, and continue this process until the entire array is sorted. The principle of bubble sorting is to compare adjacent elements, and if the order is wrong, swap them. This process is repeated until the entire array is sorted.

The core ideas of the two are different. Selection sort only selects one minimum value in each round, while bubble sort may have multiple exchange operations in each round. Both algorithms can correctly sort the input area values, but selection sort only swaps elements once per round, while bubble sort may swap elements multiple times per round.

2. Define a two-dimensional array

Similar to a one-dimensional array, a two-dimensional array is an array with two dimensions. It is often used to represent matrix or tabular data. The syntax for defining a two-dimensional array is as follows:

data_type array_name[row_size][column_size];

in:

  • data_typeIt is the data type of array elements, which can also be integers, floating point numbers, characters, etc.
  • array_nameis the name of the array.
  • row_sizeand column_sizerepresent the number of rows and columns of the two-dimensional array respectively.

For example, define a 3x3 two-dimensional array of integers:

int matrix[3][3];

Example 1: Insert image description here
Swap the row and column elements of a two-dimensional array, store it in another two-dimensional array b and output it.

#include <stdio.h>

int main() {
    
    
    int a[2][3] = {
    
    {
    
    1, 2, 3}, {
    
    4, 5, 6}};
    int b[3][2];
    int i, j;

    // 使用循环将数组a转置为数组b
    for (i = 0; i <= 1; i++) {
    
    
        for (j = 0; j <= 2; j++) {
    
    
            b[j][i] = a[i][j];
        }
    }

    // 输出数组b
    printf("数组 b 为:\n");
    for (j = 0; j <= 2; j++) {
    
    
        for (i = 0; i <= 1; i++) {
    
    
            printf("%d\t", b[j][i]);
        }
        printf("\n");
    }

    return 0;
}

operation result:

Insert image description here

Example 2: Given a matrix Insert image description here
, please program to find the element with the largest value.

#include <stdio.h>

int main() {
    
    
    int i, j, max;
    int a[3][3] = {
    
    {
    
    1, 2, 3}, {
    
    9, 8, 7}, {
    
    -10, 10, -5}};

    // 假设最大值为数组的第一个元素
    max = a[0][0];

    // 使用嵌套循环遍历数组,找到最大值
    for (i = 0; i <= 2; i++) {
    
    
        for (j = 0; j <= 2; j++) {
    
    
            if (a[i][j] > max) {
    
    
                max = a[i][j];
            }
        }
    }

    // 输出最大值
    printf("最大元素的值为 %d\n", max);

    return 0;
}

operation result:

Insert image description here

3. Define character array

Character array is a special type of array used to store strings. A string is a sequence of characters, '\0'terminated by a null character. The way to define a character array is as follows:

char string_name[length];

in:

  • charRepresents the element type of a character array.
  • string_nameis the name of the character array.
  • lengthis the length of the character array, including the null character at the end of the string '\0'.

For example, define a character array to store names:

char name[20];

Example 1: Define a character array to store names

#include <stdio.h>

int main() {
    
    
    // 声明并初始化一个字符数组来存储名字
    char name[20]; // 假设名字最多包含19个字符,留一个位置给空字符 '\0'

    // 输入名字
    printf("请输入你的名字: ");
    scanf("%19s", name); // 限制输入的字符数不超过19个,并自动在末尾添加 '\0'

    // 打印名字
    printf("你好,%s!\n", name);

    return 0;
}

operation result:

Insert image description here

4. Output character array

To output a character array, you can use the C standard library functions printf(). Here is an example:

char name[] = "John";
printf("Name: %s\n", name);

This will output:Name: John

Example 1: Define a string "Hi, Everybody!!" and then output this string.

#include<stdio.h>

int main() {
    
    
    char c[15] = {
    
    'H', 'i', ',', ' ', 'E', 'v', 'e', 'r', 'y', 'b', 'o', 'd', 'y', '!', '!'};

    int i;
    for (i = 0; c[i] != '\0'; i++) {
    
    
        printf("%c", c[i]);
    }

    printf("\n");
    return 0;
}

operation result:

Insert image description here

Example 2: Output a Insert image description here
pattern

#include<stdio.h>

int main() {
    
    
    char c[3][3] = {
    
    {
    
    ' ', '*', ' '}, {
    
    '*', ' ', '*'}, {
    
    ' ', '*', ' '}};

    int i, j;
    for (i = 0; i <= 2; i++) {
    
    
        for (j = 0; j <= 2; j++) {
    
    
            printf("%c", c[i][j]);
        }
        printf("\n");
    }

    return 0;
}

operation result:

Insert image description here

5. Input character array

To receive input from the user and store it in a character array, you can use the standard library functions scanf()or gets(). Here is an example:

Use scanf():

char name[20];
printf("Enter your name: ");
scanf("%s", name);

Use gets()(note: not recommended as it has security issues):

char name[20];
printf("Enter your name: ");
gets(name);

Example 1: Enter a line of characters consisting of spaces and words (the number of characters is within 80), please count how many words there are.

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

int main() {
    
    
    char input[80]; // 声明一个字符数组来存储输入
    int wordCount = 0; // 用于统计单词数量
    bool inWord = false; // 用于标记是否在单词中

    // 提示用户输入字符数组
    printf("请输入一行由空格和单词组成的字符 (最多80个字符):\n");

    // 使用fgets函数获取用户输入
    fgets(input, sizeof(input), stdin);

    // 去掉输入中的换行符
    size_t len = strlen(input);
    if (len > 0 && input[len - 1] == '\n') {
    
    
        input[len - 1] = '\0';
    }

    // 遍历输入的字符数组来统计单词数量
    for (int i = 0; i < len; i++) {
    
    
        if (input[i] == ' ' || input[i] == '\t') {
    
    
            // 遇到空格或制表符,标记不在单词中
            inWord = false;
        } else {
    
    
            if (!inWord) {
    
    
                // 进入新单词,增加单词数量
                wordCount++;
                inWord = true;
            }
        }
    }

    // 输出统计结果
    printf("输入的字符包含 %d 个单词。\n", wordCount);

    return 0;
}

operation result:

Insert image description here

Guess you like

Origin blog.csdn.net/m0_53918860/article/details/133045213