Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding two numbers without using operators

Tags:

c

I found this following code for addition of two numbers without using the + operator.

code to add 3 and 4:

printf("%d",printf("%*c%*c",3,' ',4,' '));

Now printf() returns the number of characters in the result and %*c ignores the next character that it encounters. But still, I am not able to understand this code. Any help would be appreciated.

like image 207
Peps0791 Avatar asked Sep 08 '12 13:09

Peps0791


3 Answers

printf("%*c", n, c) prints the character c, n times. So the code prints 3 spaces followed by 4 spaces, and printf returns the number of characters printed, which is obviously 3 + 4, completing the problem.

like image 114
Peter Alexander Avatar answered Nov 14 '22 03:11

Peter Alexander


The inner printf outputs 3 then 4 spaces and returns the number of characters, which is 7, and the outer printf is printing that result.

like image 43
Basile Starynkevitch Avatar answered Nov 14 '22 03:11

Basile Starynkevitch


I am adding this answer to specify the rules of the standard.

Here this is utilizing the return value of printf. Respectively 3-1 spaces(' ') and then again space (as you specified) and 4-1 spaces and then again 1 space is being printed. And then the total number of characters written is returned. That is how the sum is being done.

I just remember this rule

printf("%*c",X,C) prints the char C in a field of size X

All these behavior is explained in C11 Standard.

From standard §7.21.6.1p4

An optional minimum field width. If the converted value has fewer characters than the field width, it is padded with spaces (by default) on the left (or right, if the left adjustment flag, described later, has been given) to the field width. The field width takes the form of an asterisk * (described later) or a nonnegative decimal integer.

And in the same section §7.21.6.1p5

As noted above, a field width, or precision, or both, may be indicated by an asterisk. In this case, an int argument supplies the field width or precision

At last §7.21.6.1.p14

The fprintf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.


To clear your idea this example will be good enough (I am using %d here so that you get the idea of the field).

If x = 10 and y=2 then it will be

printf("%*d%*d",  x, x,  y, y);

More clearly

| | | | | | | | |1|0| |2|
 1 2 3 4 5 6 7 8 9 10 \ \
                      11 12

That's how 12 characters are printed.
like image 1
user2736738 Avatar answered Nov 14 '22 04:11

user2736738