Sum of Range

Hello everyone,
I am writing a function to find a sum of a range. I have a function that works in the main function, but I cannot figure how to call the function in main.

this is what I have.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
  #include <iostream>

using namespace std;

int sumOfRange(int, int);

int main() {
	int sumOfRange(int firstName, int lastName);
	return ;
} // End of main

int sumOfRange(int firstNum, int lastNum) {
	int Sum = 0;
	int First, Last;

	cout << "Enter the first: ";
	cin >> First;
	cout << "Enter the last:  ";
	cin >> Last;

	if (First > Last)
	{
		int Temp;

		Temp = First;
		First = Last;
		Last = Temp;
	}

	for (int Counter = First; Counter <= Last; Counter++)
		Sum += Counter;

	cout << Sum << endl;

	return 0;
}
Hello, I am just a beginner too, so what I say might very well be wrong, but I think your problem might be that you are not declaring your paramters ofsumOfRrange before you pass them. I have your program working as this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  #include <iostream>

using namespace std;

int sumOfRange(int, int);

int main() {
    int firstName;
    int lastName;
	sumOfRange(firstName, lastName);
	return 0;
} // End of main

int sumOfRange(int firstNum, int lastNum) {
	int Sum = 0;
	int First, Last;

	cout << "Enter the first: ";
	cin >> First;
	cout << "Enter the last:  ";
	cin >> Last;

	if (First > Last)
	{
		int Temp;

		Temp = First;
		First = Last;
		Last = Temp;
	}

	for (int Counter = First; Counter <= Last; Counter++)
		Sum += Counter;

	cout << Sum << endl;

	return 0;
}
Yep you're right. By declaring the variables inside the [what would be a] function call, it actually makes it a function declaration: int sumOfRange(int firstName, int lastName); declares a function (redundant because it's already declared on line 5) but does not call it.
Last edited on
Hello ccorkran,

Even with DonnaPin's suggestions this is what I see:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>

using namespace std;

int sumOfRange(int, int);  // <--- The variable names may not be required, but they do help.

int main()
{
    int firstName;  // <--- What does Name have to d with a numeric variable?
    int lastName;  // <--- Uninitialized and contain garbage values.

    sumOfRange(firstName, lastName);  // <--- Uninitialized variables containing garbage values. Also an error with
                                      // my compiler. Gives a warning in the shell program.

    return 0;  // <--- Not required, but makes a good break point.
} // End of main

// <--- This should be a void vunction.
int sumOfRange(int firstNum, int lastNum)  // <--- Variables received and with a better name.
                                           // Still contain garbage values and never used int the function.
{
    int Sum = 0;
    int First, Last;

    cout << "Enter the first: ";
    cin >> First;

    cout << "Enter the last:  ";
    cin >> Last;

    if (First > Last)
    {
        int Temp;

        Temp = First;
        First = Last;
        Last = Temp;
    }

    for (int Counter = First; Counter <= Last; Counter++)  // <--- Loops 1 more time with the "<=". Is that what you want?
        Sum += Counter;  // <--- Sum may be greater than what you expect.

    cout << Sum << endl;

    return 0;  // <--- This is not needed as there is nothing to return. And if
               // you make it a void function you can not return a value.
}


Andy
Thank you both, it will run in the stacks on this website, but will not run in visual studio because it says there are unused variables on line 8 and i have no clue what is going on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>

using namespace std;

int sumOfRange(int firstNum, int lastNum);

int main() {
	int firstNum, lastNum;
	cout << sumOfRange(firstNum, lastNum);
	/*int sumOfRange(int firstNum, int lastNum);*/
	
} // End of main

int sumOfRange(int firstNum, int lastNum) {
	int Sum = 0;
	int First, Last;

	cout << "Enter the first: ";
	cin >> First;
	cout << "Enter the last:  ";
	cin >> Last;

	if (First > Last) {
		int Temp;

		Temp = First;
		First = Last;
		Last = Temp;
	}

	for (int Counter = First; Counter < Last; Counter++)
		Sum += Counter;

	cout << Sum << endl;

	return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

void sumOfRange();

int main()
{
   sumOfRange();
}

void sumOfRange()
{
   std::cout << "Enter the first: ";
   int first;
   std::cin >> first;

   std::cout << "Enter the last:  ";
   int last;
   std::cin >> last;

   if (first > last)
   {
      int temp = first;
      first    = last;
      last     = temp;
   }

   int sum { };

   for (int counter = first; counter <= last; counter++) sum += counter;

   std::cout << "\nThe sum of " << first << " to " << last << " is: " << sum << '\n';
}

Enter the first: 1
Enter the last:  100

The sum of 1 to 100 is: 5050
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <cstdlib>
using namespace std;

int sumOfRange( int firstNum, int lastNum )
{
   return ( ( abs( lastNum - firstNum ) + 1 ) * ( lastNum + firstNum ) ) / 2;
}

int main()
{
   int First, Last;
   cout << "Enter the two numbers: ";   cin >> First >> Last;
   cout << sumOfRange( First, Last ) << '\n';
}


Enter the two numbers: 100 1
5050
Hello ccorkran,

you wrote:

but will not run in visual studio because it says there are unused variables on line 8 and i have no clue what is going on.



Strange my VS 2017 says:

Severity  Code	Description	Project	                        File           Line	
Error	C4700	uninitialized local variable 'lastNum' used	main v2.cpp	11	


If you did not understand the comments I put in the code that I posted just ask.

In "main" you are defining 2 variables "firstNum" and "lastNum", but they have no value just what happens to be in the memory they use for storage. Fo me this usually turns into an "int" of "-858993460" or known as garbage. Then when you try to call the function with out giving "firstNum" and "lastNum" a proper value the compiler complains.

You define your function as:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int sumOfRange(int firstNum, int lastNum) {
	int Sum = 0;
	int First, Last;

	cout << "Enter the first: ";
	cin >> First;
	cout << "Enter the last:  ";
	cin >> Last;

	if (First > Last) {
		int Temp;

		Temp = First;
		First = Last;
		Last = Temp;
	}

	for (int Counter = First; Counter < Last; Counter++)
		Sum += Counter;

	cout << Sum << endl;

	return 0;
}

You have sent "firstNum" and "lastNum" to your function, but where in this code do you use them.

If you do not understand just ask.

Andy
thank you Andy,
That helped a lot and is to clear to me now.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

using namespace std;

int sumOfRange(int, int);

int main() {
    
    int First, Last;

	cout << "Enter the first: ";
	cin >> First;
	cout << "Enter the last:  ";
	cin >> Last;
	
	cout << sumOfRange(First, Last);
	
	return 0;
} // End of main

int sumOfRange(int First, int Last) {
    
     if (First > Last)
     {
     return ((First-Last+1)*(First+Last))/2;
    }
    else
    {
      return ((Last-First+1)*(First+Last))/2;  
    }

}
Last edited on
@manga. Just use abs() like lastchance did in his code above.

Also, there's no need for the else as the last statement in the true condition is a return - and the tertiary operator can be used.

Without using abs():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>
#include <limits>

using namespace std;

int sumOfRange(int, int);
int getInt(const std::string& prm);

int main()
{
	const auto first {getInt("Enter the first: ")};
	const auto last {getInt("Enter the last: ")};

	cout << sumOfRange(first, last) << '\n';
}

int sumOfRange(int first, int last)
{
	return (((first > last ? first - last : last - first) + 1) * (first + last)) / 2;
}

int getInt(const std::string& prm)
{
	int i {};

	while ((std::cout << prm) && (!(std::cin >> i) || std::cin.peek() != '\n')) {
		std::cout << "Not an integer\n";
		std::cin.clear();
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	}

	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	return i;
}

The formula foe the sum of the range of consecutive integer numbers is given as


(n - m + 1) * (m + n) / 2


where m is the first number and n the last. This is derived from the standard formula for the sum of x consecutive numbers starting from 1 which is x * (x + 1) / 2

The required sum is the sum of the numbers from 1 to (m - 1) subtracted from the sum of numbers from 1 to n. Thus:


n * (n + 1) / 2 - (m - 1) * (m - 1 + 1) / 2
[n * (n + 1) - (m - 1) * m] / 2
[n* n + n - m * m + m] / 2
[(n + m) + n * n- m * m]  / 2
[(n + m) + (n - m) * (n + m)] / 2
(n + m)( n - m +1) / 2

Last edited on
It's quicker just to do (as for any arithmetic progression):

sum = (number of elements) * (average element)
    = ( n - m + 1 ) * ( m + n ) / 2

(in the case where, WMLOG, n is the larger number )
Yep. As from first principles:


S = m + (m + 1) + (m + 2) + ... + (n - 2) + (n - 1) + n
S = n + (n - 1) + (n - 2) + ... + (m + 2) + (m + 1) + m

S + S = (n + m) + (m + 1 + n - 1) + (m + 2 + n - 2) + ... + (n - 2 + m + 2) + (n - 1 + m + 1) + (n + m)

2 * S = (n + m) + (n + m) + (n + m) + ... for (n - m + 1) terms
2 * S = (n + m) * (n - m + 1)
S = (n + m) * (n - m + 1) / 2
S = (n - m + 1) * (n + m) / 2

Topic archived. No new replies allowed.