w3resource

C++ Exercises: Compute the sum of the two given integers, if one of the given integer value is in the range 10..20 inclusive return 18


Return 18 if Integer in Range 10–20

Write a C++ program to compute the sum of the two given integers. Return 18 if one of the given integer values is in the range 10..20 inclusive.

Sample Solution:

C++ Code :

#include <iostream>
using namespace std;

// Function to determine the result based on conditions involving two integers x and y
int test(int x, int y)
{
    // If x or y is between 10 and 20 (inclusive), return 18, else return the sum of x and y
    return (x >= 10 && x <= 20) || (y >= 10 && y <= 20) ? 18 : x + y;
}

int main() 
{
    // Testing the test function with different input values
    cout << test(3, 7) << endl;     // Output: 10 (sum of 3 and 7)
    cout << test(10, 11) << endl;   // Output: 18 (within the range 10-20)
    cout << test(10, 20) << endl;   // Output: 18 (within the range 10-20)
    cout << test(21, 220) << endl;  // Output: 241 (sum of 21 and 220, neither in the range 10-20)

    return 0; // Return 0 to indicate successful completion
}

Sample Output:

10
18
18
241

Visual Presentation:

C++ Basic Algorithm Exercises: Compute the sum of the two given integers, if one of the given integer value is in the range 10..20 inclusive return 18.

Flowchart:

Flowchart: Compute the sum of the two given integers, If the sum is in the range 10..20 inclusive return 18

For more Practice: Solve these Related Problems:

  • Write a C++ program to compute the sum of two integers, but if one of them lies in the range 10 to 20, return 18 instead.
  • Write a C++ program that reads two numbers and checks if either is between 10 and 20; if so, output 18, otherwise output their sum.
  • Write a C++ program to add two integers and override the result with 18 if any input number falls within the inclusive range 10–20.
  • Write a C++ program that conditionally returns 18 when one of the two integers is in the range 10–20; if not, it returns the computed sum.

C++ Code Editor:



Contribute your code and comments through Disqus.

Previous: Write a C++ program to check if a given number is within 2 of a multiple of 10.
Next: Write a C++ program to check whether a given string starts with "F" or ends with "B". If the string starts with "F" return "Fizz" and return "Buzz" if it ends with "B" If the string starts with "F" and ends with "B" return "FizzBuzz". In other cases return the original string.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.