This function gets a sequence of numbers until the user inputs -1
. It should return the sum of the numbers at the index(mod3)=0
minus the number in the other indexes.
For example:
9 2 4 7 8 1 3 -1
the function sums at first all the numbers that are at the indexes that divisible by three. So sum1
supposed to be 5
because 4 is at the 3rd index and 1 is at the 6th index, all the other indexes sum up to sum2
. Then it should subtract one from another : sum1 - sum2
and the output should be -24
(i.e., sum1 - sum2 = 5 - 29 = -24)
I wrote this code and I don't understand why it doesn't work properly the output that is returned for every sequence is 0.
int sumOfSeq();
void main()
{
printf("%d\n", sumOfSeq());
system("pause");
}
int sumOfSeq()
{
int n, curr = 1, sum1 = 0, sum2 = 0;
scanf("%d", &n);
if (n == -1)
return sum1 - sum2;
else
{
if (curr % 3 == 0)
{
sum1 += n;
curr++;
}
else
{
sum2 += n;
curr++;
}
sumOfSeq();
}
}
Within the function sumOfSeq
you are not using the sum obtained by next recursive calls of the function. You are just calling within the function
sumOfSeq();
So the function does not make a sense.
And there is no need to calculate two sums separately because in any case the function has to return one value, the result sum.
The function can be defined the following way as it is shown in the demonstrative program below.
#include <stdio.h>
long long int sumOfSeq( size_t n )
{
long long int sum = 0;
int item;
if ( scanf( "%d", &item ) == 1 && item != -1 )
{
sum += sumOfSeq( n + 1 ) + ( ( n + 1 ) % 3 == 0 ? item : -item );
}
return sum;
}
int main(void)
{
printf( "%lld\n", sumOfSeq( 0 ) );
return 0;
}
The program output for the inputted sequence of numbers
9 2 4 7 8 1 3 -1
is
-24
As you can see the function definition is enough simple and the function uses only one parameter.
Bear in mind that it is a bad idea to use static local variables if the function can be written without them. Otherwise you will have some difficulties running the function for a second time.
Also pay attention to that according to the C Standard the function main without parameters shall be declared like
int main( void )
instead of
void main()