C Format Specifiers

1. What are Format Specifiers?

  • Format specifiers tell C what type of data to print or read.

  • Used in functions like printf() (output) and scanf() (input).

  • They are placeholders that start with %.


2. Common Format Specifiers

Specifier Data Type Example
%d int (integer) int age = 25;
%i int (integer) int num = 10;
%f float float pi = 3.14;
%lf double double d = 3.14159;
%c char (character) char ch = ‘A’;
%s string char name[] = “Vipul”;
%u unsigned int unsigned int u = 100;
%x hexadecimal int x = 255;
%o octal int o = 8;
%% percent symbol printf(“%%”); prints %

3. Using Format Specifiers with printf()

Example 1: Printing different types

#include <stdio.h>

int main() {
int age = 25;
float height = 5.9;
char grade = ‘A’;
char name[] = “Vipul”;

printf(“Name: %s\n”, name);
printf(“Age: %d\n”, age);
printf(“Height: %.1f\n”, height);
printf(“Grade: %c\n”, grade);

return 0;
}

Output:

Name: Vipul
Age: 25
Height: 5.9
Grade: A
  • %.1f → Limits float output to 1 decimal place.


4. Using Format Specifiers with scanf()

Example 2: Reading user input

#include <stdio.h>

int main() {
int age;
float height;
char grade;
char name[20];

printf(“Enter your name: “);
scanf(“%s”, name);
printf(“Enter your age: “);
scanf(“%d”, &age);
printf(“Enter your height: “);
scanf(“%f”, &height);
printf(“Enter your grade: “);
scanf(” %c”, &grade); // note the space before %c

printf(“\nName: %s\nAge: %d\nHeight: %.2f\nGrade: %c\n”, name, age, height, grade);

return 0;
}

Explanation:

  • & → Passes the address of the variable to scanf().

  • " %c" → Space avoids reading leftover newline characters.


5. Tips and Tricks

  1. Always match the format specifier with the variable type.

  2. Use %.nf to control decimal precision.

  3. Use %% to print the % symbol.

  4. %s automatically stops reading input at space. For full sentences, use gets() (though unsafe) or fgets().

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 *