Q:

C++ Templates | Find output programs | Set 2

belongs to collection: C++ find output programs

0

This section contains the C++ find output programs with their explanations on C++ Templates (set 2).

Program 1:

#include <iostream>
using namespace std;

template <class Type>
Type fun(Type num)
{
    int f = 1;

    while (num > 0) {
        f = f * num;
        num--;
    }
}

int main()
{
    int fact = 0;

    fact = fun<int>(5);

    cout << fact;

    return 0;
}

Program 2:

#include <iostream>
using namespace std;

template <class T1, class T2>
class Sample {
    T1 var1;
    T2 var2;

public:
    Sample(T1 v1, T2 v2)
    {
        var1 = v1;
        var2 = v2;
    }
    void print()
    {
        cout << var1 << endl;
        cout << var2 << endl;
    }
};

int main()
{
    Sample<char, float> S1('A', 3.14F);
    Sample<int, double> S2(101, 3.14);

    S1.print();
    S2.print();

    return 0;
}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer Program 1:

Output:

120

Explanation:

The above code will print 120 on the console screen. In the above program, we defined a generic function using templates with argument num. Here we used the "class" keyword instead of "typename". This function is used to calculate the factorial of the specified number.

Now coming to the main() function. Here we passed integer value in the function fun(). Then it will return 120 that will be printed on the console screen.

Answer Program 2:

Output:

A
3.14
101
3.14

Explanation:

In the above program, we created a generic class Sample with two types T1 and T2. The Sample class contains two data members' var1, var2, and a parameterized constructor that will initialize the data member's var1 and var2.

Here we also created a print() member function to print the values of var1 and var2. Now coming to the main() function. Here we created two objects S1 and S2 with different types of values. Then we called print() function using S1 and S2 that will print the values of data members.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ find output programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ Preprocessor | Find output programs | Set 1... >>
<< C++ Templates | Find output programs | Set 1...