1 Pseudocode:
1. Start
2. Ask user to enter choice
3. Clear all variables
4. Call ‘add’ function if addition, otherwise ‘sub’ function
5. Continue until user wants
6. End
Add
function:
1. Start
2. Ask user to enter two 8-bit numbers: num1, num2
3. carry = 0
4. Begin Addition from LSB
5. sum = num1[i] + num2[i] + carry
6. If sum of two bits >= 2, carry = 1
7. Otherwise, carry = 0
8. sum = sum % 2
9. Repeat 5 through 8 until all bits are added
10. Display sum
11. End
Sub
function:
1. Start
2. Ask user to enter two 8-bit numbers: num1, num2
3. Begin Addition from LSB
4. diff = num1[i] – num2[i]
5. If difference of two bits < 0, num1[i-1] = num1[i-1] - 1
6. diff = absolute(diff % 2)
7. Repeat 5 through 7 until all bits are added
8. Display diff
9. End
2 Program:
#include <stdio.h>
#include <conio.h>
#include <math.h>
int c =
0,numa[8]={0},numb[8]={0},diff[8]={0},sum[8]={0};
void add();
void sub();
void main(){
int
ch;
do{
clrscr();
for(int
i=0; i<8; i++){
numa[i]
= 0;
numb[i]
= 0;
diff[i]
= 0;
sum[i]
= 0;
}
c
= 0;
printf("\tADDITION-SUBTRACTION
USING TWO'S COMPLEMENT");
printf("\n1.ADD\n2.SUBTRACT\nEnter
your choice: ");
scanf("%d",&ch);
switch(ch){
case
1: add();
break;
case
2: sub();
break;
default:
printf("\nInvalid Choice: ");
}
printf("\nPress
1 to Continue...");
scanf("%d",&ch);
}while(ch
== 1);
}
void add(){
printf("\nEnter
two 8-bit binary numbers\n");
printf("\nEnter
first number: ");
for(int
i = 0; i<8; i++){
scanf("%d",&numa[i]);
}
printf("\nEnter
second number: ");
for(i
= 0; i<8; i++){
scanf("%d",&numb[i]);
}
for(i
= 7; i >= 0; i--){
sum[i]
= numa[i]+ numb[i] + c;
if(sum[i]>=2){
c
= 1;
}
else
c
= 0;
sum[i]
= sum[i]%2;
}
printf("\nSum
is: ");
for(i
= 0; i<8; i++){
printf("%d",sum[i]);
}
}
void sub(){
printf("\nEnter
two 8-bit binary numbers\n");
printf("\nEnter
first number: ");
for(int
i = 0; i<8; i++){
scanf("%d",&numa[i]);
}
printf("\nEnter
second number: ");
for(i
= 0; i<8; i++){
scanf("%d",&numb[i]);
}
for(i
= 7; i >= 0; i--){
diff[i] = numa[i] - numb[i];
if(diff[i]
< 0){
numa[i-1]
= numa[i-1] - 1;
}
diff[i]
= fabs(diff[i]%2);
}
printf("\nDifference
is: ");
for(i
= 0; i<8; i++){
printf("%d",diff[i]);
}
}
©Dixit Bhatta 2013
No comments:
Post a Comment
Was this post helpful? Ask any questions you have, I will try to answer them for you.