fueanta

sum or sub two integers (without +/- operators)

Sep 6th, 2016
425
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. /* Cpp program to sum or sub two integers (without +/- operators)
  2.  * Author: Taqui ; Date : 14 July,2016
  3.  * ###Copyright: All Rights Reserved###
  4.  */
  5.  
  6. #include <iostream>
  7. using namespace std;
  8.  
  9. // prototype declarations for sum and sub functions.
  10. int summation(int,int);
  11. int subtraction(int,int);
  12.  
  13. // main function starts:-
  14. int main(void) {
  15.     int a,b;
  16.     cout << "Here a and b are two integers." << endl;
  17.     cout << "Now,\ngive a: "; cin >> a;
  18.     cout << "And,\ngive b: "; cin >> b;
  19.     cout << "\nNow, Summation(a+b) of Subtraction(a-b)? Type (Sum/Sub): "; string choice; cin >> choice;
  20.     if (choice=="Sum")
  21.         cout << "\nThe summation(a+b) is: " << summation(a,b) << endl;
  22.     else if (choice=="Sub")
  23.         cout << "\nThe subtraction(a-b) is: " << subtraction(a,b) << endl;
  24.     cout << "\nRe-run the program? Type (Yes/No): " << endl; cin >> choice;
  25.     if (choice=="Yes")
  26.         { cout << endl; main(); }
  27.     else
  28.         cout << "\nThank You." << endl;
  29.     return 0;
  30. }
  31.  
  32. // definitions of several declared functions:-
  33. int summation (int x,int y) {
  34.     if (y==0)
  35.         return x;
  36.     int carry= (x&y); // and operation
  37.     x= x^y; // xor operation
  38.     y= carry <<1; // left shift operator
  39.     summation(x,y); // recursion
  40. }
  41. int subtraction (int x,int y) {
  42.     if (y==0)
  43.         return x;
  44.     int borrow= (~x)&y;
  45.     x= x^y;
  46.     y= borrow <<1;
  47.     subtraction(x,y);
  48. }
Advertisement
Add Comment
Please, Sign In to add comment