isdigit() Function
The isdigit()
function in C checks whether a given character is a decimal digit. This function is useful when validating input or parsing strings where numeric characters are expected. It determines if a character represents one of the digits 0 through 9.
Syntax of isdigit()
int isdigit(int c);
Parameters
Parameter | Description |
---|---|
c | An integer representing the character to be checked, typically cast from a char or EOF. |
The isdigit()
function examines if the character falls within the range of the decimal digits, i.e., from ‘0’ to ‘9’.
Return Value
The function returns a nonzero value (true) if the character is a decimal digit; otherwise, it returns zero (false).
Examples for isdigit()
Example 1: Checking a Single Digit Character
This example demonstrates how to use isdigit()
to check if a single character is a decimal digit.
Program
#include <stdio.h>
#include <ctype.h>
int main() {
int ch = '5';
if (isdigit(ch)) {
printf("The character %c is a digit.\n", ch);
} else {
printf("The character %c is not a digit.\n", ch);
}
return 0;
}
Explanation:
- A character variable is assigned the value
'5'
. - The
isdigit()
function checks whether'5'
is a decimal digit. - Since
'5'
is within the range of 0 to 9, the condition is true and the program prints the appropriate message.
Program Output:
The character 5 is a digit.
Example 2: Testing a Non-Digit Character
This example illustrates how isdigit()
behaves when the character checked is not a decimal digit.
Program
#include <stdio.h>
#include <ctype.h>
int main() {
int ch = 'A';
if (isdigit(ch)) {
printf("The character %c is a digit.\n", ch);
} else {
printf("The character %c is not a digit.\n", ch);
}
return 0;
}
Explanation:
- A character variable is assigned the value
'A'
. - The
isdigit()
function checks whether'A'
is a decimal digit. - Since
'A'
is not a digit, the function returns false and the program prints that the character is not a digit.
Program Output:
The character A is not a digit.
Example 3: Iterating Over a String to Identify Digits
This example demonstrates scanning through a string and using isdigit()
to determine which characters are decimal digits.
Program
#include <stdio.h>
#include <ctype.h>
int main() {
char str[] = "Room 101";
int i = 0;
while (str[i] != '\0') {
if (isdigit(str[i])) {
printf("Character '%c' is a digit.\n", str[i]);
} else {
printf("Character '%c' is not a digit.\n", str[i]);
}
i++;
}
return 0;
}
Explanation:
- A string
"Room 101"
is defined. - The program iterates through each character of the string.
- The
isdigit()
function is used to check if a character is a decimal digit. - A message is printed for each character indicating whether it is a digit or not.
Program Output:
Character 'R' is not a digit.
Character 'o' is not a digit.
Character 'o' is not a digit.
Character 'm' is not a digit.
Character ' ' is not a digit.
Character '1' is a digit.
Character '0' is a digit.
Character '1' is a digit.