KLMM
KLMM

Reputation: 93

C programming basic call back function

The question briefly is this:

Implement a callback function void data_cb(int raw). Each time data_cb(n) is called by the analyzer (in this case our test module), you must update the internal state of your module based on the value of n. you cannot use an array. Instead, we have a few module variables to keep track of the statistics.

This is what I have done:

// data_cb(n) updates the internal state based on the value of n 
void data_cb(int n)
{
 a= n;}

// total_data_points() returns the number of integers processed so far
int total_data_points(void){
count++;
return count;}

// negative_sum() returns the sum of the negative integers processed so far
//    NOTE: you do not have to worry about overflow
int negative_sum(void){
if (a<=0)
{
    neg_sum = neg_sum+a;
    return neg_sum;
}
else
{
    return neg_sum;
}}

// positive_sum() returns the sum of the positive integers processed so far
//    NOTE: you do not have to worry about overflow
int positive_sum(void){
if (a>=0)
{
    pos_sum = pos_sum+a;
    return pos_sum;
}
else
{
    return pos_sum;}}

The total_data_points() returns the number of integers processed, but its not giving us what we want. Consider the below example:

assume that data_cb(n) have been invoked with the following values: 2 5 7 4 1 -3 -6 -5 -3 1 3 5

    assert (total_data_points() == 12);
assert (negative_sum() == -17);
assert (positive_sum() == 28);
assert (data_max() == 7);
assert (data_min() == -6);
assert (data_spread() == 4);     

Upvotes: 0

Views: 85

Answers (1)

lc.
lc.

Reputation: 116488

The problem is by the time your total_data_points(), negative_sum(), etc functions are called, the only data you have left is the most recent call of data_cb(5). The internal state simply is keeping a = 5.

Instead, you need to update something(s) to keep track of the statistics as you receive data. I would imagine the stipulation of "you cannot use an array" in the exercise is to make sure you are processing the data as a stream instead of just holding on to all of it in memory. Thus you would need to do something like the following:

void data_cb(int n)
{
    dataPointsSeen++;
    if (n > 0) {positiveSum += n;}
    if (n < 0) {negativeSum += n;}
    //...
}

Then simply return these somethings when requested:

int total_data_points()
{
    return dataPointsSeen;
}

Upvotes: 1

Related Questions