CSE NotesCSE Notes
Simplifying Complexity

Input and Output statements

In C, input and output operations are typically handled using standard library functions, primarily through printf for output and scanf for input. Here’s an overview of how these functions work:

Output Statements

  1. printf Function: Used to display output to the console.
    • Basic Syntax:
      printf("format string", arguments);
    • Example:
      #include <stdio.h>
      int main()
      {
      int age = 25;
      printf("I am %d years old.\n", age); // %d is a format specifier for integers
      return 0;
      }
    • Common Format Specifiers:
      • %d: Integer
      • %f: Float
      • %c: Character
      • %s: String
      • %lf: Double
      • %%: Prints a literal %
  2. Formatting Output: You can format output using width and precision.
    float num = 123.456;
    printf("Formatted number: %.2f\n", num); // Outputs: Formatted number: 123.46

Input Statements

  1. scanf Function: Used to read input from the console.
    • Basic Syntax:
      scanf("format string", &variable);
    • Example:
      #include <stdio.h>
      int main()
      {
      int age;
      printf("Enter your age: ");
      scanf("%d", &age); // & is used to get the address of the variable
      printf("You are %d years old.\n", age);
      return 0;
      }
    • Common Format Specifiers (similar to printf):
      • %d: Reads an integer
      • %f: Reads a float
      • %c: Reads a character
      • %s: Reads a string (up to the first whitespace)
  2. Reading Strings: Use %s to read strings, but be cautious as it doesn’t check for buffer overflow. Use fgets for safer input.
    char name[50];
    printf("Enter your name: ");
    fgets(name, sizeof(name),
    stdin); // Reads a line of input safely
    printf("Hello, %s", name);

Example Program

Here’s a simple program demonstrating both input and output:

#include <stdio.h>
int main()
{
char name[50];

int age;

// Input

printf("Enter your name: ");
fgets(name, sizeof(name), stdin); // Safer way to read strings
printf("Enter your age: ");

scanf("%d", &age);

// Output

printf("Hello, %sYou are %d years old.\n", name, age);

return 0;
}

Summary

  • Output: Use printf for formatted output to the console.
  • Input: Use scanf for reading formatted input, and prefer fgets for reading strings to avoid buffer overflows.