Labels

Saturday, 29 July 2017

How to find addition of two numbers without using any arithmatic operator?


To find sum of two numbers without using any arithmetic operator


Write a C program to find sum of positive integers without using any operator. Only use of printf() is allowed. No other library function can be used.
--> We can use printf() to find sum of two numbers as printf() returns the number of characters printed. The width field in printf() can be used to find the sum of two numbers. We can use ‘*’ which indicates the minimum width of output. For example, in the statement “printf(“%*d”, width, num);”, the specified ‘width’ is substituted in place of *, and ‘num’ is printed within the minimum width specified. --> If number of digits in ‘num’ is smaller than the specified ‘wodth’, the output is padded with blank spaces. If number of digits are more, the output is printed as it is (not truncated).
int add (int z, int x)
    return printf ("%*d%*d", z, 1, x, 2);
}
int main (void)
{
    printf ("\nsum=%d\n", add(4,4));
}
Output:
   1   2
sum=8
The output is: number "1" is represented in width (in 4 digit place, as <space><space><space><1>) and the number "2" is also followed the same. Totally first add() printed z+x characters on the console using printf and printf returns number of characters printed on the console. So we will get the addition result as a return value for add().

No comments:

Post a Comment