How to use the “in” function in C language?

In the C language, there is no built-in “in” operator. However, you can simulate the “in” operation using conditional statements and logical operators.

One common way to simulate the “in” operation is by using conditional statements and logical operators.

#include <stdio.h>

int main() {
    int num = 5;
    int arr[] = {1, 3, 5, 7, 9};

    int isInArray = 0; // 初始化为假

    for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
        if (num == arr[i]) {
            isInArray = 1; // 如果找到相等的元素,将isInArray设置为真
            break; // 找到后可以提前结束循环
        }
    }

    if (isInArray) {
        printf("%d is in the array.", num);
    } else {
        printf("%d is not in the array.", num);
    }

    return 0;
}

Iterating through the array, checking if each element is equal to the given value. If a matching element is found, the isInArray variable is set to true. Finally, output the result based on the value of isInArray.

This is just one method, and different implementation approaches can be chosen based on specific circumstances.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds