LearnFrenzy
Sign in Take a free test

Functions and Default Arguments · Predict the Output · Question 19

Recursive function printing a number in binary Answer, explanation & discussion

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

What is the output of the following C++ program?

main.cpp
#include <iostream>

void binary(unsigned n) {
    if (n > 1) binary(n / 2);
    std::cout << n % 2;
}

int main() {
    binary(13);
    std::cout << ' ';
    binary(64);
    std::cout << '\n';
    return 0;
}
  • A 1101 1000000 Correct
  • B 1011 0000001
  • C 1101 100000
  • D 13 64
Correct Answer: Option A

The recursion handles the higher bits first and prints the lowest bit last, so the digits come out in the right order: 13 = 1101, 64 = 1000000.

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