Accelerated C++ Solution to Exercise 0-4

Exercise 0-4

Write a program that, when run, writes the Hello World program as its output.

Solution

Using the skills picked up from the previous exercises, this should be quite a straight forward exercise. There is nothing new here. Below is my code (of course, there are many ways to do this.)

#include <iostream>
int main()
{
    std::cout << "#include <iostream>" << std::endl;
    std::cout << "int main()" << std::endl;
    std::cout << "{" << std::endl;
    std::cout << "  std::cout << \"Hello World!\" << std::endl;" << std::endl;
    std::cout << "  return 0;" << std::endl;
    std::cout << "}" << std::endl;
    return 0;
}

Result

Submitting the program produces the Hello World code in the console output window.

#include <iostream>
int main()
{
  std::cout << "Hello World!" << std::endl;
  return 0;
}

Process returned 0 (0x0)   execution time : 0.179 s
Press any key to continue.

# Reference

Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000

2 thoughts on “Accelerated C++ Solution to Exercise 0-4”

  1. First I would like to thank you for a great blog!

    I have a question about this exercise.
    Wouldn’t code execute quicker if you create the expression in one line?

    Example:

    std::cout << “// a small C++ program \n#include \n\nint main ()\n{\n\tstd::cout << \”Hello , World!\” << std::endl;\n\treturn 0;\n}” << std::endl;

    It’s more messy, but maybe you save a millisecond? ;-)

    Kind regards
    Magnus

Comments are closed.