Input and Output Functions in C Programming (printf and scanf)


This tutorial explains input and output operations in C programming using the printf and scanf functions. It covers syntax, format specifiers, examples, and common mistakes, helping beginners learn how to display output and accept user input effectively in C programs.

1. Introduction to Input and Output in C

Input and output operations allow a program to:

  1. Receive data from the user
  2. Display results to the user

C provides standard input and output functions through the Standard I/O library.


#include <stdio.h>

2. printf() Function

What is printf()?

printf() is used to display output on the screen.

Syntax


printf("format string", variables);

Example 1: Simple Output


printf("Welcome to C Programming");

Example 2: Output with Variables


int age = 25;
printf("Age is %d", age);

Common Format Specifiers

SpecifierData Type
%dint
%ffloat
%lfdouble
%cchar
%sstring

Example 3: Multiple Outputs


int id = 101;
float salary = 45000.75;

printf("ID: %d\nSalary: %.2f", id, salary);

3. scanf() Function

What is scanf()?

scanf() is used to take input from the user.

Syntax


scanf("format string", &variable);

Note: & (address-of operator) is required for variables.

Example 1: Taking Integer Input


int number;
scanf("%d", &number);

Example 2: Multiple Inputs


int age;
float salary;

scanf("%d %f", &age, &salary);

Example 3: Character Input


char grade;
scanf(" %c", &grade);

(The space before %c avoids reading newline characters.)

4. Complete Example Program


#include <stdio.h>

int main() {
int age;
float salary;
char grade;

printf("Enter age: ");
scanf("%d", &age);

printf("Enter salary: ");
scanf("%f", &salary);

printf("Enter grade: ");
scanf(" %c", &grade);

printf("\nDetails Entered:\n");
printf("Age: %d\n", age);
printf("Salary: %.2f\n", salary);
printf("Grade: %c\n", grade);

return 0;
}

5. Input of Strings Using scanf


char name[20];
scanf("%s", name);

Note: scanf reads input until a space is encountered.

6. Common Mistakes to Avoid

  1. Forgetting & in scanf
  2. Using wrong format specifier
  3. Not handling spaces when reading characters
  4. Buffer overflow when reading strings

7. Difference Between printf and scanf

Featureprintfscanf
PurposeOutputInput
DirectionProgram → UserUser → Program
Uses &NoYes

Key Points to Remember

  1. Always include <stdio.h>
  2. Use correct format specifiers
  3. Use \n for new lines
  4. Be careful with input buffers