Determine Integer or Float in C

CCBeginner
Practice Now

Introduction

In this lab, we will write a C program that identifies whether a user-input number is an integer or a float. This is a fundamental concept in programming where different data types have different memory requirements and behaviors.

We will focus on detecting the presence of a decimal point in the input to determine if the number is a floating-point value. This lab introduces you to basic string handling in C, user input processing, and conditional logic.

By the end of this lab, you will understand how to:

  • Read user input as a string in C
  • Check for specific characters within a string
  • Use conditional logic to make decisions based on input

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("C")) -.-> c/FileHandlingGroup(["File Handling"]) c(("C")) -.-> c/UserInteractionGroup(["User Interaction"]) c(("C")) -.-> c/BasicsGroup(["Basics"]) c(("C")) -.-> c/ControlFlowGroup(["Control Flow"]) c(("C")) -.-> c/CompoundTypesGroup(["Compound Types"]) c/BasicsGroup -.-> c/variables("Variables") c/BasicsGroup -.-> c/operators("Operators") c/ControlFlowGroup -.-> c/if_else("If...Else") c/ControlFlowGroup -.-> c/for_loop("For Loop") c/ControlFlowGroup -.-> c/while_loop("While Loop") c/CompoundTypesGroup -.-> c/arrays("Arrays") c/FileHandlingGroup -.-> c/create_files("Create Files") c/UserInteractionGroup -.-> c/user_input("User Input") c/UserInteractionGroup -.-> c/output("Output") subgraph Lab Skills c/variables -.-> lab-123267{{"Determine Integer or Float in C"}} c/operators -.-> lab-123267{{"Determine Integer or Float in C"}} c/if_else -.-> lab-123267{{"Determine Integer or Float in C"}} c/for_loop -.-> lab-123267{{"Determine Integer or Float in C"}} c/while_loop -.-> lab-123267{{"Determine Integer or Float in C"}} c/arrays -.-> lab-123267{{"Determine Integer or Float in C"}} c/create_files -.-> lab-123267{{"Determine Integer or Float in C"}} c/user_input -.-> lab-123267{{"Determine Integer or Float in C"}} c/output -.-> lab-123267{{"Determine Integer or Float in C"}} end

Create and Open the C Program File

Let's start by creating a new C file for our program. We'll name it main.c and place it in the project directory.

  1. First, make sure you're in the project directory:
cd ~/project
  1. Now, in the WebIDE, click on the "File" menu, select "New File", and name it main.c. Alternatively, you can use the "New File" icon in the file explorer sidebar.

  2. The file editor will open automatically. Let's add the required header files to our program:

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

These header files are essential for our program:

  • stdio.h provides functions for standard input and output operations like printf() and scanf().
  • string.h provides functions for string manipulation, though in this simple program, we'll mainly use it for string length calculation.

Notice that we didn't include conio.h as mentioned in the original template. This is because conio.h is not a standard C library and is not available on many systems, including our Ubuntu environment.

Adding the Main Function and Declaring Variables

Now that we have our header files, let's add the main() function and declare the variables we'll need for our program.

Add the following code to your main.c file:

int main() {
    char number[20];  // Array to store the input number as a string
    int flag = 0;     // Flag to track if a decimal point is found (0 = not found, 1 = found)
    int i;            // Loop counter variable

    // Program will continue here...

    return 0;
}

Let's understand these variables:

  • number[20]: This is a character array (string) that will store the user's input. We've increased the size to 20 characters to accommodate larger numbers.
  • flag: This integer variable will act as a boolean flag. If we find a decimal point in the input, we'll set this to 1.
  • i: A simple counter variable for our loop.

The main() function is the entry point of our C program. All the code we write will be inside this function. The return 0 statement at the end indicates that the program executed successfully.

Your file should now look like this:

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

int main() {
    char number[20];  // Array to store the input number as a string
    int flag = 0;     // Flag to track if a decimal point is found (0 = not found, 1 = found)
    int i;            // Loop counter variable

    // Program will continue here...

    return 0;
}

Implementing the Program Logic

Now, let's add the remaining code to read the user input and determine if the number is an integer or a float.

Replace the "Program will continue here..." comment with the following code:

    // Prompt the user to enter a number
    printf("Enter a number: ");
    scanf("%s", number);

    // Check each character in the number string for a decimal point
    for(i = 0; number[i] != '\0'; i++) {
        if(number[i] == '.') {
            flag = 1;  // Set flag to 1 if decimal point is found
            break;
        }
    }

    // Display the result based on the flag value
    if(flag) {
        printf("The entered number is a floating point number.\n");
    } else {
        printf("The entered number is an integer number.\n");
    }

Let's examine what this code does:

  1. The printf() statement displays a prompt asking the user to enter a number.
  2. The scanf() function reads the user's input as a string and stores it in the number array.
  3. We use a for loop to iterate through each character of the string until we reach the null terminator ('\0').
  4. Inside the loop, we check if each character is a decimal point ('.'). If found, we set the flag to 1 and exit the loop.
  5. Finally, we use an if statement to check if the flag is set. If it is, we inform the user that the number is a floating point; otherwise, it's an integer.

Your complete program should now look like this:

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

int main() {
    char number[20];  // Array to store the input number as a string
    int flag = 0;     // Flag to track if a decimal point is found (0 = not found, 1 = found)
    int i;            // Loop counter variable

    // Prompt the user to enter a number
    printf("Enter a number: ");
    scanf("%s", number);

    // Check each character in the number string for a decimal point
    for(i = 0; number[i] != '\0'; i++) {
        if(number[i] == '.') {
            flag = 1;  // Set flag to 1 if decimal point is found
            break;
        }
    }

    // Display the result based on the flag value
    if(flag) {
        printf("The entered number is a floating point number.\n");
    } else {
        printf("The entered number is an integer number.\n");
    }

    return 0;
}

Compiling and Running the Program

Now that we've written our program, let's compile and run it to see it in action.

  1. First, save the file if you haven't already (Ctrl+S or File > Save).

  2. Open a terminal in the WebIDE (if it's not already open).

  3. Navigate to the project directory and compile the program using the GCC compiler:

cd ~/project
gcc main.c -o main

The gcc command compiles our C source file, and the -o main option specifies that the output executable should be named main.

  1. Now run the compiled program:
./main
  1. When prompted, enter a number. Try an integer first, like 42:
Enter a number: 42

You should see the output:

The entered number is an integer number.
  1. Run the program again and try a floating-point number like 3.14:
./main
Enter a number: 3.14

You should see the output:

The entered number is a floating point number.

The program correctly identifies integers and floating-point numbers based on the presence of a decimal point in the input.

Enhancing the Program

Let's enhance our program to make it more user-friendly and robust. We'll add a loop so the user can check multiple numbers without restarting the program, and we'll also add input validation.

Update your main.c file with the following code:

#include <stdio.h>
#include <string.h>
#include <ctype.h>  // For isdigit function

int main() {
    char number[20];
    int flag, i;
    char choice;

    do {
        flag = 0;  // Reset flag for each iteration

        // Prompt the user to enter a number
        printf("\nEnter a number: ");
        scanf("%s", number);

        // Input validation - check if the input contains only digits and at most one decimal point
        int valid = 1;
        int decimal_count = 0;

        for(i = 0; number[i] != '\0'; i++) {
            if(number[i] == '.') {
                decimal_count++;
                if(decimal_count > 1) {
                    valid = 0;
                    break;
                }
            } else if(!isdigit(number[i])) {
                valid = 0;
                break;
            }
        }

        if(!valid) {
            printf("Invalid input! Please enter a valid number.\n");
            continue;
        }

        // Check if the number is integer or float
        for(i = 0; number[i] != '\0'; i++) {
            if(number[i] == '.') {
                flag = 1;
                break;
            }
        }

        // Display the result
        if(flag) {
            printf("The entered number is a floating point number.\n");
        } else {
            printf("The entered number is an integer number.\n");
        }

        // Ask if the user wants to continue
        printf("\nDo you want to check another number? (y/n): ");
        scanf(" %c", &choice);

    } while(choice == 'y' || choice == 'Y');

    printf("\nThank you for using the program!\n");
    return 0;
}

This enhanced version includes:

  1. A do-while loop that allows the user to check multiple numbers.
  2. Input validation to ensure that the input contains only digits and at most one decimal point.
  3. A more user-friendly interface with clearer prompts and feedback.

Compile and run this enhanced version:

cd ~/project
gcc main.c -o main
./main

Test it with various inputs, including:

  • Integer numbers like 42
  • Floating-point numbers like 3.14
  • Invalid inputs like abc or 1.2.3

The program should appropriately handle all these cases and allow you to continue checking numbers until you choose to exit.

Summary

In this lab, you successfully created a C program that determines whether a user-input number is an integer or a floating-point number. Here are the key concepts you learned:

  1. String Handling in C: You used character arrays to store and process string data, iterating through each character to check its properties.

  2. User Input Processing: You learned how to prompt for and read user input using the scanf() function.

  3. Control Structures: You implemented conditional statements (if-else) and loops (for, do-while) to control the flow of your program.

  4. Input Validation: In the enhanced version, you added checks to ensure that the user input is a valid number.

  5. Program Enhancement: You improved the basic program by adding features like a user loop and input validation, making it more robust and user-friendly.

These concepts are fundamental to many programming tasks and will serve as a solid foundation as you continue learning C programming. The ability to distinguish between different types of data is particularly important in strongly-typed languages like C, where different data types have different memory allocations and behaviors.