Examveda

What will be the output of the following C code?
#include <stdio.h>
int main()
{
    printf("Ram\rShyam\n");
    return 0;
}

A. RamShyam

B. Ram
Shyam

C. ShyamRam

D. Ram

Answer: Option B

Solution (By Examveda Team)

The correct answer is Option B: Ram Shyam.

Here's why:

* `printf("Ram\rShyam\n");` is the core of the problem. Let's break it down:
* `Ram`: This part is initially printed to the console buffer.
* `\r`: This is the carriage return character. It moves the cursor to the beginning of the current line.
* `Shyam`: Because of `\r`, this overwrites the beginning of the existing line. So "Ram" is replaced by "Shyam". If "Shyam" has fewer characters than "Ram", some parts of "Ram" may remain.
* `\n`: This is the newline character. It moves the cursor to the beginning of the next line.
Because `\r` brings the cursor to the start of the line *before* "Shyam" is printed, "Shyam" will overwrite "Ram", and then `\n` will put the cursor on a newline for subsequent outputs (if any).

This Question Belongs to C Program >> C Fundamentals

Join The Discussion

Comments (1)

  1. Xyz Chakraborty
    Xyz Chakraborty:
    4 months ago

    wrong answer .How it works:
    "Ram" is printed first.


    brings the cursor to the beginning of the line.

    "Shyam" then overwrites "Ram":

    'S' overwrites 'R'

    'h' overwrites 'a'

    'y' overwrites 'm'

    'a' and 'm' are printed afterward

    So "Ram" is erased. Only "Shyam" is shown.

Related Questions on C Fundamentals