Carry Flag in 8-bit Addition

Code

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

void add_with_carry(uint8_t a, uint8_t b, uint8_t* result, uint8_t* carry) {
    // Your logic here
    *result = a + b;
    *carry = (*result < a) ? 1 : 0;
}

int main() {
    uint8_t a, b, result, carry;
    scanf("%hhu %hhu", &a, &b);

    add_with_carry(a, b, &result, &carry);

    printf("%u ", result);
    printf("%u", carry);
    return 0;
}

Solving Approach

  • *result = a + b performs 8-bit addition (wraps around if >255)
    • *carry = (*result < a) detects overflow:
    • If the result is smaller than a, it means a wrap occurred → carry = 1
Upvote
Downvote
Loading...

Input

100 50

Expected Output

150 0