Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C program Problem B: Write a function that has two integer parameters and return

ID: 3786702 • Letter: C

Question

C program

Problem B: Write a function that has two integer parameters and returns an integer that equals the argument that is smaller in absolute value. If the two arguments have the same absolute value but different sign, the function should return the positive one. If the two arguments are identical, their (common) value should be returned. Write a main program that tests your function with enough test cases to give you confidence in the correctness of your function. Use assertions and, optionally, calls to printf. The function prototype should be

int smallerabsval(int x, int y);

Explanation / Answer

#include <stdio.h>
#include <assert.h>

int smallerabsval(int x, int y);
int main()
{
assert(2 == smallerabsval(2,2));

printf("Result is %d ", smallerabsval(2,2));

assert(2 == smallerabsval(2,-2));

printf("Result is %d ", smallerabsval(2,-2));

assert(2 == smallerabsval(2,3));

printf("Result is %d ", smallerabsval(2,3));
  

return 0;
}
int smallerabsval(int x, int y){
if(x == y){
return x;
}
else if(abs(x) == abs(y)){
if(x < y){
return y;
}
else{
return x;
}
}
else{
if(x < y){
return x;
}
else{
return y;
}
}
}

Output:

sh-4.2$ gcc -o main *.c                                                                                                                                                                                                                                

sh-4.2$ main                                                                                                                                                                                                                                           

Result is 2                                                                                                                                                                                                                                            

Result is 2                                                                                                                                                                                                                                            

Result is 2