Chapter 4: Input and Output

1. printf() – Printing Output (We Already Know Some)

printf() is used to print messages and values on the screen.

Basic Syntax:

C

Format Specifiers (very important – you must use the correct one):

Data Type Format Specifier Example What it does
int %d printf(“%d”, age); Prints integer
float %f printf(“%f”, height); Prints float (6 decimals by default)
double %lf or %f printf(“%.2lf”, pi); Prints double
char %c printf(“%c”, grade); Prints single character
string %s printf(“%s”, name); Prints string

Formatting Tricks:

  • %.2f → Show 2 decimal places
  • %10d → Right-align with 10 spaces
  • %-10s → Left-align string with 10 spaces
  • \n → New line
  • \t → Tab space

Example: Nice Formatted Output

C

Output:

text

2. scanf() – Taking Input from the User

scanf() reads input from the keyboard and stores it in variables.

Basic Syntax:

C

Important Rule: Always use & (address of) before the variable name! & tells scanf: “Put the input at this memory location.”

Format Specifiers for scanf() (same as printf):

Data Type Format Specifier
int %d
float %f
double %lf
char %c
string %s

Example 1: Simple Input

C

How it works:

  • Program prints: “Enter your age: “
  • You type 25 and press Enter
  • scanf stores 25 in the variable age
  • Then it prints: “You entered: 25”

3. Full Practical Example – Interactive Program

C

Sample Run:

text

4. Important Tips & Common Mistakes

Tip 1: Why space before %c?

C

After entering number (age), Enter key (newline) stays in buffer. Space before %c eats that newline. If you forget space → grade may take wrong value!

Tip 2: For strings with spaces (full name) Use %[^\n] or fgets() (we’ll learn fgets later – safer than scanf for strings).

Common Mistakes:

  • Forgetting & → program crashes or wrong value
  • Wrong format specifier → garbage output
  • Not putting space before %c

5. Another Fun Example – Simple Calculator

C

Today’s Homework

  1. Run the Student Details program above.
  2. Change it to ask for:
    • Your full name (use scanf(“%[^\n]”, name); – or just one word for now)
    • Your city
    • Your favorite number
    • Print everything in a beautiful format (use lines, tabs, etc.)
  3. Create a program that asks for two numbers and prints their sum, difference, product, and division (use float for division).
  4. Try forgetting the & in one scanf and see what happens (error or wrong output).

You may also like...