I am a bit confused in functions maybe because I am teaching myself but can any
one tell me how to find sum of all the number between two integers entered by the user, using a function regardless of which input is bigger. Thank you
Break it down into smaller parts.
1. Create a function which takes your two numbers as parameters
2. Find which is the bigger number
3. loop from the smallest to biggest
4. add the control variable of the loop to a sum variable
5. Return the sum
#include <iostream>
// "const" and "&" are so a copy of Num1 and Num2 aren't created
int add(constint& Num1, constint& Num2)
{
int Sum = 0;
int numMin = (Num1 < Num2) ? Num1 : Num2;
int numMax = (Num1 > Num2) ? Num1 : Num2;
// Add all numbers betweeen Num1 and Num2
for (int Temp = numMin; Temp < numMax; Temp++)
{
Sum += Temp;
}
return Sum;
}
int main()
{
int Num1, Num2, Sum;
std::cout << "Enter the two numbers you would like to add:\n\n";
std::cout << "1st number: ";
std::cin >> Num1;
std::cout << "2nd number: ";
std::cin >> Num2;
// Add the numbers in between
Sum = add(Num1, Num2);
std::cout << "\n\nAnswer: " << Sum;
return 0;
}
If the user enters a higher number first it does not work.
I would make these changes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int add(int num1,int num2)
{
int sum = 0;
int temp = 0;
if (num2 < num1) {
swap(num1, num2);
}
for (int i = num1 + 1; i < num2; i++)
{
sum += i;
}
return sum;
}