Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Subtract two numbers without using arithmetic operators
Next article icon

To find sum of two numbers without using any operator

Last Updated : 02 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

C++
#include <iostream> using namespace std;   int add(int x, int y) {     return printf("%*c%*c", x, ' ', y, ' '); }  // Driver code int main() {     printf("Sum = %d", add(3, 4));     return 0; }  // This code is contributed by shubhamsingh10 
C
#include <stdio.h>  int add(int x, int y) {     return printf("%*c%*c", x, ' ', y, ' '); }  // Driver code int main() {     printf("Sum = %d", add(3, 4));     return 0; } 
Java
public class Add  {     public static void main(String[] args)      {         int x = 3, y = 4;         System.out.print("Sum = " + add(x, y));     }       public static int add(int x, int y)     {         String str = String.format("%" + x + "c%" + y + "c", ' ', ' ');         return str.length();     } } 
Python
# Python code for the above approach def add(x, y) :          return (x + y);     # Driver code if __name__ == "__main__":          print("Sum = ", add(3, 4))      # This code is contributed by splvel62. 
C#
using System;  namespace Add {     class Program     {         static void Main(string[] args)         {             int x = 3, y = 4;             Console.WriteLine("Sum = " + Add(x, y));         }          static int Add(int x, int y)         {             string str = string.Format("{0," + x + "}{1," + y + "}", ' ', ' ');             return str.Length;         }     } } 
JavaScript
function add(x, y) {     return console.log("%*c%*c", x, ' ', y, ' '); }  // Driver code function main() {     console.log("Sum = %d", add(3, 4));     return 0; }  main();  // This code is contributed by factworx412 

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.

C++
#include <iostream> using namespace std;  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; }  // This code is contributed by shubhamsingh10 
C
#include <stdio.h>  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; } 
Java
class GFG {      static int add(int x, int y) {         return (x + y);     }      // Driver code     public static void main(String[] args) {         System.out.printf("Sum = %d", add(3, 4));     } }  // This code is contributed by Rajput-Ji 
Python
# Python program for the above approach def add(x, y) :          return (x + y);       # driver code print("Sum = ", add(3, 4));  # This code is contributed by sanjoy_62 
C#
// C# program for the above approach using System;  public class GFG {    static int add(int x, int y)   {     return (x + y);   }     // Driver Code   public static void Main(String[] args) {      Console.WriteLine("Sum = " + add(3, 4));   } }  // This code is contributed by code_hunt. 
JavaScript
<script>     // JavaScript code for the above approach    function add(x, y)   {     return (x + y);   }      // Driver Code     document.write("Sum = " + add(3, 4));          // This code is contributed by avijitmondal1998. </script> 

Output: 

      Sum = 7

Time Complexity: O(1)

Auxiliary Space: O(1)


Another Method : 

C++
#include <iostream> using namespace std;  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++;         }     }     cout << "Sum = " << a;     return 0; }  // This code is contributed by SHUBHAMSINGH10 // This code is improved & fixed by Abhijeet Soni. 
C
#include <stdio.h>  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 
Java
// Java code class GfG {      public static void main(String[] args)     {         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++;             }         }         System.out.println("Sum is: " + a);     } }  // This code is contributed by Abhijeet Soni 
Python
# Python 3 Code  if __name__ == '__main__':          a = 10     b = 5      if b > 0:         while b > 0:             a = a + 1             b = b - 1     if b < 0:         while b < 0:             a = a - 1             b = b + 1          print("Sum is: ", a)  # This code is contributed by Akanksha Rai # This code is improved & fixed by Abhijeet Soni 
C#
// C# code using System;  class GFG {     static public void 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++;             }         }         Console.Write("Sum is: " + a);     } }  // This code is contributed by Tushil // This code is improved & fixed by Abhijeet Soni. 
JavaScript
<script>  // Javascript program for the above approach  // Driver Code      let a = 10, b = 5;     if (b > 0) {         while (b > 0) {             a++;             b--;         }     }     if (b < 0) { // when 'b' is negative         while (b < 0) {             a--;             b++;         }     }     document.write("Sum = " + a);  </script> 
PHP
<?php // PHP Code $a = 10; $b = 5;  if ($b > 0) { while($b > 0) {     $a++;     $b--; } }  if ($b < 0) { while($b < 0) {     $a--;     $b++; } }   echo "Sum is: ", $a;  // This code is contributed by Dinesh  // This code is improved & fixed by Abhijeet Soni. ?> 

Output: 

sum = 15

Time Complexity: O(b)
Auxiliary Space: O(1)

Approach: Bit Manipulation

Steps:

  1. Calculate the sum of the numbers without taking into account the carry.
  2. Calculate the carry using bitwise AND and shift left operator.
  3. Add the carry to the sum.
  4. Repeat steps 1-3 until there is no carry left.
C++
// C++ program for the above approach #include <iostream>  // Function to add two number without // operators int add_without_operator(int a, int b) {      while (b != 0) {          // Calculate sum without carry         int sum = a ^ b;          // Calculate carry         int carry = (a & b) << 1;          // Add sum and carry         a = sum;         b = carry;     }      return a; }  // Driver Code int main() {     int a = 5;     int b = 7;     int result = add_without_operator(a, b);     std::cout << "The sum of " << a << " and " << b               << " is: " << result << std::endl;      return 0; } 
Java
public class AddWithoutOperator {     public static int add(int a, int b)     {         while (b != 0) {             int sum = a ^ b; // XOR operation to calculate                              // sum without carry             int carry                 = (a & b)                   << 1; // AND and left shift operation to                         // calculate carry             a = sum;             b = carry;         }         return a;     }      public static void main(String[] args)     {         int a = 5;         int b = 7;         int result = add(a, b);         System.out.println("The sum of " + a + " and " + b                            + " is: " + result);     } } 
Python
def add_without_operator(a: int, b: int) -> int:     while b != 0:         # Calculate sum without carry         sum = a ^ b                  # Calculate carry         carry = (a & b) << 1                  # Add sum and carry         a = sum         b = carry          return a  a = 5 b = 7 result = add_without_operator(a, b) print(f"The sum of {a} and {b} is: {result}") 
C#
using System;  class Program {     // Function to add two number without operators     static int AddWithoutOperator(int a, int b)     {         while (b != 0)         {             // Calculate sum without carry             int sum = a ^ b;              // Calculate carry             int carry = (a & b) << 1;              // Add sum and carry             a = sum;             b = carry;         }          return a;     }      // Driver Code     static void Main(string[] args)     {         int a = 5;         int b = 7;         int result = AddWithoutOperator(a, b);         Console.WriteLine("The sum of {0} and {1} is: {2}", a, b, result);     } } 
JavaScript
function addWithoutOperator(a, b) { while (b !== 0) { // Calculate sum without carry let sum = a ^ b; // Calculate carry let carry = (a & b) << 1;  // Add sum and carry a = sum; b = carry; }  return a; }  // Driver Code let a = 5; let b = 7; let result = addWithoutOperator(a, b); console.log(`The sum of ${a} and ${b} is: ${result}`); 

Output
The sum of 5 and 7 is: 12

Time Complexity: O(log N), where N is the maximum number of bits in a or b.
Auxiliary Space: O(1)



Next Article
Subtract two numbers without using arithmetic operators
author
kartik
Improve
Article Tags :
  • Mathematical
  • C Language
  • DSA
  • C-Operators
Practice Tags :
  • Mathematical

Similar Reads

  • Add two numbers without using arithmetic operators
    Given two integers a and b, the task is to find the sum of a and b without using + or - operators. Examples: Input: a = 10, b = 30Output: 40 Input: a = -1, b = 2Output: 1 Approach: The approach is to add two numbers using bitwise operations. Let's first go through some observations: a & b will h
    5 min read
  • Subtract two numbers without using arithmetic operators
    Write a function subtract(x, y) that returns x-y where x and y are integers. The function should not use any of the arithmetic operators (+, ++, –, -, .. etc). The idea is to use bitwise operators. Addition of two numbers has been discussed using Bitwise operators. Like addition, the idea is to use
    8 min read
  • C++ program to divide a number by 3 without using *, / , +, -, % operators
    For a given positive number we need to divide a number by 3 without using any of these *, /, +, – % operatorsExamples: Input : 48 Output : 16 Input : 16 Output : 5 Algorithm Take a number num, sum = 0while(num>3), shift the number left by 2 bits and sum = add(num >> 2, sum). Create a functi
    2 min read
  • How to sum two integers without using arithmetic operators in C/C++?
    Given two integers a and b, how can we evaluate the sum a + b without using operators such as +, -, ++, --, ...? Method 1 (Using pointers)An interesting way would be: C/C++ Code // May not work with C++ compilers and // may produce warnings in C. // Returns sum of 'a' and 'b' int sum(int a, int b) {
    4 min read
  • Find average of two numbers using bit operation
    Given two integers x and y, the task is to find the average of these numbers i.e. (x + y) / 2 using bit operations. Note that this method will give result as floor value of the calculated average.Examples: Input: x = 2, y = 4 Output: 3 (2 + 4) / 2 = 3Input: x = 10, y = 9 Output: 9 Approach: Average
    3 min read
  • Multiplication of two numbers with shift operator
    For any given two numbers n and m, you have to find n*m without using any multiplication operator. Examples : Input: n = 25 , m = 13 Output: 325 Input: n = 50 , m = 16 Output: 800 Method 1We can solve this problem with the shift operator. The idea is based on the fact that every number can be repres
    7 min read
  • Javascript program to swap two numbers without using temporary variable
    To swap two numbers without using a temporary variable, we have multiple approaches. In this article, we are going to learn how to swap two numbers without using a temporary variable. Below are the approaches used to swap two numbers without using a temporary variable: Table of Content Using Arithme
    6 min read
  • Add two numbers using ++ and/or --
    Given two numbers, return a sum of them without using operators + and/or -, and using ++ and/or --.Examples: Input: x = 10, y = 5 Output: 15 Input: x = 10, y = -5 Output: 10 We strongly recommend you to minimize your browser and try this yourself first The idea is to do y times x++, if y is positive
    4 min read
  • Find two numbers from their sum and OR
    Given two integers X and Y, the task is to find two numbers whose Bitwise OR is X and their sum is Y. If there exist no such integers, then print "-1". Examples: Input: X = 7, Y = 11Output: 4 7Explanation:The Bitwise OR of 4 and 7 is 7 and the sum of two integers is 4 + 7 = 11, satisfy the given con
    6 min read
  • Addition of two numbers without propagating Carry
    Given 2 numbers a and b of same length. The task is to calculate their sum in such a way that when adding two corresponding positions the carry has to be kept with them only instead of propagating to the left.See the below image for reference: Examples: Input: a = 7752 , b = 8834 Output: 151586 Inpu
    15 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences