C Program to find sum of two numbers without using any operator

C++Server Side ProgrammingProgramming

In this section we will see how to print the sum of two numbers without using any type of operator into our program.

This problem is tricky. To solve this problem we are using minimum width field of printf() statement. For an example if we want to put x number of spaces before “Hello” using printf() we can write this. Here printf() takes the width and then the character that will be printed. In this case we are writing blank space.

Example Code

#include<stdio.h>
main() {
   int x = 10;
   printf("%*cHello", x, ' ');
}

Output

Hello

Now let us see how this functionality can help us to get the result of sum in our code. We take x and y as input to get result of x + y. So using this procedure we will create x number of spaces followed by y number of spaces. Then we take the returned value of the printf() as our result. We know that the printf() returns the length of that string.

Example Code

#include<stdio.h>
int add(int x, int y) {
   int len;
   len = printf("%*c%*c", x, ' ', y, ' ');
   return len;
}
main() {
   int x = 10, y = 20;
   int res = add(x, y);
   printf("\nThe result is: %d", res);
}

Output

The result is: 30
raja
Published on 04-Apr-2019 13:35:42
Advertisements