Question 7: Please write a function int fun(intss, int t, int k) in C, which is used to find the subscript of the largest element of the array in the array and store it in the storage unit pointed to by k.

Please add a picture description

C test questions

Question 7请用C编写一个函数int fun(intss,int t,int k),用来求出数组的最大元素在数组中的下标并存放在k所指的存储单元中。

ChatGPT answers as follows:

The following knowledge points were mainly investigated:

  1. Arrays and pointers in C language;
  2. Function definition, parameter passing and return value in C language;
  3. forLoop structure ( loop) in C language ;
  4. Conditional judgment statement (statement) in C language if;
  5. Pointer manipulation in C language (using pointers to indirectly access and modify the value of variables).

At the same time, the code also involves some basic programming ideas, such as how to find the maximum value and its subscript in the array, and return the subscript through the pointer. These ideas are also very common in actual programming.

The problem-solving idea of ​​the program:

  1. Define two integer variables maxand idx, which represent the currently found maximum value and its subscript respectively, and the initial values ​​are sthe first element of the array and 0;
  2. Use fora loop to traverse the array s, starting from the second element, and maxcompare them one by one. If the current element s[i]is greater than max, update maxthe idxvalue of the sum;
  3. After the loop ends, idxthe value of is returned through the pointer k, and maxthe value of is returned.

The time complexity of this program is O ( n ) O(n)O ( n ) , wherennn issthe length of the array.

Solution: Complete C code:

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

int fun(int s[], int t, int *k) {
    
    
    int maxIndex = 0;
    for (int i = 1; i < t; i++) {
    
    
        if (s[i] > s[maxIndex]) {
    
    
            maxIndex = i;
        }
    }
    *k = maxIndex;
    return s[maxIndex];
}

int main() {
    
    
    int s[] = {
    
    876, 675, 896, 101, 301, 401, 980, 431, 451, 777};
    int t = sizeof(s) / sizeof(int);
    int k;
    int max = fun(s, t, &k);
    printf("maxIndex: %d, max: %d\n", k, max);
    return 0;
}

In the main function, an integer array is defined sand its elements are initialized. Then call funthe function, passing in sthe array, the number of elements t, and a pointer to the storage subscript k. Finally, output the index of the maximum value and the maximum value itself.

If you are satisfied with the answer, please correct me.

Guess you like

Origin blog.csdn.net/zp1990412/article/details/130745198