Add two numbers

Add two numbers without arithmetic operator

Add two numbers without using arithmetic operator

In this program, we will see how to print the sum of two numbers without using any type of operator into our program. We take x and y as input to get the result of a + b. So using this procedure we will create some spaces followed by b number of spaces. Then we take the returned value of the printf() as our result. We know that the printf() returns the length of that string.

#include<stdio.h>
#include<conio.h>
int add(int a, int b) {
   int len;
   len = printf("%*c%*c", a, ' ', b, ' ');
   return len;
}
void main() {

   int a = 10, b = 20;
   int res = add(a, b);
   clrscr();
printf("\n\t\t\t...Welcome To EduNews.Tech... ");
   printf("\n\nThe result is: %d", res);
printf("\n\n\n\t\t\tThankyou for Joining Us !");
   printf("\n\t\t\t!Regards EduNews !");
   getch();
}

Program Output:

add two numbers

Another example- If a and b don’t have set bits at the same position(s), then bitwise XOR (^) of a and b gives the sum of a and b. To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of a and b gives all carry bits. We calculate (a & b) << 1 and add it to a ^ b to get the required result.

#include<stdio.h> 
#include<conio.h>
int Add(int a, int b) 
{ 
    // Iterate till there is no carry   
    while (b != 0) 
    { 
        // carry now contains common  
        //set bits of a and b 
        int carry = a & b;   
  
        // Sum of bits of a and b where at  
        //least one of the bits is not set 
        a = a ^ b;  
  
        // Carry is shifted by one so that adding 
        // it to x gives the required sum 
        b = carry << 1; 
    } 
    return a; 
} 
  
void main() 
{ 
printf(“…Welcome To EduNews.Tech…”);
    printf("%d", Add(10, 20)); 
    printf("\n\n\n\t\t\tThankyou for Joining Us !");
    printf("\n\t\t\t!Regards EduNews !");

getch();
} 

Program Output:

add two numbers-1

In both cases, our output is – 30

I hope this post helps you to understand the “Addition of two numbers” and its implementation in C programming language.

Keep coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *