Skip to main content

ProwessApps

Learn · Practice · Excel

Create a class Template which stores an array. Include member function .
(i) To search an element in the array.
(ii) To find the sum of elements of an array
(iii) To find the largest elements of an array

C++ Code Example — Exception Handling

ADVERTISEMENT

Create a class Template which stores an array. Include member function .
(i) To search an element in the array.
(ii) To find the sum of elements of an array
(iii) To find the largest elements of an array

Objective

Write a C++ program using a Class Template to perform operations (Search, Sum, Largest) on a generic array.

Algorithm / Approach

  1. Define template <class T> before the class.
  2. Declare an array of the generic type: T arr[5].
  3. Implement input(), search(), sum(), and largest() using the generic placeholder T for all temporary variables.
  4. In main(), instantiate the generic class.
main.cpp
#include
using namespace std;
template 
class Test{
 public:
 T arr[5];
 void input() {
   T x;
  cout<<"Enter 5 Elements ";
  for(int i =0; i<5; i++) {
  
   cin>>x;
   arr[i] = x;
  }
 }
 void search() {
  T a;
  int flag = 0;
  int i=0;
  cout<<"Enter Element to search ";
  cin>>a;
  for(i = 0; i<5; i++) {
   if(arr[i]==a) {
    flag = 1;
    break;
   }
  }
 if(flag ==1 ) {
  cout<<"Found At "<< i<< endl;
  }
 else {
  cout<<"Element NOT found "<< endl;
  }
 }
 void sum() {
  T s =0;
  for(int i=0; i<5; i++) {
   s = s+ arr[i];
  }
  cout<<"Sum = "<< s<< endl;
 }
 void largest() {
 T max= arr[0];
 for(int i = 0;i<5; i++) {
  if(max< arr[i]) {
   max = arr[i];
  }
 }
 cout<<"Maximum = "<< max<< endl;
}
};
int main() {
 Test t;
 t.input();
 t.search();
 t.sum();
 t.largest();
 return 0;
}

Expected Output

Enter 5 Elements 1 4 8 6 4
Enter Element to Search 5
Element NOT found
Sum = 23
Maximum = 8

Explanation of the Program

  • This demonstrates how powerful templates can be. You can write complex data structure logic once, and instantly use it for arrays of floats, integers, or strings just by changing the template parameter.
  • Note on the provided code: It contains massive syntax errors that will prevent compilation. The include directive is empty (#include instead of #include&lt;iostream&gt;). The template declaration is empty (template instead of template&lt;class T&gt;). And the object instantiation in main is missing the data type (Test t; instead of Test&lt;int&gt; t;).

Complexity

Time Complexity O(n) - For searching, summing, and finding the max.
Space Complexity O(n) - To store the array.

Common Mistakes

  • Syntax Error: Empty #include directive.
  • Syntax Error: Empty template declaration. It must include the generic parameter (e.g., template&lt;class T&gt;).
  • Syntax Error: Failing to specify the data type when instantiating a template class (e.g., writing Test t; instead of Test&lt;int&gt; t;).
ADVERTISEMENT