In: Computer Science
2 Program 1 - Special Values
Patrick Star wasted a lot of time in Boating School instead of signing up for his Spanish Class. Unfortunately for him, Spanish 101 is now full, and the only other class that will suit his schedule is Advanced Math. Patrick is determined not to let this defeat him. He will make his way up the stairs of learning one way or another. However, it’s been a while since Average Everyday Math, and he is somewhat behind. Patrick is going to put his programming class (he took that last term) to good use and write programs to do his homework. For the rest of this homework, you are Patrick Star, trying to outwit the math teacher.
For this program, we define a new term called Special Value. The Special Value of a number is the product of a random number between 15 and 25 (inclusive) and the difference between the number and its reverse.
1
For example, the Special Value of 1234 could be 55566 ( 18 * ( |
4321 - 1234 | ) ).
In this program, you are required to find the sum of the special
values of a set of numbers. Make
sure you conform to the following requirements.
Write a function called reverse that takes a number as a parameter and returns the reversed number. (20 points)
Write a function called value that accepts a number as a parameter, calculates the special value of that number, and returns it. This function should call the reverse function. (12 points)
In the main function, accept a seed for the Random Number Generator from the user, and use it to set up the RNG. (3 points)
Then, accept a series of numbers from the user. Stop if the number entered is 0. Use the value function to find the special value of each of the numbers as they are entered, and calculate their sum. Finally, print the sum. (10 points)
Make sure you add comments to explain your logic. (5 points)
2.1 Sample Run
Please note that the final answer depends on the random number generated at each function call, and you might get a different answer.
Enter the seed for the random number generator: 75361 Enter the numbers (0 to stop): 123 603
957 63 4567 62576 19
0 The sum of the special values is 99468
#include<bits/stdc++.h>
using namespace std;
//function to reverse a number
int reverse(int num)
{
int rev_num = 0;
while (num > 0)
{
rev_num = rev_num * 10 + num % 10;
num = num / 10;
}
return rev_num;
}
int value(int n) {
return (15 + rand() % 11) * abs(n - reverse(n));
}
int main() {
cout << "Enter the seed for the random number generator:";
int seed, result = 0;
//reading seed value
cin >> seed;
cout << "Enter the numbers (0 to stop):\n";
// loop runs untill user enters 0
while (true) {
int x;
cin >> x;
if (x == 0)
break;
result += value(x);
}
// displaying the result
cout << "The sum of the special values is " << result << endl;
return 0;
}
OUTPUT: