c++ code problem Write a function Diminish that is given an integer parameter an
ID: 3579913 • Letter: C
Question
c++ code problem
Write a function Diminish that is given an integer parameter and returns an integer value. The function will take the given value and repeatedly reduce the value.
The function should behave as follows: while the value is greater than 15, print the value to the console (each value on a separate line) and then reduce the value using integer arithmetic.
The value is reduced by the following rules:
if the value is odd, divide the value by 2.
if the value is even, divide the value by 3.
c++ code problem
Explanation / Answer
#include <iostream>
using namespace std;
int Diminish (int n){
int count = 0;
while(n > 15){
count++;
cout<<n<<endl;
if(n % 2 == 0){
n = n / 3;
}
else{
n = n / 2;
}
}
return count;
}
int main()
{
int n;
cout << "Enter a value: ";
cin >> n;
int count = Diminish(n);
cout<<"Number of operations: "<<count<<endl;
return 0;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
Enter a value: 1554341
1554341
777170
259056
86352
28784
9594
3198
1066
355
177
88
29
Number of operations: 12
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.