I am new to C programming as you can already guess by my question. I am trying to enter a valid pin of 4 digits e.g. 9999. However, if the first digit is a zero i.e. 0111 the logic in my program doesn't increment counter. In a nutshell I am stuck on how I can account for a pin that begins with a zero. I could add a piece of error checking stating to the user that the pin must not begin with a zero but I don't want to resort to that if its possible.
Here is what I have so far:
/*
Program name: Count num of digits
*/
#include <stdio.h>
#define PIN_LENGTH 4
int main()
{
int pin = 0;
int counter = 0;
printf("Enter your PIN: ");
scanf("%d", &pin);
while(pin != 0)
{
pin = pin / 10;
counter++;
}
if(counter == PIN_LENGTH)
{
printf("Valid pin of %d digits\n", counter);
}
else
{
printf("Invalid pin of %d digits\n", counter);
}
return(0);
}
As you can see I divide the pin number by 10 and assign the new value into pin.
- 9999 divided by 10 = 999 (int truncates decimal part) and counter = 1
- 999 divided by 10 = 99 (int truncates decimal part) and counter = 2
- 99 divided by 10 = 9 (int truncates decimal part) and counter = 3
- 9 divided by 10 = 0 (int truncates decimal part) and counter = 4
Then I compare it to the symbolic name value which is 4 and if they are the same length I say its valid, and if not, its not valid.
But how do I account for a pin beginning with zero...