Output of Following program is : hai
I didn't get how the \r
carriage return works in this program and in real can any one help me out ?
#include <stdio.h> #include<conio.h> void main() { printf("\nab"); printf("\bsi"); printf("\rha"); _getch(); }
CR = Carriage Return ( \r , 0x0D in hexadecimal, 13 in decimal) — moves the cursor to the beginning of the line without advancing to the next line. LF = Line Feed ( \n , 0x0A in hexadecimal, 10 in decimal) — moves the cursor down to the next line without returning to the beginning of the line.
In short: Carriage return ( \r or 0xD ): To take control at starting on the same line. Line feed ( \n or 0xA ): To Take control at starting on the next line. Form feed ( \f or 0xC ): To take control at starting on the next page.
CR (character : \r, Unicode : U+000D, ASCII : 13, hex : 0x0d) : This is simply the 'r' character. This character is commonly known as 'Carriage Return'. As matter of fact, \r has also has a different meaning. In older printers, \r meant moving the print head back to the start of line and \n meant starting a new line.
Enter key. Also called the "Return key," it is the keyboard key that is pressed to signal the computer to input the line of data or the command that has just been typed. The Enter key was originally the "Return key" on a typewriter, which caused the carriage to return to the beginning of the next line on the paper.
From 5.2.2/2 (character display semantics) :
\b
(backspace) Moves the active position to the previous position on the current line. If the active position is at the initial position of a line, the behavior of the display device is unspecified.
\n
(new line) Moves the active position to the initial position of the next line.
\r
(carriage return) Moves the active position to the initial position of the current line.
Here, your code produces :
<new_line>ab
\b
: back one charactersi
: overrides the b
with s
(producing asi
on the second line)\r
: back at the beginning of the current lineha
: overrides the first two characters (producing hai
on the second line)In the end, the output is :
\nhai
Program prints ab
, goes back one character and prints si
overwriting the b
resulting asi
. Carriage return returns the caret to the first column of the current line. That means the ha
will be printed over as
and the result is hai
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With