w3resource

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:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming-exercises/basic-algo/c-programming-basic-algorithm-exercises-32.php