Read User Input

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to read user input in C programming language using the scanf() function. The scanf() function is used to read input from the user and is defined in the standard input/output library stdio.h. C language is a strongly typed language and supports different data types. In this example, we will use the char and int data types to read and display user input.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/PointersandMemoryGroup(["`Pointers and Memory`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/data_types("`Data Types`") c/BasicsGroup -.-> c/operators("`Operators`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/PointersandMemoryGroup -.-> c/memory_address("`Memory Address`") c/FunctionsGroup -.-> c/function_declaration("`Function Declaration`") subgraph Lab Skills c/output -.-> lab-136075{{"`Read User Input`"}} c/data_types -.-> lab-136075{{"`Read User Input`"}} c/operators -.-> lab-136075{{"`Read User Input`"}} c/user_input -.-> lab-136075{{"`Read User Input`"}} c/memory_address -.-> lab-136075{{"`Read User Input`"}} c/function_declaration -.-> lab-136075{{"`Read User Input`"}} end

Read User Input

In this step, you will write a program that reads user input and prints a greeting message.

  1. Create a file named user-input.c and open it in WebIDE.

  2. Copy and paste the following code into the file:

    #include <stdio.h>
    int main()
    {
      char name[100];
      int age;
      printf("Enter your name: ");
      scanf("%s", name);
      printf("Enter your age: ");
      scanf("%d", &age);
      printf("Hello, %s, you are %d years old.\n", name, age);
      return 0;
    }
  3. Save the file.

  4. Compile the file using the gcc compiler with the following command:

    gcc user-input.c -o user-input
  5. Run the compiled executable with the following command:

    ./user-input
  6. The program will prompt you to enter your name. Type your name and press Enter.

  7. Next, the program will prompt you to enter your age. Type your age and press Enter.

  8. The program will then output a greeting message with your name and age.

Summary

After completing this lab, you will be able to read user input in C programming language using the scanf() function. You will also have a better understanding of how to format and display user input in C.

Other C Tutorials you may like