# Thread: For loop with nested switch statement help

1. ## For loop with nested switch statement help

When i get to the 9th number and enter anything other than an integer, it's printing a 0
Input integers separated by a space to store into Array A: 8 8 8 8 8 8 8 8 8 .
8 8 8 8 8 8 8 8 8 0
10

Input integers separated by a space to store into Array A: 1 2 3 4 5 6 7 8 9 a
1 2 3 4 5 6 7 8 9 0

Code:
```#include<stdio.h>
#include<stdlib.h>

int main(void)
{
int i = 0, A[10], B[10];
int countA = 0, countB = 0;

printf("Please enter up to 10 integers separated by a space, when done hit any char in place of an integer\n");
printf("Input integers separated by a space to store into Array A: ");
fflush(stdout);

for(i=0; i<10; i++)
{
scanf("%d", &A[i]);
switch(A[i])
{
case 0:
//    printf("%d ", A[i]);
break;
case 1:
//    printf("%d ", A[i]);
break;
case 2:
//    printf("%d ", A[i]);
break;
case 3:
//    printf("%d ", A[i]);
break;
case 4:
//    printf("%d ", A[i]);
break;
case 5:
//    printf("%d ", A[i]);
break;
case 6:
//    printf("%d ", A[i]);
break;
case 7:
//    printf("%d ", A[i]);
break;
case 8:
//    printf("%d ", A[i]);
break;
case 9:
//    printf("%d ", A[i]);
break;
default:
goto ArrayB;
}
countA++;
}

ArrayB:
//printf("\n");
for(int z=0;z<countA;z++)
{
printf("%d ", A[z]);
}

return 0;
}```

2. When presented with anything other than a digit, your scanf is going to return a status you're ignoring.

You would be wise to check this.

3. I think thats what im trying to figure out, i reckon i need another case statement, or if statement, but don't know how to write it.

if(A[i] == not an integer)
{
goto blah;
}

4. I guess a better question would be, why does it sometimes assume a = 0?

5. > I guess a better question would be, why does it sometimes assume a = 0?
It doesn't.
If the scanf fails, then the particular A[i] that you tried to write to is left in an undefined state (but probably not modified). But since you didn't initialise your array to begin with, you still don't know what it's value is (but zero is a not unreasonable guess in a small program).

What you should be doing is reading the scanf manual.
RETURN VALUE

On success, these functions return the number of input items
successfully matched and assigned; this can be fewer than provided
for, or even zero, in the event of an early matching failure.

The value EOF is returned if the end of input is reached before
either the first successful conversion or a matching failure occurs.
EOF is also returned if a read error occurs, in which case the error
indicator for the stream (see ferror(3)) is set, and errno is set to
indicate the error.
So,
Code:
```if ( scanf("%d", &A[i]) == 1 ) {
// do something with successful input
} else {
// looks like breaking out of your for loop is appropriate
// in this case.
}```