Input Format
The locked Solution class in your editor will pass different types of arrays to your printArray function.
Constraints
  • You must have exactly  function named printArray.
Output Format
Your printArray function should print each element of its generic array parameter on a new line.
Generics problem solution 30 days of code HackerRank

Problem solution in Java programming language.

public < E > void printArray( E[] inputArray ){    
     for ( E element : inputArray ){        
        System.out.printf( "%s\n", element );
     }
}

Second solution

<T> void printArray(T[] array) {
     for(T i : array){
          System.out.println(i);
     }
}

Problem solution in C++ programming language.

template<typename T> 
void printArray(vector<T> array) {
     for(T i : array){
          cout << i << endl;
     }
}

Second solution

#include <iostream>
#include <vector>
#include <string>

using namespace std;

/**
*    Name: printArray
*    Print each element of the generic vector on a new line. Do not return anything.
*    @param A generic vector
**/

template <class T>
void printArray(vector<T> vec){

   for(int i=0; i<vec.size(); i++)
   cout<<vec[i]<<endl;

}

int main() {
    int n;
    
    cin >> n;
    vector<int> int_vector(n);
    for (int i = 0; i < n; i++) {
        int value;
        cin >> value;
        int_vector[i] = value;
    }
    
    cin >> n;
    vector<string> string_vector(n);
    for (int i = 0; i < n; i++) {
        string value;
        cin >> value;
        string_vector[i] = value;
    }

    printArray<int>(int_vector);
    printArray<string>(string_vector);

    return 0;
}

Problem solution in C Sharp programming language.

static void printArray<T>(T[] array){
    foreach( T i in array ){
        Console.WriteLine(i); 
    }
}

Problem solution in the Swift programming language.

func printArray<T>(array: [T]) {
    for i in array {
        print("\(i)")
    }
}