InterviewSolution
| 1. |
Write a code to print numbers from 0 to 100 in C++ without using loop and recursion. |
|
Answer» Template Metaprogramming is the idea used in this code. Let's have a look at how this works. Non-data types can ALSO be used as parameters in C++ templates. The term "non-datatype" refers to a value rather than a datatype. In the preceding code, for example, N is passed as a value rather than a datatype. For each parameter, a new instance of a generic class is constructed, and these classes are created at compile time. #include <IOSTREAM>using namespace std; template<int n>class PrintZeroToN{public: static void display() { PrintZeroToN<n-1>::display(); // this should not be mistaken for recursion cout << n << endl; }}; template<>class PrintZeroToN<0>{public: static void display() { cout << 0 << endl; }};int main(){ const int n = 100; PrintZeroToN<n>::display(); return 0;}Explanation: N is passed as a value rather than a data type in the above program. For each parameter, a new instance of a generic class is constructed, and these classes are created at compile time. When the compiler encounters the line “PrintZeroToN<>::print()” with N = 100, it produces an instance PrintZeroToN<100>. Another FUNCTION PrintZeroToN<99>::print() is called in function PrintZeroToN<100>::print(), resulting in the creation of an instance PrintZeroToN<99>. All instances from PrintZeroToN<100> to PrintZeroToN<1> are created in the same way. The function PrintZeroToN<0>::print() already exists and prints 0. The PrintZeroToN<1> function prints 1 and so on. As a result, all numbers from 0 to N are printed on the screen. |
|