Home > Blockchain >  Program to add condition to digits
Program to add condition to digits

Time:10-15

I've written a program to take a 4-digit input and print the digits at 1000th, 100th, 10th and unit places. I want to add a condition that if the user inputs more or less than 4-digits, it should give output as Only 4-digits are allowed.

#include<stdio.h>

int main(){

    int a, th, h, t, u;
    printf("Enter a 4-digit number: ");
    scanf("%d", &a);

    u = a%10;
    t = (a/10)%10;
    h = (a/100)%10;
    th = (a/1000);

    printf("\nThousands = %d, Hundreds = %d, Tens = %d, Units = %d\n", th, h, t, u);

    return 0;
}

What to do?

CodePudding user response:

You can try the following code

if(a<1000 || a>9999)
{
   printf("Only 4-digits are allowed:");
}

CodePudding user response:

It depends upon whether "0999" is considered a 4-digit number. If it isn't, then any of the already-posted solutions will work. If it is, you'll have to scan the input as a string so you can test its length before you convert it to an int. You could also go this route:

char digits[5];
scanf("%c%c%c%c", &digits[0], &digits[1], &digits[2], &digits[3]);
digits[4] = '\0'; // terminate the character array.
for(int i=0; i<4; i  ) {
  if (digits[i] < '0' or digits[i] > '9') {
    //throw a fit at the user and return
  }
}

printf("thousands: %c, hundreds: %c, tens: %c, ones: %c\n", digits[0].... etc.);
  • Related