fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // Class template for a generic array
  5. template <class T>
  6. class GenericArray {
  7. private:
  8. T arr[100]; // Fixed-size array
  9. int size; // Size of the array
  10.  
  11. public:
  12. // Constructor
  13. GenericArray(T elements[], int n) {
  14. size = n;
  15. for (int i = 0; i < size; i++) {
  16. arr[i] = elements[i];
  17. }
  18. }
  19.  
  20. // Function to calculate the summation of all elements
  21. T findSum() {
  22. T sum = 0;
  23. for (int i = 0; i < size; i++) {
  24. sum += arr[i];
  25. }
  26. return sum;
  27. }
  28.  
  29. // Display elements of the array
  30. void display() {
  31. cout << "[ ";
  32. for (int i = 0; i < size; i++) {
  33. cout << arr[i] << " ";
  34. }
  35. cout << "]" << endl;
  36. }
  37. };
  38.  
  39. int main() {
  40. // Test with integers
  41. int intArr[] = {1, 2, 3, 4, 5};
  42. GenericArray<int> intArray(intArr, 5);
  43. cout << "Integer Array: ";
  44. intArray.display();
  45. cout << "Sum: " << intArray.findSum() << endl;
  46.  
  47. // Test with doubles
  48. double doubleArr[] = {1.1, 2.2, 3.3, 4.4, 5.5};
  49. GenericArray<double> doubleArray(doubleArr, 5);
  50. cout << "\nDouble Array: ";
  51. doubleArray.display();
  52. cout << "Sum: " << doubleArray.findSum() << endl;
  53.  
  54. // Test with characters
  55. char charArr[] = {'a', 'b', 'c', 'd', 'e'};
  56. GenericArray<char> charArray(charArr, 5);
  57. cout << "\nCharacter Array: ";
  58. charArray.display();
  59. cout << "Sum: " << static_cast<int>(charArray.findSum()) << " (ASCII Sum)" << endl;
  60.  
  61. return 0;
  62. }
  63.  
Success #stdin #stdout 0.01s 5272KB
stdin
Standard input is empty
stdout
Integer Array: [ 1 2 3 4 5 ]
Sum: 15

Double Array: [ 1.1 2.2 3.3 4.4 5.5 ]
Sum: 16.5

Character Array: [ a b c d e ]
Sum: -17 (ASCII Sum)