Takaman Takaman - 4 months ago 39
C Question

Calling methods with arrays in C++

My problem is that I have trouble calling the int

computePattern
method in int main(). I am able to use the
insertNumber
method. But i don't know how to use the
computePattern
method. The method is to compute the number of patterns and return the count. The pattern is that both adjacent numbers must be greater than 7. Hence, there are only 5 pairs to check as there are 10 numbers. For now the output is only the random arrays which worked, but I need to print out the number of patterns too. I need to use methods as it is required in the question.

int insertNumber(int b )
{
int a = rand()%10+1;
return a;
}
int computePattern(int* inArray, int size )
{
int patterns=0;
for(int z=0;z<size;z=z+2)
{
if(inArray[z]+inArray[z+1]>7)
{
patterns ++ ;
}
}
return patterns;
}
int main()
{
int arrays[10];
srand(time(0));
for ( int b=0; b<10 ; b++)
{
arrays[b] = insertNumber(b);
}
cout << "Arrays";
for ( int c= 0; c<10; c++)
{
cout << " " ;
cout << arrays[c];
}
int patterns =computePattern(arrays,10);
cout<<endl;
cout << "Patterns" <<patterns;
}

Answer

You have different arrays in main than in computePattern. Just because they share a name doesn't mean they're the same variable. Each one of them is function scope. A better way is to pass in the address and size of the array.

int computePattern(int* inArray, int size)
{
    int patterns=0;
    for(int z=0; z<size-1; z+=2)
    {
        if((inArray[z] + inArray[z+1]) > 7)
        {
            patterns++;
        }
    }
    return patterns;
}
//... then in main...

int patterns=computePattern(arrays, 10);
cout << patterns;