1

I am trying to validate the input of the array to only allow an input of only one single digit integer (either 2 or 3) at each index of the array. For example a = [2,3,2,3,2,2,2,2,2,3]. My attempt is below.

int main()
{
        int a[10];
        int b;
        bool c= false;
        printf( "Please the 10 values: \n");
        while(c)
        {
            for(b=0;b<10;b++)
            {

                scanf("%d", &a[b]);//enter each value individually
                if(&a[b]==2 || &a[b]==3)
                {
                    c= true;
                }
                else
                {
                    printf("please the value");
                    scanf("%d", &a[b]);
                    c= false;
                }
            }

        }
}

2 Answers 2

2

If you want to check the value, you have to change your code

if(&a[b]==2 || &a[b]==3)

to

if((a[b]==2) || (a[b]==3))   //no need for address of (&) operator

However, for an array like int a[10];, using

 for(b=0;b<32;b++)

will overrun the allocated memory and you'll run into undefined behavior.

That said, the else part is not checking the validity of the repeated input. You need to take care of that, too.

Also, the recommended signature of main() is int main(void).

Sign up to request clarification or add additional context in comments.

2 Comments

Ahh it was supposed to be 32 at first but I changed it to 10 I'll edit the code now. My mistake sorry
You are using unnecessary parentheses. Just do if(a[b] == 2 || a[b] == 3)
0

Increment the counter b when there is a correct value.
scanf will return the number of items successfully scanned. In this case one.
If scanf does not return one, the else will read a character and then scanf can try again.

int main()
{
    int a[10];
    int b = 0;
    printf( "Please the 10 values: \n");
    while(b < 10)
    {
        printf( "enter value for a[%d]\n", b);
        if ( ( scanf("%d", &a[b])) == 1) {//enter each value individually
            if(a[b]==2 || a[b]==3)
            {
                b++;//correct value increment b
            }
        }
        else //scanf failed to read an int
        {
            getchar ( );//read a character and try again
        } 
    }
}

2 Comments

When I enter a letter I still get an error. Is there anyway to avoid that?
I'm also trying to solve the problem using for validating for loops.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.