-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Addition.c
More file actions
62 lines (53 loc) · 1.45 KB
/
Binary_Addition.c
File metadata and controls
62 lines (53 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main()
{
int A, B, temp;
bool isBinaryA, isBinaryB;
printf("Give me the first binary number : ");
do {
isBinaryA = true;
scanf("%d", &A);
temp = A;
if (temp == 0) isBinaryA = true;
while (temp > 0) {
int digit = temp % 10;
if (digit != 0 && digit != 1) {
isBinaryA = false;
printf("Invalid! Use only 0 and 1. Try again: ");
break;
}
temp /= 10;
}
} while (!isBinaryA);
printf("Give me the second binary number : ");
do {
isBinaryB = true;
scanf("%d", &B);
temp = B;
while (temp > 0) {
int digit = temp % 10;
if (digit != 0 && digit != 1) {
isBinaryB = false;
printf("Invalid! Use only 0 and 1. Try again: ");
break;
}
temp /= 10;
}
} while (!isBinaryB);
int carry = 0;
int result = 0;
int position = 1;
while (A || B || carry) {
int addition = (A % 10) + (B % 10) + carry;
int result_digit = addition % 2;
carry = addition / 2;
result = result + result_digit * position;
position *= 10;
A /= 10;
B /= 10;
}
printf("Result: %d\n", result);
return 0;
}