
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
Add two numbers using ++ operator in C++.
Adding two numbers is a basic arithmetic operation, where we simply combine their values to get the total. The given task is to add two numbers using the "++" operator in C++.
Let's understand this with an example:
Scenario 1
// Adding two numbers using '+' operator Input: a = 7, b = 3 Output: 10 Explanation: a + b => 7 + 3 = 10
Scenario 2
// Adding two numbers using '++' operator Input: a = 7, b = 3 Output: 10 Explanation: a + b => 7 + 1 + 1 + 1 = 10 (we increase 'a' 3 times because the second number 'b' is 3).
Adding Two Numbers Using the "++" Operator
The ++ operator is a unary increment operator, i.e., it operates on a single variable. It increases the value of a variable by 1. For example, if x is 3, then x++ will make it 4.
The idea is that we can increase the value of the first number as many times as the value of the second number using "++" to get the sum, to achieve this:
- Start a for loop with 0 as the initial value and the secondNumber as the end value.
- Within the loop, increment the first number.
Example
In the following C++ program, we are adding two numbers using the "++" operator:
#include <iostream> using namespace std; int main() { int firstNumber = 10, secondNumber = 5; // Add secondNumber to firstNumber using only ++ operator for (int i = 0; i < secondNumber; i++) { firstNumber++; } cout<<"First number is: "<< firstNumber <<endl; cout<<"Second number is: "<<secondNumber <<endl; cout << "Sum = " << firstNumber << endl; return 0; }
Following is the output of the above program:
First number is: 15 Second number is: 5 Sum = 20
Conclusion
In this article, we have learned how to add two numbers using the ++ operator by incrementing one number repeatedly. This method is simple and easy to understand.