C++ Exercises: Compute the sum of three given integers. If the two values are same return the third value
Sum or Third Integer if Two are Equal
Write a C++ program to compute the sum of three given integers. Return the third value if the two values are the same.
Sample Solution:
C++ Code :
#include <iostream>
using namespace std;
// Function 'test' takes three integers (x, y, z) as parameters
int test(int x, int y, int z)
{
// Check if x, y, and z are all equal
if (x == y && y == z)
return 0; // Return 0 if all three numbers are equal
// Check if x and y are equal
if (x == y)
return z; // Return z if x and y are equal
// Check if x and z are equal
if (x == z)
return y; // Return y if x and z are equal
// Check if y and z are equal
if (y == z)
return x; // Return x if y and z are equal
// If none of the above conditions are met, return the sum of x, y, and z
return x + y + z;
}
int main()
{
// Testing the 'test' function with different sets of numbers
cout << test(4, 5, 7) << endl;
cout << test(7, 4, 12) << endl;
cout << test(10, 10, 12) << endl;
cout << test(12, 12, 18) << endl;
return 0;
}
Sample Output:
16 23 12 18
Visual Presentation:

Flowchart:

For more Practice: Solve these Related Problems:
- Write a C++ program to compute the sum of three integers, but if any two of them are equal, return the third integer.
- Write a C++ program that reads three numbers and outputs the third number if a pair among the first two or last two is equal; otherwise, print the sum of all three.
- Write a C++ program to compare three integers and, in the case of a duplicate pair, return the unique value; if no duplicates exist, output their total.
- Write a C++ program that accepts three integer inputs and checks for equality among any two, returning the non-duplicate value or the sum if all are distinct.
Go to:
PREV : Sum with Same Number of Digits or Return x.
NEXT : Sum Ignoring 13 and Right Values.
C++ Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?