Home » C++ programs

C++ template program with arrays

Here, we are going to learn how to use template with arrays? Here, we will print the arrays using the C++ template?
Submitted by IncludeHelp, on December 22, 2019

In the below program, we are declaring two arrays – 1) character array and 2) integer array, and we are creating a function that will accept both of the arrays and print the elements using the C++ template.

C++ program:

// C++ template program with arrays

#include <iostream>
#include <string.h>
using namespace std;

template <class TypeName>

// function using the template
void printArray(TypeName* arr, int len)
{
    for (int i = 0; i < len; i++) {
        cout << *arr << " ";
        ++arr; // pointing to next element
    }
    cout << endl;
}

// main code/ main function
int main()
{
    // declaring character array
    char chrArr[] = "IncludeHelp";
    //declaring integer array
    int numArr[] = { 10, 20, 30, 40, 50 };

    //printing array elements
    cout << "chrArr: ";
    printArray(chrArr, strlen(chrArr));

    cout << "numArr: ";
    printArray(numArr, 5);

    //passing direct string
    cout << "Hello: ";
    printArray("Hello", 5);

    return 0;
}

Output

chrArr: I n c l u d e H e l p
numArr: 10 20 30 40 50
Hello: H e l l o


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.