Exercises to practice C language (the second part of summer)

Insert image description here


Preface

Say important things three times!
study! study! study!


1. Expression judgment

For the code snippet, the following description is correct ( )

t=0;
while(printf("*"))
{
    
    
    t++;
    if (t<3)
        break;
}

A: The loop control expression is equivalent to 0
B: The loop control expression is equivalent to '0'
C: The loop control expression is illegal
D: None of the above statements are correct

Question analysis:
Because the return value of the print("*") function call is the number of characters in the string, which is 1.
Therefore, the condition after while is always true, so the loop control expression is equivalent to '0' (the character '0' is not 0).
The correct answer is B

Question answer:
B


2. Understanding and application of Assii code

When the following program is run, if 1abcedf2df <Enter> is entered, the output result is ( )

#include <stdio.h>
int main()
{
    
    
    char ch;
    while ((ch = getchar()) != '\n')
    {
    
    
        if (ch % 2 != 0 && (ch >= 'a' && ch <= 'z'))
        ch = ch - 'a' + 'A';
        putchar(ch);
    }
    printf("\n");
    return 0;
}

A: 1abcedf2df
B: 1ABCEDF2DF
C: 1AbCEdf2df
D: 1aBceDF2DF

Problem analysis:
The program first considers whether the ASCII code value of ch is an odd number, and then checks whether it is a lowercase letter. When both are satisfied, it is changed to an uppercase letter.

Question answer:
C


3. Loop jump judgment

We know that the break statement in C language can only jump out of the nearest loop, but sometimes we need to jump out of multiple loops. The correct way to jump out of multiple loops below is [Multiple Choice] ( ) A: Write the program as a
function End the function with return to jump out of loop
B: Modify the outer loop condition, for example

for( int i = 0 ; i < MAX1 ; i ++ )
{
    
    
    for( int j = 0 ; j < MAX2 ; j ++ )
    {
    
    
        if( condition )
        {
    
    
            i = MAX1;
            break;
        }
    }
}

C: Set judgment conditions in the outer loop, for example

for( ; symbol != 1 && condition2 ; )
{
    
    
    for( ; symbol != 1 && condition3 ; )
    {
    
    
        if( condition1 )
        symbol = 1 ;
    }
}

D: Add break after the outer loop, for example

for( ; condition2 ; )
{
    
    
    for( ; condition3 ; )
    {
    
    
        if( condition1 )
            symbol = 1 ;
    } 
        if(symbol == 1 )
             break ;
}

Question analysis:
This question aims to sort out the methods of jumping out of multi-level loops. Each option is correct. The code is pseudo code, and condition represents a logical expression.

Answer to the question:
ABCD


4. Number of times a number appears in an ascending array

Question link OJ link
Insert image description here

Problem analysis:
It can also be solved using traversal, but the array is in non-descending order. The idea of ​​using binary search is the best. First find the leftmost digital position by binary search, and then binary search the rightmost digital position. The subtraction of the two positions + 1 is the length. If
the middle value is larger than the value you are looking for: the number you are looking for must be on the right, left = mid + 1;
if the middle value is smaller than the value you are looking for: then the number you are looking for must be on the left, right = mid - 1;
the middle value is the same as the value you are looking for. The values ​​are the same:
the leftmost number to be found: if mid is left, just return mid, otherwise reset right=mid-1, and continuously shift the center to the left. The rightmost
number to find: if mid is right, just return mid. , otherwise reset left=mid+1 and continuously shift the center to the right.

Answer to the question:

int get_last_or_first_idx(int* data, int len, int k,int flag) {
    
    
    int left = 0, right = len - 1, mid;//左右指针下标及中间结点下标
    while (left <= right) {
    
    
        mid = left + (right - left) / 2;//找到中间结点
        if (data[mid] > k)
            right = mid - 1;//如果中间节点大于k,则将右节点左移
        else if (data[mid] < k)
            left = mid + 1;//如果中间节点小于k,则将左节点右移
        else {
    
    //如果中间节点值等于k,则判断flag的值来区分找的是哪边
            if (flag == 0) {
    
     
                if (mid == left || data[mid - 1] != k) return mid;//如果中间结点等于k,且前一个结点不等于k,以及和left位置相同,则找到最左边的k,返回下标
                else right = mid - 1;
            } else {
    
    
                if (mid == right || data[mid + 1] != k) return mid;//如果中间结点等于k,且后一个结点不等于k,以及和right位置相同,则找到最右边的k,返回下标
                else left = mid + 1;
            }
        }
    }
    return -1;
}
int GetNumberOfK(int* data, int dataLen, int k ) {
    
    
    if (dataLen == 0) return 0;
    int left = get_last_or_first_idx(data, dataLen, k, 0);
    int right = get_last_or_first_idx(data, dataLen, k, 1);
    if (left == -1 && right == -1) return 0; 
    return right - left + 1;//左右下标相减得到k的个数
}

5. Integer conversion

Question link: OJ link
Insert image description here

hint:

The range of A and B is between [-2147483648, 2147483647]

Question analysis:
Actually, when asking how many bits need to be modified, the question is just how many bits are different, because only how many bits are different can be modified;

Question answer:

int convertInteger(int A, int B){
    
    
    int a=A^B;//相同为0,相异为1
    double count=0;
    for(int i=0;i<32;i++){
    
    
        if((a>>i)&1==1){
    
    //通过与1与,得到求出的数二进制序列中有多少个1,从而确定个数;
            count++;
        }
    }
    return count;
}

6. Application of loop statements

Which of the following descriptions is correct ( )
A: The break statement can only be used in the loop body and the switch statement body.
B: When break appears in the switch statement body in the loop body, its function is to jump out of the switch statement body and terminate the loop body. The function of executing
the C: continue statement is to terminate the loop after executing the remaining statements in the loop body.
D: The continue statement cannot be used in while statements and do-while statements.

Question analysis:
The break statement is usually used in loop statements and switch statements. When break is used in a switch statement, the program can jump out of the switch and execute the statements after the switch;
when break is used in a do-while, for, while loop statement, the program can terminate the loop and execute the statements after the loop. That is, the loop will break out when the conditions are met.
The function of the continue statement is to skip the remaining statements in the loop body and force the execution of the next loop. There are errors in options B, C and D. Therefore, the correct answer to option A is

:
A


7. Function call

Assume that the description of the function fun and the actual parameter group is in the following form, then in the function call statement, the correct one is ( )

void fun(char ch,float x[]);
float a[10];

A: fun(“asd” , a[]); B: fun(‘x’ , A); C: fun(‘68’ , 2.8); D: fun(32 , a);

Question analysis:
To pass parameters in the array of option A, you only need to write the array name. a[] is wrong. The second parameter of option B is written in uppercase, which is wrong. The second parameter of option C is a floating point number, but the second parameter of the fun function is an array that does not match. The fun function parameter x needs to pass an array or a float * pointer. Only the form of option D is correct.
Question answer:
D


8. Intersection of two arrays

Question link: OJ link
Insert image description here

hint:

1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <=1000

Question analysis:
To pass parameters in the array of option A, you only need to write the array name. a[] is wrong. The second parameter of option B is written in uppercase, which is wrong. The second parameter of option C is a floating point number, but the second parameter of the fun function is an array that does not match. The fun function parameter x needs to pass an array or a float * pointer. Only the form of option D is correct.
Question answer:

int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {
    
    
    static int arr[1000];//定义静态,防止销毁
    *returnSize = 0;//返回数组大小
    for (int i = 0; i < nums1Size; i++) {
    
    //将nums1中的每个数遍历nums2找到相同的数
        for (int j = 0; j < nums2Size; j++) {
    
    
            if (nums1[i] == nums2[j]) {
    
    
                int k = 0;
                for (k = 0; k < *returnSize; k++) {
    
    //遍历arr数组看是否已经存在,找到了返回下标
                    if (arr[k] == nums2[j])
                        break;
                }
                if (k == *returnSize) {
    
    //如果k等于*returnSize则说明数组中不存在该数,则向数组中加入该数
                    arr[*returnSize] = nums2[j];
                    (*returnSize)++;//返回数组长度+1
                }
            }
        }
    }
    return arr;
}

9. Basics of C language

Among the following descriptions of C language functions, the correct one is [Multiple choice] ( )
A: In C language, a function generally consists of two parts, which are the function header and function body
B: the actual parameters and form of the function Parameters can have the same name
C: Variables defined in main() can be used directly in other called functions
D: In C programs, function calls cannot appear in expression statements

Question analysis:
The local variables defined in the main function are only valid in the main function, because the main function is also a function, and it has a parallel relationship with other functions. C error; when the function has a return value, it can appear in the expression, D Wrong
answer:
AB


10. Picture organization

Question link: OJ link
Insert image description here

Question analysis:
This question actually examines character sorting. Each ascii character has a corresponding ascii value in the memory, and it can be sorted through the storage of data in the memory.
Bubble sorting: Compare and exchange adjacent data, push larger or smaller data backward to the end of the array, and then start the next round of bubbling
process of big data.

Answer to the question:
Method 1:

#include <stdio.h>
void Qsort(char*arr,int len){
    
    
    for(int i=0;i<len;i++){
    
    //冒泡排序
        for(int j=0;j<len-i-1;j++){
    
    
            if(arr[j]>arr[j+1]){
    
    
                char temp=arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=temp;
            }
        }
    }
}
int main() {
    
    
    char arr[1001] = {
    
    0};
    while (scanf("%s", arr)!= EOF) {
    
    
        char digit[1001] = {
    
    0};//将数字入到该数组
        int digits = 0;//数字个数
        char upper[1001] = {
    
    0};//将大写字母入到该数组
        int uppers = 0;//大写字母个数
        char lower[1001] = {
    
    0};//将小写字母入到该数组
        int lowers = 0;//小写字母个数
        char* ptr = arr;
        while (*ptr) {
    
    //查找并添加
            if (*ptr >= '0' && *ptr <= '9') {
    
    
                digit[digits] = *ptr;
                digits++;
            }
            if (*ptr >= 'A' && *ptr <= 'Z') {
    
    
                upper[uppers] = *ptr;
                uppers++;
            }
            if (*ptr >= 'a' && *ptr <= 'z') {
    
    
                lower[lowers] = *ptr;
                lowers++;
            }
            ptr++;
        }  
        //进行排序      
        Qsort(digit,strlen(digit));
        Qsort(upper,strlen(upper));
        Qsort(lower,strlen(lower));
        //进行输出
        for (int j = 0; j < digits; j++) {
    
    
            printf("%c", digit[j]);
        }
        for (int j = 0; j < uppers; j++) {
    
    
            printf("%c", upper[j]);
        }
        for (int j = 0; j < lowers; j++) {
    
    
            printf("%c", lower[j]);
        }
    }
return 0;
}

Method Two:

#include <stdio.h>
int main()
{
    
    
    char str[1024] = {
    
    0};
    while(gets(str)) {
    
    
        int len = strlen(str);
        for (int i = 0; i < len; i++) {
    
    
            for (int j = 1; j < len - i; j++) {
    
    
                if (str[j] < str[j - 1]) {
    
    
                    char ch = str[j - 1];
                    str[j - 1] = str[j];
                    str[j] = ch;
                }
             }
         }
        printf("%s\n", str);
    }
    return 0;
}

11. Array reference

If there is a definition: int a[2][3];, the correct reference to the a array element in the following options is ( )
A: a[2][0]
B: a[2][3]
C:a[0 ][3]
D: a[1>2][1]

Question analysis:
This question mainly considers the case of array out-of-bounds access. The rows and columns of a two-dimensional array start from 0. For an array a, the maximum row subscript is 1, and the maximum column subscript is 2. In option D, 1 The value of the >2 expression is 0, which is correct. Other options may have rows and columns that are out of bounds. A means that the row is out of bounds, B means that both the row and column are out of bounds, and C is that the column is out of bounds.
Question answer:
D


12. Array reference

It is known that i and j are both integer variables. Among the following expressions, the one that is not equivalent to the subscript reference X[i][j] is [multiple choice] ( ) A: (
X [i]+j)
B:
(X+i)[j]
C: *(X+i+j)
D: ( (X+i)+j)

Question analysis:
This question tests the element access of a two-dimensional array. Option A is correct. X[i] is the array name of the i-th row. The array name represents the address of the first element. The address of an element, after +j, is the address of the element whose subscript is j in line i. The overall dereference is X[i][j], and A is correct. Option B is because [] has a higher priority than *, so the code is equivalent to **((x+i)+j), and it crosses the boundary after X+i+j, which does not mean X[i][j], so mistake. Option C is also obviously wrong. The D option is a standard pointer form for accessing an element of a two-digit array.
Answer to the question:
BC


13. Character count statistics

Question link: OJ link
Insert image description here

Question analysis:
The idea of ​​​​this question is to first create an array with a size of 128, so as to ensure that various characters from 0 to 127 can find the position corresponding to its assi value in the array, change the found position to 1, and finally change the array Add the values ​​​​in to get
the answer to the character type question:

#include <stdio.h>
int main() {
    
    
    char arr[501]={
    
    0};
    while (scanf("%s",arr) != EOF) {
    
     
        char*ptr=arr;
        int count[128]={
    
    0};
        while(*ptr){
    
    
            int temp=*ptr;//通过Assii码值作为下标找到count数组中对应的位置
            count[temp]=1;//将值变为1;
            ptr++;
        }
        int ret=0;
        for(int i=0;i<=129;i++){
    
    //遍历相加
            ret+=count[i];
        }
        printf("%d\n",ret);
    }
    return 0;
}

14. Most elements

Question link: OJ link
Insert image description here

提示:
n == nums.length
1 <= n <= 5 * 104
-109 <= nums[i] <= 109

Question analysis:
There is a number in an array that appears more than n/2 times. Starting from the 0th character, assuming it is the most numerous number, when encountering the same number, the count will be +1, and when encountering different numbers, the count will be -1. In fact, they are consuming each other. When the count reaches 0, it means that the spelling is completed and the spelling starts again from the next character. However, in the final analysis, the number of numbers that appear more than n/2 is more, so it is also the last remaining character.
Example: "23335" first starts counting 1 from character 2. If it encounters 3, it will be -1 if it is different. The process of starting from the remaining "335" will be consumed. At this time, the saved character is 3. If it encounters 3, it will count. +1, when encountering 5, the count is -1. When the count is not 0, the characters saved at the end are the characters whose number exceeds n/2.

Answer to the question:

int majorityElement(int* nums, int numsSize){
    
    
    int count=1;//记录多数元素的个数与非多数元素出现个数的差
    int more=nums[0];//将第一个作为多数元素
    int i=1;
    for(i;i<numsSize;i++){
    
    
        if(more==nums[i]){
    
    //下标对应的数为多数元素,则count++
            count++;
        }
        else{
    
    //下标对应的数不是多数元素,则count--
            count--;
        }
        if(count==0){
    
    //如果count等于0,那就可能该数不是多数元素,将下一个作为多数元素继续遍历
            more=nums[i+1];
        }
    }
    if(count>0){
    
    //多数元素的个数与非多数元素出现个数的差大于0,则说明此时记录的元素多于总数的一半,为多数元素,
        return more;
    }
    else{
    
    
       return 0;
    }
}

Summarize

Say important things three times!
come on! come on! come on!

Guess you like

Origin blog.csdn.net/mdjsmg/article/details/132533809