Mastering User Input with `scanf` in C

Sep 16, 2024

Lecture on Using scanf in C Programming

Introduction

  • Purpose: Understand how to allow user inputs in C programs using the scanf statement.
  • Context: Writing code that allows users (who may not know how to code) to input data like numbers.
  • Goal: Enable users to input numbers into a C program without recompiling the code.

Setup

  • Opening Command Prompt:
    • Open command prompt via cmd.
    • Navigate to directories using cd desktop and cd c\code.
  • Running the Program:
    • Use batch file: make project.bat average_width_scanf
    • Open the C file average_with_scanf.c in Notepad++.
  • Template: Use average_v2c from previous work.
    • Copy (Ctrl+A, Ctrl+C) and paste (Ctrl+V) the code into the new file.

Code Modifications

  • Changing Program Content:
    • Modify the program to take 3 numbers instead of 5.
    • Remove hard-coded assignments (e.g., a[0] = 3, a[1] = 5, a[2] = 8).
  • Implementing scanf Loop:
    • Use a for loop to input numbers.
    • scanf Syntax:
      • %f: Expecting a float.
      • %d: Expecting an integer.
      • %g: Float that handles both regular and exponential notation.
      • Include & before variable names in scanf (e.g., &a[i]).

Prompting User

  • Initial Setup: Program waits at scanf for user input.
  • Improving User Interaction:
    • Add printf before scanf to prompt users.
    • Avoid technical terms (e.g., index numbers) in user prompts.
    • Example: Use a counter variable j (i+1) to display user-friendly prompts.

Compiling and Running the Program

  • Compilation:
    • gcc average_with_scanf.c -o average_with_scanf
  • Execution: Run program and input numbers when prompted.
  • Output: Program calculates the average of the input numbers.

Conclusion

  • Usefulness: scanf is less common now for terminal input.
  • Next Steps: More common practice is file input; will cover scanning from files in subsequent lessons.