C++ Exercises: Get the absolute difference between n and 51
Absolute Difference with 51
Write a C++ program to find the absolute difference between n and 51. If n is greater than 51 return triple the absolute difference.
Sample Solution:
C++ Code :
#include <iostream>
using namespace std;
// Function to perform a calculation based on the value of input 'n'
int test(int n)
{
const int x = 51; // Declare a constant variable 'x' with value 51
if (n > x) // Check if 'n' is greater than 'x'
{
return (n - x) * 3; // If 'n' is greater than 'x', return the result of (n - x) multiplied by 3
}
return x - n; // If 'n' is not greater than 'x', return the result of 'x' minus 'n'
}
// Main function
int main()
{
cout << test(53) << endl; // Output the result of test function with argument 53
cout << test(30) << endl; // Output the result of test function with argument 30
cout << test(51) << endl; // Output the result of test function with argument 51
return 0; // Return 0 to indicate successful execution of the program
}
Sample Output:
6 21 0
Visual Presentation:
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to compute the sum of the two given integer values. If the two values are the same, then return triple their sum.
Next: Write a C++ program to check two given integers, and return true if one of them is 30 or if their sum is 30.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics