DEV Community

Cover image for Format Specifiers and Escape Sequence in C Language
Rishabh Kumar
Rishabh Kumar

Posted on • Originally published at codewithrish.com

1 1

Format Specifiers and Escape Sequence in C Language

What is Format Specifier

The format specifier is a way to tell your compiler what type of data are you dealing with. It is used while inputting and outputting any data. For all format specifiers, you can check this chart or complete article here

General Syntax in printf()

printf("%a.b{formatSpecifier}", yourvariable);

where a and b are integers where a tells total character spaces for output and b tells the accuracy after the decimal.

Let's look at this code for more details

#include <stdio.h>
int main()
{
    float b = 5.63;
    printf("%6.3f\n", b);
    return 0;
}
// output
 5.630
Enter fullscreen mode Exit fullscreen mode

In the above code, there a=6 and b=3 means we will have 3 decimal places and if we look closely there is 1 space before 5 in the output 4 character spaces by 5, 6, 3 and 0 and fifth by . but we said 6 so it added a space before because a was positive if a would have been negative it will add spaces after the output.

General Syntax in scanf()

scanf("%{formatSpecifier}", &yourvariable);

Sample Code

#include <stdio.h>
int main(){    
    float a;
    printf("Enter a number: ");
    scanf("%f", &a);
    printf("Your Input Is: %7.3f", a);
    return 0;  
}    
// output
Enter a number: 5.32
Your Input Is:   5.320
Enter fullscreen mode Exit fullscreen mode

What is Escape Sequence

In C, an escape sequence is a character sequence that cannot be used directly in a string literal. You need more character starting with backslash . For example, \n represents new line.

List of Escape Sequence in C

Escape Sequence.png

Sample Code

#include <stdio.h>
#include<stdio.h>    
int main(){    
    int number=50;    
    printf("We\nareC\b learning\t\"C\" programming here \'on\' CodeWithRish");
    return 0;  
}    
// output
We
are learning    "C" programming here 'on' CodeWithRish
Enter fullscreen mode Exit fullscreen mode

Neon image

Serverless Postgres in 300ms (❗️)

10 free databases with autoscaling, scale-to-zero, and read replicas. Start building without infrastructure headaches. No credit card needed.

Try for Free →

Top comments (0)

AWS Industries LIVE! Stream

Watch AWS Industries LIVE!

New tech. Real solutions. See what’s possible on Industries LIVE! with AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay