Write a program to find sum of positive integers without using any operator. Only use of printf() is allowed. No other library function can be used.
Solution
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.
#include int add(int x, int y) { return printf("%*c%*c", x, ' ', y, ' '); } // Driver code int main() { printf("Sum = %d", add(3, 4)); return 0; }
Output:
Sum = 7
Time Complexity: O(1)
Auxiliary Space: O(1)
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.
#include int add(int x, int y) { return printf("%*c%*c", x, '\r', y, '\r'); } // Driver code int main() { printf("Sum = %d", add(3, 4)); return 0; }
Output:
Sum = 7
Time Complexity: O(1)
Auxiliary Space: O(1)
Another Method :
#include int main() { int a = 10, b = 5; if (b > 0) { while (b > 0) { a++; b--; } } if (b < 0) { // when 'b' is negative while (b < 0) { a--; b++; } } printf("Sum = %d", a); return 0; } // This code is contributed by Abhijeet Soni
Output:
sum = 15
Time Complexity: O(b)
Auxiliary Space: O(1)
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.