Tuesday, 25 September 2012

Find sum of two numbers without using any arithmetic operators in C

Finding sum of two numbers in C is simple.
You simply add the two numbers using an ADDITION operator:

sum = num1 + num2;

Simple!

I had never come across something which said "how to find sum of two numbers in C, without using arithmetic operators".
Yes, this is possible. You can do this using the 'printf()' function in C.
Basically, a printf() returns the number of characters that the function prints, i.e. an int.

For example,

printf("%d",printf("Hello"));

will print 5, because the inner printf() prints 5 characters of the word 'Hello'(5 characters).

Also, you can specify how many times do you want to print a particular character by using a *, which represents the width field of printf():

For example,

printf("%*c",5,'A');

will print AAAAA, as we specified width=5.

Now, to find the sum of two numbers, all we need to do is to print a particular string whose length is equal to the sum of the two numbers.
Following is the way it can be done:

int a=3,b=4;
printf("%d",printf("%*c%*c",a,'A',b,'B'));

will print 7, which is the sum of a and b. This is because the inner printf returns a character string AAABBBB.

I hope this helps you.
So, next time you go in an interview and you are asked if its possible to find the sum of two numbers in C without using any arithmetic operators, you have your answer! :)

~SunMit