I had a quick question about this part of the code
why will it not do the if/else function correctly?!Code:
for (i=0; i < MAXLEN && i!= EOF; i++)
{
printf("Enter numbers between 0-9 \n"); /* Asks the users for a number 0-9 */
number = getchar() - '0'; /* sets the string to a int */
if (number >= '0' && number <= '9') /* looks for a number '0' - '9' */
{
--i;
}
else /* gives a error message if not the write parameters */
{
printf("invalid number\n");
}
getchar();
array[i] = number; /* puts the number in the array */
}
also I do not understand the point to state getchar() again after the if/else statement??
here is the whole code just for reference
Code:#include <stdio.h>
#define MAXLEN 5 /* sets the length of the array */
main()
{
int array[MAXLEN]; /* places the integeres in the array */
int i, sum, number;
for (i=0; i < MAXLEN && i!= EOF; i++)
{
printf("Enter numbers between 0-9 \n"); /* Asks the users for a number 0-9 */
number = getchar() - '0'; /* sets the string to a int */
if (number >= '0' && number <= '9') /* looks for a number '0' - '9' */
{
--i;
}
else /* gives a error message if not the write parameters */
{
printf("invalid number\n");
}
getchar();
array[i] = number; /* puts the number in the array */
}
for (i=0; i<MAXLEN && i!= EOF; i++)
{ sum += array[i]; /* will count the sum and store in the array */
printf("%d ", array[i]); /* prints out the numbers til it gets to count 5 */
}
printf("= %d\n", sum); /* will print the sum */
}
/* expected output:
Enter numbers between 0-9
1
Enter numbers between 0-9
2
Enter numbers between 0-9
5
Enter numbers between 0-9
6
Enter numbers between 0-9
3
1 2 5 6 3 = 17 */

