Author Topic: Turbo C Binary Number Addition without Array  (Read 1772 times)

kathir

  • Administrator
  • Sr. Member
  • *****
  • Posts: 283
Turbo C Binary Number Addition without Array
« on: April 02, 2012, 01:32:27 pm »
Here is the Turbo C program to add two binary numbers without using array.

Code:
//Source Code Listing

#include <stdio.h>
#include <conio.h>

#define NUM_BINARY_DIGITS 16

int AddBinaryNumbers(int number1, int number2)
{
   int i, c = 0, sum = 0;
   int a, b;
   int factor = 1;

   for(i = 0; i < NUM_BINARY_DIGITS; i++)
   {
      a = (number1 % 10) ? 1 : 0;
      b = (number2 % 10) ? 1 : 0;
      number1 /= 10;
      number2 /= 10;
      sum += ((a ^ b) ^ c) * factor; 
      factor *= 10;
      c = ((a & b) | (b &c)) | (b & c);
   }
   if(c > 0)
      sum += factor; 
   
   return sum;
}

void main()
{
   printf("Program for Binary Number Addition\n");
   
   printf("Number First Number:");
   scanf("%d", &x);

   printf("Number Second Number:");
   scanf("%d", &y);

   z = AddBinaryNumbers(x,y);

   printf("Sum = %d\n", z);
}


Program for Binary Number Addition
Number First Number:10101010
Number Second Number:1
Sum = 10101011

 


Disclaimer: This web site is for educational and informational purposes only. Click here to read the Disclaimer.
Content copyright 2010-2014. Kathiresan. All rights reserved.
This page is using SMF version 2.0.1