cif-statement

Why is this code still adding 1 to i even when the if statment that does so isnt called in C?


So this is my code:

#include <stdio.h>
#define SIZE 10

int main(void)
{
    int x,p[SIZE],i=0;
    printf("type some characters\n");
    while((x = getchar()) != EOF && i<SIZE)
    {
        if(x<'0' || x>'9')
        {
            p[i]=x;
            i++;
        }
        else
        {
            printf("this number is not valid %d\n",i);
        }
    }
    for(i=0;i<SIZE;i++)
    {
        putchar(p[j]);
    }
    return 0;
}

when you type a "number character" it is suppose to not add to the counter but instead of doing that it add 1 when i type in a number character and adds 2 when i add in any other time of character.


Solution

  • You are typing one character per line, with a Return/Enter after each character. Each time you do that, the program receives two characters: The first character you typed and a newline character for the Return/Enter.

    Since two characters are sent, the program executes two iterations of the loop. With a digit character, the program prints the “not valid” message for the digit and enters the newline character in the array, thus advancing i by 1. With a non-digit character, the program enters both that character and the newline character in the array, thus advancing i by 2.

    If you want the user to enter the input that way, you need to modify the program to ignore newline characters.