C Output

1. Using printf() for Output

The most common way to display output in C is with the printf() function from the stdio.h library.

Basic Syntax:

printf("format string", values);
  • "format string" → The text you want to display.

  • values → Variables or constants to display.

  • Placeholders in the format string are replaced by variable values.


2. Format Specifiers

Format specifiers tell printf() what type of data to print:

Specifier Type Example
%d Integer int x = 10
%f Float float pi = 3.14
%c Character char ch = ‘A’
%s String char str[] = “Hi”
%lf Double double d = 3.1415
%u Unsigned int unsigned int u = 20

3. Examples of Output

Example 1: Display text only

#include <stdio.h>

int main() {
printf("Hello, World!\n");
return 0;
}

Output:

Hello, World!

Example 2: Display variables

#include <stdio.h>

int main() {
int age = 25;
float height = 5.9;
char grade = 'A';

printf("Age: %d\n", age);
printf("Height: %.1f\n", height); // .1 limits to 1 decimal
printf("Grade: %c\n", grade);

return 0;
}

Output:

Age: 25
Height: 5.9
Grade: A

Example 3: Multiple variables

#include <stdio.h>

int main() {
int a = 10, b = 20;
printf("a = %d, b = %d\n", a, b);
return 0;
}

Output:

a = 10, b = 20

4. Escape Sequences

Special characters that give formatting instructions:

Escape Sequence Meaning
\n New line
\t Horizontal tab
\\ Backslash
\" Double quote
\' Single quote

Example:

printf("Hello\tWorld\n");

Output:

Hello World

5. Tips for Using printf()

  1. Always match format specifiers with variable types.

  2. Use %.nf to control decimal places for floats/doubles.

  3. Combine text and variables in a single statement for cleaner code.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *