Pages

Friday, 10 May 2013

C program for binary addition using two's complement


1 Pseudocode:

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


2 Program:
#include <stdio.h>
#include <conio.h>
#include <math.h>
void main(){
clrscr();
            int c = 0,numa[8]={0},numb[8]={0},sum[8]={0};
            printf("\tADDITION USING TWO'S COMPLEMENT");
            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]);
            }

getch();
}

©Dixit Bhatta 2013

1 comment:

Was this post helpful? Ask any questions you have, I will try to answer them for you.