Click here to Skip to main content
15,903,388 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi.

I need help with this program:

Example input: 2 4 6 -1 7 3 -2 1
Output: 3 3 (longest series of even is 3, longest series of positive is 3)

Here is the code:

C++
#include <stdio.h>
int even(int x)
 {
return x % 2 == 0;
 }

int positive(int x)
{
    return x>0;
}
int longest_series(int a[], int n, int (*f) (int)) {
int i;
/*Length of the current series is  0 or  1 depending on whether it is a array
empty or not*/
int cs = 0;
/* Longest series is current series */
int ls = cs;
for (i = 0; i < n; i++) {
if ((*f)(a[i]))
cs++;
else
cs = 0;
if (cs > ls)
ls = cs;
}
return ls;
}
int main() {
int a[] = {2,4,6,-1,7,3,-2,1},
n = sizeof(a)/sizeof(int);
printf("%d %d\n", longest_series(a, n, &even),
longest_series(a, n, &positive));
return 0;
}


My question is how to write this code if the prototype of function is:

C++
void series(int *array, int n, int (*s)(int), int **beginning, int *length);


Thanks for replies.
Posted
Comments
OriginalGriff 16-Mar-15 5:47am    
This is not a good question - we cannot work out from that little what you are trying to do.
Remember that we can't see your screen, access your HDD, or read your mind.
So what do the extra parameters do? What are they supposed to be used for?
And please, indent your code! It makes it a lot, lot more readable, particularly if (like us) you have never seen that code before!
Use the "Improve question" widget to edit your question and provide better information.

1 solution

This is your homework. We would not do you a favor by doing it for you. Take some time to look at the problem and you will certainly find the solution. The effect is that you will learn something. If, however, you think it is a waste of time doing such exercises, then you are probably in the wrong class. Then you would be better off finding another subject that does interest you more.

The problem at hand is relatively easy. I would start by properly indenting the code and then understand what the function longest_series does. The new function series should obviously return two more items: A pointer to the start of that longest series and the length of it. Create a local variable for the pointer to the longest series and update it whenever you have found a new longest series. It's a matter of a few lines of code -- and a good exercise.
 
Share this answer
 
Comments
CPallini 16-Mar-15 6:05am    
5.
nv3 16-Mar-15 7:26am    
Thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900