Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to sum two integers without using arithmetic operators in C/C++ Program?
In this tutorial, we will be discussing a program to understand how to sum two integers without using arithmetic operators in C/C++.
For adding two integers without using arithmetic operators, we can do this with either using pointers or using bitwise operators.
Example
Using pointers
#include <iostream>
using namespace std;
int sum(int a, int b){
int *p = &a;
return (int)&p[b];
}
int main() {
int add = sum(2,3);
cout << add << endl;
return 0;
}
Output
5
Example
Using bitwise operators
#include <iostream>
using namespace std;
int sum(int a, int b){
int s = a ^ b;
int carry = a & b;
if (carry == 0)
return s;
else
return sum(s, carry << 1);
}
int main() {
int add = sum(2,3);
cout << add << endl;
return 0;
}
Output
5
Advertisements