Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Problem Statement
3.
Some Examples
4.
Program to add two numbers in C++
4.1.
Method 1: Using + Operator
4.2.
Method 2: Using - Operator
4.3.
Method 3: Using ++(Increment)/--(Decrement) Operator
4.4.
Method 4: Using printf() function
4.5.
Method 5: Using Half Adder method
4.6.
Method 6: Using log() and exp() function
5.
Frequently Asked Questions
5.1.
How to add two numbers in C++?
5.2.
What are the best method to add two numbers in C++?
5.3.
What are the disadvantages of using printf() method to add two numbers in C++?
5.4.
What are the disadvantages of using log() and exp() methods to add two numbers in C++?
6.
Conclusion
Last Updated: Sep 6, 2024
Easy

Program to add two numbers in C++

Author Tanay kumar Deo
2 upvotes

Introduction

Adding two numbers is one of the fundamental operations in programming, and implementing this in C++ provides a basic understanding of syntax, variables, and input/output operations. A simple program to add two numbers in C++ involves declaring variables to store the numbers, taking user input, performing the addition, and then displaying the result. 

Program to add two numbers in C++

This blog will discuss the problem: Program to add two numbers in C++

Problem Statement

Write a program to add two numbers in C++ by taking inputs from the user.

Some Examples

Input

a = 3

b = 2

Output

Sum = 5

Explanation

The sum of two numbers a and b can be obtained by sum = a + b i.e. sum = 3 + 2 = 5.

 

Input

a = 799

b = 1

Output

Sum = 800

Explanation

The sum of two numbers a and b can be obtained by sum = a + b i.e. sum = 799 + 1 = 800.

Also see, Literals in C.

Program to add two numbers in C++

Now we will solve this problem on how to add two numbers in C++ using many different methods. These methods are as follows:

Method 1: Using + Operator

First, let's start with a very simple program to add two numbers in C++ using addition (+) operators.

Code:

#include <iostream>
using namespace std;


// Function to add two numbers
int addTwoNumber(int a, int b)
{
    // Return sum of a and b
    int sum = a + b;
    return sum;
}
 
// Driver Code
int main()
{
    // Given two number
    int a = 3, b = 2;
 
    // Function call
    cout << "sum of " <<a<<" and "<<b<< " = "<< addTwoNumber(a, b)<<endl;
    cout << "sum of " <<799<<" and "<<1<< " = "<< addTwoNumber(799, 1)<<endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

sum of 3 and 2 = 5
sum of 799 and 1 = 800

Time Complexity: O(1) because we add two numbers using + operation in linear time.

Space Complexity: O(1) because only one extra variable is used.

Try and compile with online c++ compiler.

Method 2: Using - Operator

Here simply, we will use the subtraction operator ( - ) between the two numbers two times so that minus and minus multiply and produces + operator and return the sum of the number. 

This method used the following formula: A - ( -B ) = A + B.

We can implement this approach as mentioned below:

Code:

#include <iostream>
using namespace std;


// Function to add two numbers
int addTwoNumber(int a, int b)
{
    // Return sum of a and b
    int sum = a - (-b);
    return sum;
}
 
// Driver Code
int main()
{
    // Given two number
    int a = 3, b = 2;
 
    // Function call
    cout << "sum of " <<a<<" and "<<b<< " = "<< addTwoNumber(a, b)<<endl;
    cout << "sum of " <<799<<" and "<<1<< " = "<< addTwoNumber(799, 1)<<endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

sum of 3 and 2 = 5
sum of 799 and 1 = 800

Time Complexity: O(1) because we add two numbers using - operator in constant time.

Space Complexity: O(1) because only one extra variable is used.

Method 3: Using ++(Increment)/--(Decrement) Operator

The Increment (++) operator increments the variable's value by 1, and the decrement (--) operator decreases by 1. So, we can increment the value of any variable a to a+b by calling increment operator b times. Similarly, we can use the decrement operator to add any negative value of b in a.

The implementation of this method is shown below:

Code:

#include <iostream>
using namespace std;


// Function to add two numbers
int addTwoNumber(int a, int b)
{
    if(b > 0){
            // For positive b
            for(int i=0; i<b; i++){
                    a++;
            }
    }else{
            // For negative b
            for(int i = b; i<0; i++){
                    a--;
            }
    }
    
    return a;
}
 
// Driver Code
int main()
{
    // Given two number
    int a = 3, b = 2;
 
    // Function call for positive a and b
    cout << "sum of " <<a<<" and "<<b<< " = "<< addTwoNumber(a, b)<<endl;
    
    // Function call for negative b
    cout << "sum of " <<799<<" and "<<-499<< " = "<< addTwoNumber(799, -499)<<endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

sum of 3 and 2 = 5 
sum of 799 and -499 = 300

 

Time Complexity: O(b) because we loop b times to get our desired result.

Space Complexity: O(1) because only one extra variable is used.

Method 4: Using printf() function

We will use the “%*s” specifier in the printf() function in this method. The approach for this method is based on the below approach,

printf(“%*s%*s”, A, “”, B, “”);
You can also try this code with Online C++ Compiler
Run Code

 

Here "%*s" specifier will print a variable the value of the variable times, and the printf() returns how many characters print on the screen. 

For example, (“%s*s”, 3,””,2,””) will first print 3 white spaces, then 2 white spaces. Now printf() function will return the count of these characters i.e. 5 (3 + 2) in this case. This count is the sum of the two numbers.

Here is the implementation of the above method:

Code:

#include <iostream>
using namespace std;


// Function to add two numbers
int addTwoNumber(int a, int b)
{
    // Returns the sum of a and b
    return printf("%*s%*s", a, "", b, "");
}
 
// Driver Code
int main()
{
    // Given two number
    int a = 3, b = 2;
 
    // Function call for positive a and b
    cout << "sum = " << addTwoNumber(a, b)<<endl;
    
    // Function call for negative b
    cout << "sum = " << addTwoNumber(799, -499)<<endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

sum of 3 and 2 = 5 
sum of 799 and -499 = 1298

 

Note: In the output, we see that the sum of positive integers is correct. But the sum of 799 and -499 is wrong. This is because the printf() method return the total number of characters produced by "%*s", which cannot be negative. So we cannot find the sum of negative integers using the printf() function.

Method 5: Using Half Adder method

The Half adder method states that the sum of two bits can be achieved by performing Bitwise XOR(^) of the two bits. A carry bit can be achieved by performing Bitwise AND(&) of two bits.

Sum = A&B;
Carry = x^y
You can also try this code with Online C++ Compiler
Run Code

 

We can expand this logic for integer values. If x and y do not have set bits at the same position, then x ^ y gives the sum of x and y. And for the same set, bitwise AND (&) can be used. x & y gives all carry bits. We can calculate (x & y) << 1 and then add it to x ^ y to get the result.

Here is the implementation of the above method:

#include <iostream>
using namespace std;


// Function to add two numbers
int addTwoNumber(int a, int b)
{
    // Iterate till there is no carry
    while (b != 0) {
 
            // Carry contains common set bits of a and b
            int carry = a&b;
 
            // Sum of bits of a and b (not set bits)
            a = a ^ b;
 
            // Carry is shifted by 1
            b = carry << 1;
    }
    
    return a;
}
 
// Driver Code
int main()
{
    // Given two number
    int a = 3, b = 2;
 
    // Function call for positive a and b
    cout << "sum = " << addTwoNumber(a, b)<<endl;
    
    // Function call for negative b
    cout << "sum = " << addTwoNumber(799, -499)<<endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

sum of 3 and 2 = 5 
sum of 799 and -499 = 300

 

Time Complexity: O(log b)

Space Complexity: O(1) as no extra space was used.

Method 6: Using log() and exp() function

In this method we will find the exponential of the two numbers and then print the logarithm of the multiplication on the both results. The idea behind this method is as follows

Sum = log( exp(a) * exp(b) );
Sum = log( exp(a) ) + log( exp(b) );
Sum = a + b
You can also try this code with Online C++ Compiler
Run Code

 

Here is the implementation of the above method:

#include <bits/stdc++.h>
using namespace std;


// Function to add two numbers
int addTwoNumber(int a, int b){
    return log(exp(a) * exp(b));
}
 
// Driver Code
int main(){
    // Given two number
    int a = 3, b = 2;
 
    // Function call for positive a and b
    cout << "sum = " << addTwoNumber(a, b)<<endl;
    
    // Function call for negative b
    cout << "sum = " << addTwoNumber(79, -49)<<endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

sum of 3 and 2 = 5 
sum of 79 and -49 = 128

 

Time Complaxity: O((log a) * (log b)) as time complexity of log() is O(1) and that of exp() is log(n).

Space Complexity: O(1) as no extra space was used.


Check out this problem - Two Sum Problem

Also check out Addition of Two Numbers in Java here.

Also readDecimal to Binary c++

Frequently Asked Questions

How to add two numbers in C++?

To add two numbers in C++, declare two variables to store the numbers, take user input using cin, and then add the values using the + operator. Finally, display the result using cout. This simple operation demonstrates basic C++ syntax.

What are the best method to add two numbers in C++?

The best methods to add two numbers in C++ are by using the + operator and - operator as they have a time complexity of O(1) and are very easy to implement.

What are the disadvantages of using printf() method to add two numbers in C++?

The main disadvantage of using printf() method with the "%*s" specifier is that this method fails for any negative integer value.

What are the disadvantages of using log() and exp() methods to add two numbers in C++?

The disadvantage of using log() and exp() method is that is slow, i.e. it has a time complexity of O(log a * log b). Also, we can not calculate the sum of two large numbers as exp(a) will be out of the range of int or long for larger numbers.

Conclusion

Program to add two numbers in C++ is an easy program that introduces key programming concepts such as variable declaration, input/output operations, and arithmetic operations. Mastering this basic program lays the foundation for more complex coding challenges, helping beginners build confidence in their programming skills.

We hope that this blog has helped you enhance your knowledge on how to add two numbers in C++, and if you would like to learn more, check out our articles on STL containers in C++Data Types in C++ and Implementing Sets Without C++ STL Containers. Do upvote our blog to help other ninjas grow. 

Live masterclass