C Escape Sequences

In C programming, escape sequences are special characters that begin with a backslash () and are used to perform specific functions in strings or character data. These sequences represent non-printable characters or alter the output format.

Commonly Used Escape Sequences in C

Escape Sequence Description
\n New line
\t Horizontal tab
\\ Backslash
\" Double quotation mark
\' Single quotation mark
\a Alert (bell)
\b Backspace
\r Carriage return

Now that we have a thorough understanding of each escape sequence in C,

Alarm or Beep (\a):

The alarm or beep escape sequence (a) produces an audible alert or beep sound.

                        
#include <stdio.h>
int main() 
{  
printf("This is an alarm sound: \a");  
  
return 0;  
}              
                        
                    

Output

This is an alarm sound:

Backspace (\b):

The cursor can be advanced by one character with the backspace escape key (b).

                        
#include <stdio.h>
int main() 
{  
printf("Hello\b\b\bWorld!");  
  
return 0;  
}  
                      
                    

Output

HelloWorld!

Form Feed (\f):

The form feed escape sequence (f) is used to mimic a page break or advance to the next page.

                        
#include <stdio.h>
int main() 
{  
printf("This is before the form feed.\fThis is after the form feed.");  
  
return 0;  
}  
        
                        
                    

Output

This is before the form feed. This is after the form feed.

New Line (\n)

The new line escape sequence (n) is used to insert a newline character and move the cursor to the start of the following line.

                    
#include <stdio.h>
int main()
{
printf("Line 1\nLine 2");
    
return 0;
}
                    
                

Output

Line 1
Line 2

Carriage Return (\r)

The carriage return escape sequence (r) moves the cursor to the start of the current line.

                    
#include <stdio.h>
int main() 
{
printf("Hello\rWorld!");
    
return 0;
}
                    
                

Output

World!

Tab (Horizontal) (\t)

The tab escape sequence (t) inserts a horizontal tab and shifts the cursor to the next tab stop.

                    
#include <stdio.h>
int main() 
{
printf("Name:\tJohn\tAge:\t25");
return 0;
}
                    
                

Output

Name: John Age: 25

Vertical Tab (\v)

The vertical tab escape sequence (v) simulates a vertical tab.

                    
#include <stdio.h>
int main() 
{
printf("Hello\vWorld!");

return 0;
}
                    
                

Output

Hello
World!

Form Feed (\f)

The form feed escape sequence (f) is used to mimic a page break or advance to the next page.

                    
#include <stdio.h>
int main() 
{
printf("This is before the form feed.\fThis is after the form feed.");
    
return 0;
}
                    
                

Output

This is before the form feed.
This is after the form feed.