How to Calculate the Sum of a Sequence in C


The challenge

Your task is to make function, which returns the sum of a sequence of integers.

The sequence is defined by 3 non-negative values: beginendstep (inclusive).

If begin value is greater than the end, function should 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)

The solution in C

Option 1:

unsigned sequence_sum(int start, int end, int step) {
    int sum=0,i;
    for(i=start;i<=end;i=i+step)
        sum=sum+i;
    return sum;
}

Option 2:

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

Option 3:

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

Test cases to validate our solution

#include <criterion/criterion.h>

unsigned sequence_sum(unsigned start, unsigned end, unsigned step);

Test(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);
}