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:
- Arrays and pointers in C language;
- Function definition, parameter passing and return value in C language;
for
Loop structure ( loop) in C language ;- Conditional judgment statement (statement) in C language
if
; - 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:
- Define two integer variables
max
andidx
, which represent the currently found maximum value and its subscript respectively, and the initial values ares
the first element of the array and 0; - Use
for
a loop to traverse the arrays
, starting from the second element, andmax
compare them one by one. If the current elements[i]
is greater thanmax
, updatemax
theidx
value of the sum; - After the loop ends,
idx
the value of is returned through the pointerk
, andmax
the value of is returned.
The time complexity of this program is O ( n ) O(n)O ( n ) , wherennn iss
the 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 s
and its elements are initialized. Then call fun
the function, passing in s
the 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.