Friday, March 3, 2023
HomeSoftware EngineeringMethods to Calculate the Sum of a Sequence in C

# Methods to Calculate the Sum of a Sequence in C

## The problem#

Your activity is to make perform, which returns the sum of a sequence of integers.

The sequence is outlined by 3 non-negative values:Â start,Â finish,Â step (inclusive).

IfÂ startÂ worth is bigger than theÂ finish, perform ought to returnsÂ ****

Examples

``````2,2,2 --> 2
2,6,2 --> 12 (2 + 4 + 6)
1,5,1 --> 15 (1 + 2 + 3 + 4 + 5)
1,5,3  --> 5 (1 + 4)
``````

Choice 1:

``````unsigned sequence_sum(int begin, int finish, int step) {
int sum=0,i;
for(i=begin;i<=finish;i=i+step)
sum=sum+i;
return sum;
}
``````

Choice 2:

``````unsigned sequence_sum(unsigned begin, unsigned finish, unsigned step) {
if(begin > finish) return 0;
else {
unsigned n = (finish - begin)/step;
return ((n + 1)*begin + n*(n + 1)*step/2);
}
}
``````

Choice 3:

``````unsigned sequence_sum(unsigned begin, unsigned finish, unsigned step){
if(begin > finish) return 0;
int n = (end-start)/step + 1;
return (n)*(2*begin+(n-1)*step)/2;
}
``````

## Check circumstances to validate our resolution#

``````#embody <criterion/criterion.h>

unsigned sequence_sum(unsigned begin, unsigned finish, unsigned step);

Check(Sample_Test, should_return_the_sum_of_sequence)
{
cr_assert_eq(sequence_sum(2u, 6u, 2u), 12u);
cr_assert_eq(sequence_sum(1u, 5u, 1u), 15u);
cr_assert_eq(sequence_sum(1u, 5u, 3u), 5u);
cr_assert_eq(sequence_sum(0u, 15u, 3u), 45u);
cr_assert_eq(sequence_sum(16u, 15u, 3u), 0u);
}
``````

RELATED ARTICLES