﻿ C Program: Find the value closest to 13 from 2 integers

# C Exercises: Check two given integers and return the value whichever value is nearest to 13 without going over

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

Write a C program to check two given integers and return the one nearest to 13 without crossing over. Return 0 if both numbers go over.

C Code:

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

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

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

// Definition of the 'test' function
int test(int x, int y) {
// Checking conditions and returning appropriate values based on comparisons
if (x > 13 && y > 13) return 0;
if (x <= 13 && y > 13) return x;
if (y <= 13 && x > 13) return y;

// If none of the above conditions are met, return the greater of 'x' and 'y'
return x > y ? x : y;
}
``````

Sample Output:

```5
12
13
0
```

Explanation:

```int test(int x, int y) {
if (x > 13 && y > 13) return 0;
if (x <= 13 && y > 13) return x;
if (y <= 13 && x > 13) return y;
return x > y ? x : y;
}
```

The above function takes two integers x and y as input parameters and performs the following operations:

• If both x and y are greater than 13, the function returns 0.
• If x is less than or equal to 13 and y is greater than 13, the function returns x.
• If y is less than or equal to 13 and x is greater than 13, the function returns y.
• If both x and y are less than or equal to 13, the function returns the larger of the two values.
• Time complexity and space complexity:

Time complexity: O(1), as the function has a constant number of operations, regardless of the input size.

Space complexity: O(1), as the function 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.

﻿