Search code examples
c++mathinteger-arithmetic

I'm struggling with this question about arithmetic


The function must return the sum of all integers between from and to including these numbers. For example, arithmeticSum(2,4) should be 9 because 2+3+4 = 9.

This is the code right now, i can't change anything in the main.

#include <iostream>
using namespace std;
int aritmetiskSumma(int from, int to){
    int i=0;
    int sum=0;
    for(i=1;i<to;i++){
        sum+=i;
    }
  return sum; // TODO
}
// Ändra inget nedanför denna rad
void provaAritmetiskSumma(){
    int from, to;
    cin >> from >> to;
    int summa = aritmetiskSumma(from, to);
    cout << summa << endl;
}
int main(){
    provaAritmetiskSumma();
    return 0;
}



Solution

  • In order to calculate the sum, adjust the for loop like this:

    for(; from <= to; from++)
    {
       sum += from;
    }
    

    This code starts with the from value and calculates the sum of all the integers up to and including to.