“How to search for a specific number in an array in the C language?”

In C language, a loop structure can be used to traverse an array, comparing each element with a target value until a matching element is found. Here is an example code:

#include <stdio.h>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int target = 3;
    int length = sizeof(arr) / sizeof(arr[0]);
    int i;
    int found = 0;

    for (i = 0; i < length; i++) {
        if (arr[i] == target) {
            found = 1;
            break;
        }
    }

    if (found) {
        printf("找到了目标数值 %d,该数字在数组中的索引为 %d\n", target, i);
    } else {
        printf("未找到目标数值 %d\n", target);
    }

    return 0;
}

In the code above, we defined an integer array called ‘arr’ and a target value ‘target’. We then looped through the array, comparing each element with the target value. If a match was found, we set the ‘found’ flag to 1 and broke out of the loop. Finally, we used the value of ‘found’ to determine if the target value was found, and output the corresponding result.

广告
Closing in 10 seconds
bannerAds