In a previous article, I have mentioned basic C programming examples and now in this article, I have provided sample code to check if a input type is int or float in C.

Check if the input is int or float in C using for loop

In the given program, we are initializing a char array and a flag

Then we ask the user to enter the number and save it in array as char using scanf

Once we have the character array we loop through each character and check if it doesn't contain "." if it contains "decimal (.)" it means it is floating-point number else int

#include <stdio.h>

int main() {
    char number[100];
    int flag = 0;

    printf("Enter the number to check itself: ");
    scanf("%s", number);

    //loop through each character of input
    for (int i = 0; number[i] != 0; i++) {
    //if decimal "." is fount, it means it is float
        if (number[i] == '.') {
            flag = 1;
            break;
        }
    }

    if (flag)
    {
       printf("\n%s is a floating-point number.\n", number);
    }
    else{
       printf("\n%s is an integer number.\n", number);
    }

    return 0;
}

Output:

check-if-int-c-program-min.png

Check If the input is int using isdigit in C

We can also use "isdigit" which is a library function and checks whether a character is numeric character(0-9) or not.

So here is the code for it

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

bool digit_check(char key[])
{
    for(int i = 0; i < strlen(key); i++)
    {
        if(isdigit(key[i])==0)
        {
            return false;
        }
    }
    return true;
}

void main()
{
    char number[10];
    do{
        printf("Input a number: ");
        scanf("%s",number);
    }
    while (!digit_check(number));
    printf("Input is number now\n");

}

In the above code we are using do-while loop, and it check if user input number or not.

If user doesn't input number, it will keep asking user "Input a number", until a valid int is input by user.

Take a look at below output

input-is-number-isdigit-min.png

As you can see in the above output, the program keeps asking the user to enter valid input, until it finds one.

You may also like to read:

Star program in C (Pyramid pattern program examples)

Program for Matrix multiplication in C (With & Without pointers)

Linked list program in C (Algorithm & Code sample)

File program in C (Open, Read and Write)

Program & algorithm for Quick sort in C

Sorting array elements in ascending order program in C

Fibonacci Series program in C ( With and Without recursion)

Simple C programming examples with output (must read for beginners)