Home > Blockchain >  Check if the user input matches one of the elements in the array
Check if the user input matches one of the elements in the array

Time:01-03

If the user inputs a value that matches with an int in the array continue the program else quit the program. My issue is that the function loops the whole array and if it finds one of the values doesnt match it will quit.

//Check if the user input matches with one of the ints in the array
void check(int num, int arr[]) {
    for (int i = 0; i < 3; i  ) {
        if (arr[i] != num) {
            printf("Invalid input");
            exit(0);
        }
    }
}

void main() {
    int arr[3] = { 1, 2, 3 };
    int num = 0;

    for (int i = 0; i < 3; i  ) {
        printf("%d ", arr[i]);
    }

    printf("\nPLease enter a value which matches with the array %d", num);
    scanf("%d", &num);
    check(num, arr);
}

CodePudding user response:

You have a logic flaw in the check function: you should output the message and quit if none of the values match the input. You instead do this if one of the values does not match. The check always fails.

Here is a modified version:

#include <stdio.h>

//Check if the user input matches with one of the ints in the array
void check(int num, const int arr[], size_t len) {
    for (size_t i = 0; i < len; i  ) {
        if (arr[i] == num) {
            // value found, just return to the caller
            return;
        }
    }
    // if we get here, none of the values in the array match num
    printf("Invalid input: %d\n", num);
    exit(1);
}

int main() {
    int arr[3] = { 1, 2, 3 };
    size_t len = sizeof(arr) / sizeof(*arr); // length of the array
    int num;

    for (size_t i = 0; i < len; i  ) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    printf("Please enter a value which matches with the array: ");
    if (scanf("%d", &num) == 1) {
        check(num, arr, len);
    } else {
        // input missing or not a number
        printf("Invalid input\n");
    }
    return 0;
}

CodePudding user response:

void check(int num, int arr[]) {
    for (int i = 0; i < 3; i  ) {
        if (arr[i] == num) {
            return;
        }
    }
    printf("Invalid input");
    exit(0);
}

Your issue is that checks a single element and judges the input on that specific value. If it has run through each value and the function has still not returned, there is not match and we can exit the program.

CodePudding user response:

You are right, you do exit once arr[i] != num (When the value is not the same as the i:th element in the array).

So, you could change it to: arr[i] == num. If it is the same, perhaps print "You got it!", and a return afterwards.

  •  Tags:  
  • c
  • Related