arithmetic-operators-in-c++

“`html

Arithmetic Operators in C++ are symbols employed to carry out mathematical computations. Additionally, these operators facilitate the incrementing and decrementing of variable values and can execute unary operations. In this article, we will explore the arithmetic operators in C++, their classifications, syntax, precedence, associativity, and examples within C++ programming.

Table of Contents:

What are Arithmetic Operators in C++?

Arithmetic Operators

Arithmetic operators in C++ refer to the operators utilized to conduct fundamental arithmetic tasks on variables or constants. They execute computations such as addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).

Syntax of Arithmetic Operators in C++

variable = value1 arithmetic_operator value2;

Where:

  • value1 and value2 represent numerical values or variables.
  • arithmetic_operator denotes one of the arithmetic operators.
  • and variable holds the computed result.

Types of Arithmetic Operators in C++

Arithmetic operators in C++ can be categorized into three groups based on the operations they execute.

Types of Arithmetic Operators in C++

1. Basic Arithmetic Operators

These arithmetic operators in C++ are employed to perform fundamental mathematical calculations.

Operator Name Symbol Description Syntax
Addition + Combines two numbers a + b
Subtraction – Removes the second from the first a – b
Multiplication * Multiplies two numbers a * b
Division / Divides the first by the second (quotient) a / b
Modulus % Returns the remainder from the division a % b

2. Unary Arithmetic Operators

Unary arithmetic operators are those that function on a single operand. They accept just one value and perform actions on it.

Operator Name Symbol Description Syntax
Unary Plus + Denotes a positive value (has no effect) +a
Unary Minus – Negates the value (turns positive to negative and vice versa) -a

3. Increment and Decrement Operators

These arithmetic operators are utilized to elevate and reduce the value of a variable by 1.

Operator Name Symbol Description Syntax
Pre-Increment ++a Increases value by 1 before usage ++a
Post-Increment a++ Uses value first, then increases by 1 a++
Pre-Decrement –a Reduces the value by 1 prior to usage –a
Post-Decrement a– Utilizes value first, then decreases by 1 a–

Basic Arithmetic Operators

Let’s briefly cover each of the basic arithmetic operators with examples in C++.

1. Addition (+)

The addition operator in C++ sums two numbers or operands.

Example:

“““html

Cpp

Code Copied!

var isMobile = window.innerWidth “);

editor69543.setValue(decodedContent); // Set the initial text editor69543.clearSelection();

editor69543.setOptions({ maxLines: Infinity });

function decodeHTML69543(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard69543() { const code = editor69543.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(“.maineditor69543 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor69543 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode69543() { var code = editor69543.getSession().getValue();

jQuery(“#runBtn69543 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”, data: { language: “cpp”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output69543”).html(“

" + data + "

“); jQuery(“.maineditor69543 .code-editor-output”).show(); jQuery(“#runBtn69543 i.run-code”).hide(); } }); }

function closeoutput69543() { jQuery(“.maineditor69543 .code-editor-output”).hide(); }

// Attach event listeners to the buttons document.getElementById(“copyBtn69543”).addEventListener(“click”, copyCodeToClipboard69543); document.getElementById(“runBtn69543”).addEventListener(“click”, runCode69543); document.getElementById(“closeoutputBtn69543”).addEventListener(“click”, closeoutput69543);

Output:

1. Addition

The code illustrates that the addition operator combines two integers, a and b, with values 16 and 5, resulting in 21 being displayed in the console.

2. Subtraction(-)

The subtraction operator in C++ deducts the second number from the initial number.

Example:

Cpp

Code Copied!

var isMobile = window.innerWidth “);

editor13500.setValue(decodedContent); // Set the initial text editor13500.clearSelection();

editor13500.setOptions({ maxLines: Infinity });

function decodeHTML13500(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard13500() { const code = editor13500.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(“.maineditor13500 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor13500 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode13500() { var code = editor13500.getSession().getValue();

jQuery(“#runBtn13500 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”, data: { language: “cpp”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output13500”).html(“

" + data + "

“); jQuery(“.maineditor13500 .code-editor-output”).show(); jQuery(“#runBtn13500 i.run-code”).hide(); } }); } “““html data = myArray[1];

jQuery(“.output13500”).html(“

"+data+"");
jQuery(".maineditor13500 .code-editor-output").show();
jQuery("#runBtn13500 i.run-code").hide();

}

})

}

function closeoutput13500() { var code = editor13500.getSession().getValue(); jQuery(".maineditor13500 .code-editor-output").hide(); }

// Add event listeners to the buttons document.getElementById("copyBtn13500").addEventListener("click", copyCodeToClipboard13500); document.getElementById("runBtn13500").addEventListener("click", runCode13500); document.getElementById("closeoutputBtn13500").addEventListener("click", closeoutput13500);

Output:

2. Subtraction

The snippet illustrates how the subtraction operator is utilized to deduct two integers, a = 8 and b = 3, with the outcome of 5 being displayed as output in the console.

3. Multiplication (*)

The multiplication operator in C++ is employed to multiply two values.

Example:

Cpp

Code Copied!

var isMobile = window.innerWidth ");

editor21587.setValue(decodedContent); // Set the default text editor21587.clearSelection();

editor21587.setOptions({ maxLines: Infinity });

function decodeHTML21587(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard21587() { const code = editor21587.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(".maineditor21587 .copymessage").show(); setTimeout(function() { jQuery(".maineditor21587 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode21587() { var code = editor21587.getSession().getValue();

jQuery("#runBtn21587 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output21587").html("

"+data+"");
            jQuery(".maineditor21587 .code-editor-output").show();
            jQuery("#runBtn21587 i.run-code").hide();

} }) }

function closeoutput21587() { var code = editor21587.getSession().getValue(); jQuery(".maineditor21587 .code-editor-output").hide(); }

// Attach event listeners to buttons document.getElementById("copyBtn21587").addEventListener("click", copyCodeToClipboard21587); document.getElementById("runBtn21587").addEventListener("click", runCode21587); document.getElementById("closeoutputBtn21587").addEventListener("click", closeoutput21587);

Output:

3. Multiplication

The code demonstrates how the multiplication operator combines two integers, a and b, with values 8 and 5, subsequently printing the resulting 40 to the console.

4. Division (/)

The division operator in C++ performs division of the first value by the second, yielding the quotient as a result.

Example:

Cpp

Code Copied!

var isMobile = window.innerWidth ``````html "");

editor84296.setValue(decodedContent); // Initialize the default text editor84296.clearSelection();

editor84296.setOptions({ maxLines: Infinity });

function decodeHTML84296(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to the clipboard function copyCodeToClipboard84296() { const code = editor84296.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code copied to clipboard!");

jQuery(".maineditor84296 .copymessage").show(); setTimeout(function() { jQuery(".maineditor84296 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode84296() { var code = editor84296.getSession().getValue();

jQuery("#runBtn84296 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output84296").html("

"+data+"");
            jQuery(".maineditor84296 .code-editor-output").show();
            jQuery("#runBtn84296 i.run-code").hide();
        }
    })
}

function closeoutput84296() { var code = editor84296.getSession().getValue(); jQuery(".maineditor84296 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn84296").addEventListener("click", copyCodeToClipboard84296); document.getElementById("runBtn84296").addEventListener("click", runCode84296); document.getElementById("closeoutputBtn84296").addEventListener("click", closeoutput84296);

Output:

4. Division

The code illustrates how the division operator accomplishes the division of integer a = 20 by integer b = 4, with the output of 5 displayed in the console.

5. Modulus (%) Operator

The modulus operator in C++ provides the remainder from dividing two integers. It exclusively operates on integer data types.

Example:

Cpp

Code Copied!

var isMobile = window.innerWidth "");

editor92797.setValue(decodedContent); // Initialize the default text editor92797.clearSelection();

editor92797.setOptions({ maxLines: Infinity });

function decodeHTML92797(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard92797() { const code = editor92797.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code copied to clipboard!");

jQuery(".maineditor92797 .copymessage").show(); setTimeout(function() { jQuery(".maineditor92797 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode92797() { var code = editor92797.getSession().getValue();

jQuery("#runBtn92797 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output92797").html("

"+data+"");
            jQuery(".maineditor92797 .code-editor-output").show();
            jQuery("#runBtn92797 i.run-code").hide();
        }
    })
}

function closeoutput92797() { var code = editor92797.getSession().getValue(); jQuery(".maineditor92797 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn92797").addEventListener("click", copyCodeToClipboard92797); document.getElementById("runBtn92797").addEventListener("click", runCode92797); document.getElementById("closeoutputBtn92797").addEventListener("click", closeoutput92797);

Output:

Output

The code demonstrates how the modulus operator works to obtain the...
``````html

The remainder is 2 when the two integers a = 20 and b = 3 are divided.

Priority and Evaluation of Arithmetic Operators in C++

The priority determines the sequence of operations executed by the operator, while the evaluation of an operator ascertains the sequence in which that operator is processed.

Operator Type of Operator Priority Evaluation
+ Unary Plus Highest Right to Left
– Unary Minus Highest Right to Left
* Multiplication Highest Left to Right
/ Division High Left to Right
% Modulus High Left to Right
+ Addition Low Left to Right
– Subtraction Lowest Left to Right

C++ Illustration of Unary Arithmetic Operators

Cpp

Code Copied!

var isMobile = window.innerWidth ");

editor36042.setValue(decodedContent); // Set the default text editor36042.clearSelection();

editor36042.setOptions({ maxLines: Infinity });

function decodeHTML36042(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard36042() { const code = editor36042.getValue(); // Get code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(".maineditor36042 .copymessage").show(); setTimeout(function() { jQuery(".maineditor36042 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode36042() { var code = editor36042.getSession().getValue();

jQuery("#runBtn36042 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1]; jQuery(".output36042").html("

"+data+"");
        jQuery(".maineditor36042 .code-editor-output").show();
        jQuery("#runBtn36042 i.run-code").hide();
    }
})

}

function closeoutput36042() { jQuery(".maineditor36042 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn36042").addEventListener("click", copyCodeToClipboard36042); document.getElementById("runBtn36042").addEventListener("click", runCode36042); document.getElementById("closeoutputBtn36042").addEventListener("click", closeoutput36042);

Result:

C++ Illustration of Unary Arithmetic Operators

The snippet illustrates how the unary plus operator retains the value of a, whereas the unary minus operator inverts the value of a.

C++ Illustration of Increment and Decrement Operators

Cpp

Code Copied!

// Rest of the script... ``````javascript "");

editor55753.setValue(decodedContent); // Set initial text editor55753.clearSelection();

editor55753.setOptions({ maxLines: Infinity });

function decodeHTML55753(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard55753() { const code = editor55753.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code copied to clipboard!");

jQuery(".maineditor55753 .copymessage").show(); setTimeout(function() { jQuery(".maineditor55753 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode55753() { var code = editor55753.getSession().getValue();

jQuery("#runBtn55753 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output55753").html("

"+data+"");
            jQuery(".maineditor55753 .code-editor-output").show();
            jQuery("#runBtn55753 i.run-code").hide();
        }
    })
}

function closeoutput55753() { var code = editor55753.getSession().getValue(); jQuery(".maineditor55753 .code-editor-output").hide(); }

// Attach event listeners to buttons document.getElementById("copyBtn55753").addEventListener("click", copyCodeToClipboard55753); document.getElementById("runBtn55753").addEventListener("click", runCode55753); document.getElementById("closeoutputBtn55753").addEventListener("click", closeoutput55753);

Output:

C++ Example of Increment and Decrement Operators

The code illustrates how ++a and –a first modify the values and then assign them, while a++ and a– first assign the value and subsequently modify it. The results of all operations are then displayed in the console.

Conclusion

Arithmetic operators in C++ are crucial for executing various types of mathematical tasks, such as addition and subtraction. These operators can also be utilized to increment and decrement the values of variables. Moreover, they have a defined order of precedence and associativity. By comprehending how these operators function along with their precedence and associativity, one can easily conduct arithmetic calculations in C++ programming.

FAQs

Q1. What occurs if I divide a number by zero?

Dividing a number by zero will result in a runtime error.

Q2. Can modulus be applied to floating-point numbers?

No, the modulus operator cannot be used with floating-point numbers. Therefore, you should use fmod() from <cmath> for floating points.

Q3. What differentiates a++ from ++a?

The distinction between a++ and ++a is that a++ returns the value first, followed by incrementing, whereas ++a increments first.

Q4. Why does integer division ignore decimals?

Integer division retains only the whole number.

Q5. How can you alter operator precedence?

To change the operator precedence, use parentheses ().

The article Arithmetic Operators in C++ was first published on Intellipaat Blog.

```


Leave a Reply

Your email address will not be published. Required fields are marked *

Share This