Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if the user input matches one of the elements in the array

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);
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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[]) {
    for (int i = 0; i < 3; 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 };
    int num;

    for (int i = 0; i < 3; 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);
    } else {
        // input missing or not a number
        printf("Invalid input\n");
    }
    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading