0

This is my program, can someone tell me how to get the right value of 'n'(which is size of array) here without passing it to function?

#include <iostream>
using namespace std;

char * findFrequency (int input1[],int input2)
{
    int n = sizeof(input1) / sizeof(input1[0]);
    
    int count = 0;
    for(int i = 0; i < n; i++)
    {
        if(input1[i] == input2) 
         count++;
    }
    string ch;
    if(count == 0) 
     ch = to_string(input2) + " not present"; 
    else 
     ch = to_string(input2) + " comes " + to_string(count) + " times";
    std::cout << ch << "\nn = " << n;
}
int main ()
{
    int a[] = {1, 1, 3, 4, 5, 6};
    findFrequency(a, 1);
}
K Aditi
  • 3
  • 3

1 Answers1

1

Of course you can always use a template:

#include <iostream>
using namespace std;

template<typename T, std::size_t N>
void findFrequency (T(&input1)[N], int input2)
{
    // input1 is the array
    // N is the size of it

    //int n = sizeof(input1) / sizeof(input1[0]);

    int count = 0;
    for(int i = 0; i < N; i++)
    {
        if(input1[i] == input2)
         count++;
    }
    string ch;
    if(count == 0)
     ch = to_string(input2) + " not present";
    else
     ch = to_string(input2) + " comes " + to_string(count) + " times";
    std::cout << ch << "\nn = " << N;
}
int main ()
{
    int a[] = {1, 1, 3, 4, 5, 6};
    findFrequency(a, 1);
}
Vasilij
  • 1,861
  • 1
  • 5
  • 9