0
0
Cprogramming~5 mins

Using printf for output in C

Choose your learning style9 modes available
Introduction

We use printf to show messages or results on the screen. It helps us communicate what the program is doing.

To display a greeting message to the user.
To show the result of a calculation.
To print instructions or menus in a program.
To debug by showing variable values during program execution.
To format output nicely, like showing numbers with decimals.
Syntax
C
printf("format string", values...);

The format string tells printf what to print and how.

Placeholders like %d or %s are used to insert values.

Examples
Prints a simple message with a new line.
C
printf("Hello, world!\n");
Prints a number inside the message using %d for an integer.
C
printf("I have %d apples.\n", 5);
Prints a word or sentence using %s for a string.
C
printf("My name is %s.\n", "Anna");
Prints a floating-point number with 2 decimal places using %.2f.
C
printf("Pi is approximately %.2f.\n", 3.14159);
Sample Program

This program prints a greeting, then shows the age using %d to insert the number, and finally prints a closing message.

C
#include <stdio.h>

int main() {
    int age = 25;
    printf("Hello!\n");
    printf("I am %d years old.\n", age);
    printf("Nice to meet you!\n");
    return 0;
}
OutputSuccess
Important Notes

Always include \n at the end of your message to move to the next line.

Make sure the placeholders match the type of the values you provide (e.g., %d for int, %s for string).

printf does not add a new line automatically.

Summary

printf is used to show messages on the screen.

Use placeholders like %d, %s, and %f to insert values.

Remember to add \n to start a new line after printing.