LearnFrenzy
Sign in Take a free test

C Input / Output · Predict the Output · Question 6

scanf("%c") after scanf("%d") – the leftover newline Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

What is the output of the following C program when the input is 5⏎x⏎?

main.c
#include <stdio.h>

int main(void) {
    int n;
    char c;
    scanf("%d", &n);
    scanf("%c", &c);
    printf("%d [%d]\n", n, c);
    return 0;
}
  • A 5 [10] Correct
  • B 5 [120]
  • C 5 [0]
  • D 5 [32]
Correct Answer: Option A

%d stops at the newline and leaves it in the buffer. %c does not skip whitespace, so it reads '\n' (code 10), not 'x'. A space before %c – " %c" – would read 'x'.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links