Determine Integer or Float in C

CCBeginner
Practice Now

Introduction

In this lab, we will write a C program to check if the input number is an integer or a float. We will be using basic string manipulation techniques to check for the presence of a decimal point in the user input.

Note: You need to create the file ~/project/main.c yourself to practice coding and learn how to compile and run it using gcc.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

Include required libraries

We need to include the standard input/output header file, stdio.h, for standard I/O operations, the conio.h header file to include the console input/output operations, and the string.h header file to perform string manipulations.

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

Declare variables

We will declare the required variables for our program. We will use a char data type to store the input number in string format, number. A flag variable of int data type is used to track if a decimal point is present in the input. length of the string is stored in another variable. Finally, we declare a loop counter variable, i.

char number[10];
int flag = 0;
int length, i = 0;

Read user input

We will prompt the user to enter a number and read it with scanf() function.

printf("\n\nEnter a number: ");
scanf("%s", number);

Find if the input number is float or integer

We use a while loop to check each character of the number string for the presence of the decimal point. If a decimal point is found, we set the flag variable to 1 and break out of the while loop.

while(number[i++] != '\0')
{
    if(number[i] == '.')
    {
        flag = 1;
        break;
    }
}

We then use a conditional if statement to check if flag is 1 or 0. If flag is 1, we print that the entered number is a floating point number. Otherwise, we print that the entered number is an integer number.

if(flag)
    printf("\n\n\n\tEntered Number is a Floating point Number\n\n");
else
    printf("\n\n\n\tEntered Number is a integer Number\n\n");

Display output

Finally, we display the output on the console.

printf("\n\n\n\n\t\t\tCoding is Fun !\n\n\n");
return 0;

Summary

In this lab, we learned to write C code to check if the input number is a float or an integer. The program scanned the user-provided number as a string and then analyzed its content to see if it had a decimal point. If it did have a decimal point, the program identified it as a floating-point number; if it did not have a decimal point, it was identified as an integer. We hope you have understood this concept and can use it to develop your own programs.

Other C Tutorials you may like