C Program to Print an Integer (Entered by the User)

Updated on September 30, 2024
Print an Integer (Entered by the User) header image

Introduction

In C programming, accepting user input and displaying it back to the user is a fundamental concept implemented in many beginner projects and applications. This basic operation helps new programmers understand how to interact with users effectively and process data within their programs.

In this article, you will learn how to create a simple C program that prompts a user to enter an integer and then prints that integer on the screen. Explore hands-on examples to solidify your understanding of handling user input and output in C.

Creating the Program

Prompt the User for an Integer

  1. Begin by including the necessary header files. stdio.h is essential because it contains declarations for input/output functions.

  2. Declare a main function which is the entry point of any C program.

  3. Inside the main function, declare an integer variable to store the user input.

  4. Use printf function to prompt the user to enter an integer.

  5. Utilize scanf to read and store the user-input integer.

    c
    #include <stdio.h>
    
    int main() {
        int number;
        printf("Enter an integer: ");  
        scanf("%d", &number);
    }
    

    This code snippet initializes a variable number and then uses printf to provide a prompt. scanf with %d reads an integer from the input and stores it in the variable number.

Display the Entered Integer

  1. After storing the input, use printf again to display the entered integer.

  2. End the main function with a return statement to exit the program.

    c
    #include <stdio.h>
    
    int main() {
        int number;
        printf("Enter an integer: ");
        scanf("%d", &number);
        printf("You entered: %d", number);
        return 0;
    }
    

    Here, the entered integer is displayed using printf where %d formats the integer for output. The program then ends with return 0, signaling successful execution.

Conclusion

The C program demonstrated above effectively gathers an integer input from the user and displays it. This basic pattern is fundamental in learning C programming, as it combines both input and output operations which are essential in many applications. Follow these examples to create robust programs that can interact with users by accepting and processing user inputs efficiently.