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.
It’s a trick question. 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 ‘width’, the output is padded with blank spaces. If number of digits are more, the output is printed as it is (not truncated). In the following program, add() returns sum of x and y. It prints 2 spaces within the width specified using x and y. So total characters printed is equal to sum of x and y. That is why add() returns x+y.
Sum = 7
The output is seven spaces followed by “Sum = 7”. We can avoid the leading spaces by using carriage return. Thanks to krazyCoder and Sandeep for suggesting this. The following program prints output without any leading spaces.
Sum = 7
Another Method :
sum = 15
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Execution of printf with ++ operators
- How to sum two integers without using arithmetic operators in C/C++?
- C Program to print numbers from 1 to N without using semicolon?
- Difference between ++*p, *p++ and *++p
- Results of comparison operations in C and C++
- Copy elision in C++
- Sequence Points in C | Set 1
- Add two numbers without using arithmetic operators
- Print "Even" or "Odd" without using conditional statement
- Write a C macro PRINT(x) which prints x
- How will you show memory representation of C variables?
- What is the best way in C to convert a number to a string?
- Change/add only one character and print '*' exactly 20 times
- Condition To Print "HelloWord"
- Program for Sum the digits of a given number
Improved By : falgunatara