All submissions

Detect Underflow in Unsigned Subtraction

Code

#include <stdio.h>
#include <stdint.h>

void subtract_with_underflow(uint8_t a, uint8_t b, uint8_t *diff, uint8_t *carry) 
{
   if((a-b)<0) //If the difference of two numbers is negative, then we need to take sum of 256 and (difference of two numbers). 
   {
    *diff=256+(a-b);
    *carry=1;
   }
   else 
   {
   *diff=a-b;
   *carry=0;
   }
}

int main() {
    uint8_t a, b, diff, carry;
    scanf("%hhu %hhu", &a, &b);
    subtract_with_underflow(a, b, &diff, &carry);
    printf("diff = %u, carry = %u", diff, carry);
    return 0;
}

Solving Approach

 

 

 

Loading...

Input

100 50

Expected Output

diff = 50, carry = 0