C++ Exercises: Get the absolute difference between n and 51
C++ Basic Algorithm: Exercise-2 with Solution
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?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/cpp-exercises/basic-algorithm/cpp-basic-algorithm-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics