﻿ C Program: Sum 3 integers, if 2 are same return third

# C Exercises: Compute the sum of three given integers. If the two values are same return the third value

## C-programming basic algorithm: Exercise-29 with Solution

Write a C program to compute the sum of three given integers. Return the third value if the two values are the same.

C Code:

``````#include <stdio.h>
#include <stdlib.h>

// Function prototype for 'test'
int test(int x, int y, int z);

int main(void){
// Printing the results of calling 'test' function with different arguments
printf("%d",test(4, 5, 7));
printf("\n%d",test(7, 4, 12));
printf("\n%d",test(10, 10, 12));
printf("\n%d",test(12, 12, 18));
}

// Definition of the 'test' function
int test(int x, int y, int z)
{
// Checking if all three arguments are equal
if (x == y && y == z) return 0;

// Checking if 'x' and 'y' are equal
if (x == y) return z;

// Checking if 'x' and 'z' are equal
if (x == z) return y;

// Checking if 'y' and 'z' are equal
if (y == z) return x;

// If none of the above conditions are met, return the sum of all three arguments
return x + y + z;
}
``````

Sample Output:

```16
23
12
18
```

Explanation:

```int test(int x, int y, int z) {
if (x == y && y == z) return 0;
if (x == y) return z;
if (x == z) return y;
if (y == z) return x;
return x + y + z;
}
```

The above function first checks if all three integers are the same, in which case it returns 0. If not, it checks for each pair of integers to see if they are the same. If a pair is found, the function returns the value of the third integer. If none of the pairs are equal, the function returns the sum of all three integers.

Time complexity and space complexity:

The time complexity of the function is O(1) as it performs a constant number of comparisons and arithmetic operations, so its time complexity is constant.

The space complexity of the function is O(1) as it uses a constant amount of memory, regardless of the input size.

Pictorial Presentation: Flowchart: C Programming Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿