Practice C Programming

Ask a user to enter a hexadecimal number. If the value entered is a hexadecimal number, display a message “Hi Hexadecimal”; otherwise, display “This is not a hexadecimal.”.

You can do this as like below:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int isHexa(char *hexa, int length)
{
    int i;

    for (i = 0; i < length; i++)
    {
        if (
            (hexa[i] < '0' || hexa[i] > '9') &&
            (hexa[i] < 'A' || hexa[i] > 'F') &&
            (hexa[i] < 'a' || hexa[i] > 'f'))
        {
            // not hexadecimal string
            return 0;
        }
    }

    // hexadecimal string
    return 1;
}
int main()
{
    char *hexString = malloc(sizeof(char) * 50);

    printf("Enter the hex string: ");
    scanf("%50s", hexString);

    if (isHexa(hexString, strlen(hexString)) == 1)
    {
        printf("This is hexadecimal");
    }
    else
    {
        printf("This is not a hexadecimal");
    }
}

Sample output:

Enter the hex string: hhshsh
This is not a hexadecimal                                                                                                

Enter the hex string: ab1234
This is hexadecimal                                                                                                      

Enter the hex string: AB1234
This is hexadecimal