Sunday 24 February 2013

C/C++ Puzzles: PART - 20

Finding the Sum of Two Positive Integers without using Any Operator
  The Problem asks you to find the sum of two positive integers without using any of the C Operators. The solution given below uses the properties of printf( ) function defined in the header file <stdio.h>.

#include<stdio.h>
int main()
{
     int a,b;
     printf("Enter the Two Numbers:\n");
     scanf("%d%d",&a,&b);
     printf("\nThe Sum is %d\n",printf("%*c%*c",a,'\r',b,'\r'));
     return 0;
}

Here the inner printf( ) function returns the number of characters successfully printed by it. The format "%*c%*c" tells to print the character '\r' (Carriage Return) using 'a' number of spaces and 'b' number of spaces. So the total number of characters successfully printed is a+b. Hence the sum of two numbers is printed as the output.

Figure Below Shows a Sample Output

No comments:

Post a Comment