Home > database >  I'm struggling with this question about arithmetic
I'm struggling with this question about arithmetic

Time:12-08

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;
}


CodePudding user response:

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.

CodePudding user response:

You're almost good, just need to fix barriers: you'd like to go exactly from from, 0 offset and include to:

    for(i=from; i<=to; i  ){

CodePudding user response:

Hej! Your Arithmetic sum function takes in variables "from" and "to", however the function body does not contain your "from" variable. Instead the function is running from i = 1 every time instead of i = from.

Also I believe that i should be less than or equal to "to" in the for loop.

  • Related