isdigit() Function Example in C Programming

In this source code example, we will see how to use the isdigit() function in C programming with an example.

isdigit() Function Overview

The isdigit() function is available in the <ctype.h> library in C and it determines if a given character is a decimal digit (0 through 9). 

Key Points: 

- The <ctype.h> header is required to use the isdigit() function. 

- The function takes an int as its argument, which typically represents a character. 

- If the character is a digit, the function returns a non-zero value (true); otherwise, it returns 0 (false).

Source Code Example

#include <stdio.h>
#include <ctype.h>

int main() {
    char ch;

    printf("Enter a character: ");
    scanf("%c", &ch);

    if (isdigit(ch))
        printf("'%c' is a digit.\n", ch);
    else
        printf("'%c' is not a digit.\n", ch);

    return 0;
}

Output

Enter a character: 5
'5' is a digit.

Explanation

1. We start by including the necessary header files: stdio.h for input/output operations and ctype.h for the isdigit() function.

2. Inside the main() function, a character variable ch is declared.

3. The user is prompted to provide a character.

4. The isdigit() function checks if the inputted character is a decimal digit.

5. Based on the function's result, an appropriate message is displayed. Note that the function only considers '0' through '9' as digits.


Comments