Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

USER DEFINED FUNCTIONS! C++! Example 3: // this function receives the lower and

ID: 3812635 • Letter: U

Question

USER DEFINED FUNCTIONS! C++!

Example 3:

// this function receives the lower and upper boundaries of a range of whole numbers and a divisor. It returns the
// algebraic addition of all the numbers within the specified range (boundaries included) processed according to the // following rules:
// -if the number being processed is divisible by the divisor received, the number is ADDED to the accumulated value // -if the number being processed is NOT divisible by the divisor received, the number is SUBTRACTED from the
// accumulated value

magicNumber( ) {

}

int main( )
{
// declare variable(s)

// prompt the user to enter the range's lower and upper boundaries // get the values and store them in the corresponding variables
// prompt the user to enter the divisor
// get the values and store them in the corresponding variables

// display the magic number (must call the function to get it)

}

OUTPUT:

enter a valid range (first value smaller than second value) and a valid divisor (not zero)

Please enter the range's lower and upper boundaries: 1 50 Please enter the divisor: 3

Explanation / Answer

#include <iostream>

using namespace std;


/**
* this function receives the lower and upper boundaries of a range of whole numbers and a divisor.
* It returns the algebraic addition of all the numbers within the specified range (boundaries included) processed according to the
* following rules:
* -if the number being processed is divisible by the divisor received, the number is ADDED to the accumulated value
* -if the number being processed is NOT divisible by the divisor received, the number is SUBTRACTED from th accumulated value
*/
int magicNumber(int start, int end, int divisor)
{
int magicN = 0;
for(int i = start; i <= end; i++)
{
if (i % divisor == 0)
{
magicN += i;
}
else
{
magicN -= i;
}
}
return magicN;
}

int main()
{
int start, end, divisor;
cout << "enter a valid range (first value smaller than second value) and a valid divisor (not zero)" << endl;
cout << "Please enter the range's lower and upper boundaries: " ;
cin >> start >> end;

cout << "Please enter the divisor: ";
cin >> divisor;

cout << "The magic number is: " << magicNumber(start, end, divisor) << endl;


return 0;
}

Sample run:

enter a valid range (first value smaller than second value) and a valid divisor (not zero)
Please enter the range's lower and upper boundaries: 1 50
Please enter the divisor: 3
The magic number is: -459