C Input and Output

Beginner
6 min read
Updated: Nov 2026
1 example

What Is Input and Output?

C performs I/O through the standard library in <stdio.h>. printf writes formatted text to the screen, and scanf reads formatted input. For whole lines, fgets is safer than scanf("%s") because you can limit the length.

Remember
printf("Age: %d\n", age);      /* output */
scanf("%d", &age);            /* input: note the & */
fgets(buf, sizeof buf, stdin);/* read a line safely */
putchar('A');  int ch = getchar();

Cheat Sheet

Keep these facts handy while you work with Input and Output in C.

TopicDetail
Outputprintf(format, args...)
Inputscanf(format, &var...) returns items read
Line inputfgets(buffer, size, stdin)
Header#include <stdio.h>

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Format Specifiers.

Example 1 — Read two numbers and print their sum

The user types 7 5 and presses Enter.

C
#include <stdio.h>

int main(void) {
    int a, b;

    printf("Enter two numbers: ");
    if (scanf("%d %d", &a, &b) != 2) {
        printf("Invalid input\n");
        return 1;
    }
    printf("Sum = %d\n", a + b);
    return 0;
}

How It Works

  1. scanf needs the address of each variable, so use &a and &b.
  2. It returns how many values it read; check for 2.
  3. Input 7 5 is shown after the prompt; the program prints Sum = 12.

Edge Cases & Pitfalls

Check these before relying on Input and Output in real programs.

&

Forgetting &

scanf("%d", n) passes the value of n as an address and crashes. Use &n for non-array variables.

%s

Unbounded %s

scanf("%s", buf) can overflow buf. Use %19s with a width or fgets.

Key Takeaways

  • printf: formatted output.
  • scanf: needs & and a return-value check.
  • fgets: safest for reading lines.

One line: C performs I/O through the standard library in <stdio.h>.

Frequently Asked Questions

scanf must store the value in your variable, so it needs the variable's address. Arrays already decay to addresses, so strings read into arrays do not use &.
Use fgets(buffer, sizeof buffer, stdin). scanf("%s") stops at the first whitespace.
Continue with "C Format Specifiers" next. The % codes that tell printf and scanf how to treat each value. The C Fundamentals hub lists every topic in order.

Next: Format Specifiers

The % codes that tell printf and scanf how to treat each value.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful