w3resource

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:

C++ Basic Algorithm Exercises: Get the absolute difference between n and 51.

Flowchart:

Flowchart: Get the absolute difference between n and 51

For more Practice: Solve these Related Problems:

  • Write a C++ program to compute the absolute difference between an integer and 51, and triple the difference if the integer is greater than 51.
  • Write a C++ program that takes an integer input, calculates its absolute difference with 51, and returns triple the difference when the input exceeds 51.
  • Write a C++ program that computes the difference between a number and 51 and uses an if-statement to triple the result if the number is above 51.
  • Write a C++ program that reads a number, calculates |n-51|, and outputs triple the value if n > 51, otherwise outputs the difference as is.

Go to:


PREV : Triple Sum for Same Values.
NEXT : Check 30 or Sum 30.

C++ Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.