Write a recursive operation for takeAbsoluteValue. takeAbsoluteValue is a proced
ID: 3672231 • Letter: W
Question
Write a recursive operation for takeAbsoluteValue. takeAbsoluteValue is a procedure that applies the C++ abs(int x) operation to all Integers found in the sequence 's', all non-negative Integers are unchanged, all negative Integers are replaced by their positive counterparts The header for the C++ abs() operation is provided to the right Here is the header for the takeAbsoluteValue operation:
// requires: true
// ensures: All non-negative Integers in s are unchanged and all negative Integers in s are replaced by their positive counterparts
void takeAbsoluteValue (SequenceOfInteger& s)nterparts { }
Explanation / Answer
#include <stdio.h>
#define CHAR_BIT 8
/* This function will return absoulte value of n*/
unsigned int getAbs(int n)
{
int const mask = n >> (sizeof(int) * CHAR_BIT - 1);
return ((n + mask) ^ mask);
}
/* Driver program to test above function */
int main()
{
int n = -6;
printf("Absoute value of %d is %u", n, getAbs(n));
getchar();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.