Skip to content

Commit daaf39d

Browse files
[Edit] C++: Operators (#7101)
* [Edit] SQL: DATEDIFF() * Update datediff.md * [Edit] C++: Operators * Changes ---------
1 parent f2b6006 commit daaf39d

File tree

1 file changed

+283
-39
lines changed

1 file changed

+283
-39
lines changed
Lines changed: 283 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,80 +1,324 @@
11
---
22
Title: 'Operators'
3-
Description: 'C++ supports different types of operators such as arithmetic, relational, and logical operators.'
3+
Description: 'Perform operations on operands to manipulate data, make calculations, and control program flow in C++ programming.'
44
Subjects:
55
- 'Computer Science'
6-
- 'Game Development'
6+
- 'Web Development'
77
Tags:
8-
- 'Operators'
98
- 'Arithmetic'
10-
- 'Comparison'
11-
- 'Logical'
9+
- 'Logic'
10+
- 'Operators'
11+
- 'Programming'
1212
CatalogContent:
1313
- 'learn-c-plus-plus'
1414
- 'paths/computer-science'
1515
---
1616

17-
C++ supports different types of **operators** such as arithmetic, relational, and logical operators.
17+
**Operators** are special symbols in C++ that perform specific operations on one or more operands ([variables](https://www.codecademy.com/resources/docs/cpp/variables), constants, or expressions). They are fundamental building blocks that enable programmers to manipulate data, perform calculations, make comparisons, and control program flow. Operators take operands as input and produce a result based on the operation being performed.
18+
19+
C++ operators are extensively used in various programming scenarios including mathematical calculations, conditional statements, loops, memory management, and data manipulation. They provide a concise and efficient way to express complex operations, making code more readable and maintainable. From simple arithmetic in calculators to complex logical operations in algorithms, operators form the backbone of computational logic in C++ programming.
1820

1921
## Arithmetic Operators
2022

21-
Arithmetic operators can be used to perform common mathematical operations:
23+
**Arithmetic operators** perform mathematical operations on numeric operands. These operators work with integers, floating-point numbers, and other numeric data types to execute basic mathematical calculations.
24+
25+
| Name | Symbol | Description |
26+
| -------------- | ------ | -------------------------------------------- |
27+
| Addition | `+` | Adds two operands together |
28+
| Subtraction | `-` | Subtracts the second operand from the first |
29+
| Multiplication | `*` | Multiplies two operands |
30+
| Division | `/` | Divides the first operand by the second |
31+
| Modulo | `%` | Returns the remainder after integer division |
32+
| Increment | `++` | Increases the value of the operand by 1 |
33+
| Decrement | `--` | Decreases the value of the operand by 1 |
34+
35+
### Example
2236

23-
- `+` addition
24-
- `-` subtraction
25-
- `*` multiplication
26-
- `/` division
27-
- `%` modulo (yields the remainder)
37+
The following code demonstrates the use of basic arithmetic and increment/decrement operators in C++, performing addition, subtraction, multiplication, division, modulo, pre-increment, and post-decrement on two integer variables and printing the results:
2838

2939
```cpp
30-
int x = 0;
40+
#include <iostream>
41+
using namespace std;
42+
43+
int main() {
44+
int a = 15, b = 4;
45+
46+
cout << "Addition: " << (a + b) << endl;
47+
cout << "Subtraction: " << (a - b) << endl;
48+
cout << "Multiplication: " << (a * b) << endl;
49+
cout << "Division: " << (a / b) << endl;
50+
cout << "Modulo: " << (a % b) << endl;
51+
52+
cout << "Pre-increment: " << (++a) << endl;
53+
cout << "Post-decrement: " << (b--) << endl;
54+
55+
return 0;
56+
}
57+
```
58+
59+
The output of this code will be:
3160

32-
x = 4 + 2; // x is now 6
33-
x = 4 - 2; // x is now 2
34-
x = 4 * 2; // x is now 8
35-
x = 4 / 2; // x is now 2
36-
x = 4 % 2; // x is now 0
61+
```shell
62+
Addition: 19
63+
Subtraction: 11
64+
Multiplication: 60
65+
Division: 3
66+
Modulo: 3
67+
Pre-increment: 16
68+
Post-decrement: 4
3769
```
3870

3971
## Relational Operators
4072

41-
Relational operators can be used to compare two values and return true or false depending on the comparison:
73+
**Relational operators** compare two operands and return a boolean value (`true` or `false`) based on the relationship between them. These operators are commonly used in conditional statements and loops to make decisions.
74+
75+
| Name | Symbol | Description |
76+
| ------------------------ | ------ | -------------------------------------------------------- |
77+
| Equal to | `==` | Checks if two operands are equal |
78+
| Not equal to | `!=` | Checks if two operands are not equal |
79+
| Greater than | `>` | Checks if left operand is greater than right |
80+
| Less than | `<` | Checks if left operand is less than right |
81+
| Greater than or equal to | `>=` | Checks if left operand is greater than or equal to right |
82+
| Less than or equal to | `<=` | Checks if left operand is less than or equal to right |
4283

43-
- `==` equal to
44-
- `!=` not equal to
45-
- `>` greater than
46-
- `<` less than
47-
- `>=` greater than or equal to
48-
- `<=` less than or equal to
84+
### Example
85+
86+
The following code demonstrates the use of relational operators in C++ by comparing two integer variables `x` and `y`, and printing the results of equality, inequality, and relational comparisons:
4987

5088
```cpp
51-
if (a > 10) {
52-
// ☝️ means greater than
89+
#include <iostream>
90+
using namespace std;
91+
92+
int main() {
93+
int x = 10, y = 20;
94+
95+
cout << "x == y: " << (x == y) << endl;
96+
cout << "x != y: " << (x != y) << endl;
97+
cout << "x > y: " << (x > y) << endl;
98+
cout << "x < y: " << (x < y) << endl;
99+
cout << "x >= y: " << (x >= y) << endl;
100+
cout << "x <= y: " << (x <= y) << endl;
101+
102+
return 0;
53103
}
54104
```
55105

106+
The output of this code is:
107+
108+
```shell
109+
x == y: 0
110+
x != y: 1
111+
x > y: 0
112+
x < y: 1
113+
x >= y: 0
114+
x <= y: 1
115+
```
116+
56117
## Logical Operators
57118

58-
Logical operators can be used to combine two different conditions.
119+
**Logical operators** perform logical operations on boolean operands or expressions that evaluate to boolean values. They are essential for combining multiple conditions and implementing complex decision-making logic.
59120

60-
- `&&` requires both to be true (`and`)
61-
- `||` requires either to be true (`or`)
62-
- `!` negates the result (`not`)
121+
| Name | Symbol | Description |
122+
| ----------- | ------ | ------------------------------------------------- |
123+
| Logical AND | `&&` | Returns true only if both operands are true |
124+
| Logical OR | `\|\|` | Returns true if at least one operand is true |
125+
| Logical NOT | `!` | Returns the opposite boolean value of the operand |
126+
127+
### Example
128+
129+
This code demonstrates the use of logical operators in C++ by evaluating logical AND (`&&`), OR (`||`), and NOT (`!`) operations on two boolean variables `p` and `q`, and printing the results:
130+
131+
```cpp
132+
#include <iostream>
133+
using namespace std;
134+
135+
int main() {
136+
bool p = true, q = false;
137+
138+
cout << "p && q: " << (p && q) << endl;
139+
cout << "p || q: " << (p || q) << endl;
140+
cout << "!p: " << (!p) << endl;
141+
cout << "!q: " << (!q) << endl;
142+
143+
return 0;
144+
}
145+
```
146+
147+
The output of this code is as follows:
148+
149+
```shell
150+
p && q: 0
151+
p || q: 1
152+
!p: 0
153+
!q: 1
154+
```
155+
156+
## Assignment Operators
157+
158+
**Assignment operators** assign values to variables. The basic assignment operator stores a value in a variable, while compound assignment operators perform an operation and then assign the result back to the variable.
159+
160+
| Name | Symbol | Description |
161+
| ------------------- | ------ | ------------------------------------------------------------ |
162+
| Assignment | `=` | Assigns the right operand value to left operand |
163+
| Add and assign | `+=` | Adds right operand to left operand and assigns result |
164+
| Subtract and assign | `-=` | Subtracts right operand from left operand and assigns result |
165+
| Multiply and assign | `*=` | Multiplies left operand by right operand and assigns result |
166+
| Divide and assign | `/=` | Divides left operand by right operand and assigns result |
167+
| Modulo and assign | `%=` | Performs modulo operation and assigns result |
168+
169+
### Example
170+
171+
This code demonstrates the use of compound assignment operators in C++ by performing a series of arithmetic operations (`+=`, `-=`, `*=`, `/=`) on an integer variable `num` and printing its updated value after each operation:
63172

64173
```cpp
65-
if (coffee > 0 && donut > 1) {
66-
// Code runs if both are true
174+
#include <iostream>
175+
using namespace std;
176+
177+
int main() {
178+
int num = 10;
179+
180+
cout << "Initial value: " << num << endl;
181+
182+
num += 5;
183+
cout << "After += 5: " << num << endl;
184+
185+
num -= 3;
186+
cout << "After -= 3: " << num << endl;
187+
188+
num *= 2;
189+
cout << "After *= 2: " << num << endl;
190+
191+
num /= 4;
192+
cout << "After /= 4: " << num << endl;
193+
194+
return 0;
67195
}
196+
```
197+
198+
The output generated by this code will be:
199+
200+
```shell
201+
Initial value: 10
202+
After += 5: 15
203+
After -= 3: 12
204+
After *= 2: 24
205+
After /= 4: 6
206+
```
207+
208+
## Bitwise Operators
209+
210+
**Bitwise operators** perform operations on individual bits of integer operands. They manipulate data at the binary level and are commonly used in system programming, embedded systems, and optimization techniques.
68211

69-
if (coffee > 0 || donut > 1) {
70-
// Code runs if either is true
212+
| Name | Symbol | Description |
213+
| ----------- | ------ | --------------------------------------------------------- |
214+
| Bitwise AND | `&` | Performs AND operation on each pair of corresponding bits |
215+
| Bitwise OR | `\|` | Performs OR operation on each pair of corresponding bits |
216+
| Bitwise XOR | `^` | Performs XOR operation on each pair of corresponding bits |
217+
| Bitwise NOT | `~` | Flips all bits (1 becomes 0, 0 becomes 1) |
218+
| Left shift | `<<` | Shifts bits to the left by specified positions |
219+
| Right shift | `>>` | Shifts bits to the right by specified positions |
220+
221+
### Example
222+
223+
The following code demonstrates the use of bitwise operators in C++ by performing operations like AND (`&`), OR (`|`), XOR (`^`), NOT (`~`), left shift (`<<`), and right shift (`>>`) on two integers `a` and `b`, and displaying the results of each operation:
224+
225+
```cpp
226+
#include <iostream>
227+
using namespace std;
228+
229+
int main() {
230+
int a = 12, b = 7; // 12 = 1100, 7 = 0111 in binary
231+
232+
cout << "a & b: " << (a & b) << endl; // 0100 = 4
233+
cout << "a | b: " << (a | b) << endl; // 1111 = 15
234+
cout << "a ^ b: " << (a ^ b) << endl; // 1011 = 11
235+
cout << "~a: " << (~a) << endl; // Bitwise NOT
236+
cout << "a << 2: " << (a << 2) << endl; // Left shift by 2
237+
cout << "a >> 2: " << (a >> 2) << endl; // Right shift by 2
238+
239+
return 0;
71240
}
241+
```
242+
243+
The output by this code will be:
244+
245+
```shell
246+
a & b: 4
247+
a | b: 15
248+
a ^ b: 11
249+
~a: -13
250+
a << 2: 48
251+
a >> 2: 3
252+
```
253+
254+
## Codebyte Example: Student Grade Calculator
255+
256+
This example demonstrates how different operator types work together in a practical application that calculates and categorizes student grades:
257+
258+
```codebyte/cpp
259+
#include <iostream>
260+
using namespace std;
261+
262+
int main() {
263+
// Arithmetic operators for calculations
264+
int math = 85, science = 92, english = 78;
265+
int totalMarks = math + science + english;
266+
double average = totalMarks / 3.0;
267+
268+
// Assignment operators for score adjustment
269+
int bonus = 5;
270+
average += bonus; // Add bonus points
271+
272+
// Relational and logical operators for grade determination
273+
char grade;
274+
bool passed = (average >= 60);
275+
276+
if (average >= 90 && passed) {
277+
grade = 'A';
278+
} else if (average >= 80) {
279+
grade = 'B';
280+
} else if (average >= 70) {
281+
grade = 'C';
282+
} else {
283+
grade = 'F';
284+
}
285+
286+
// Bitwise operator for status flag
287+
int status = 0;
288+
status |= (1 << 0); // Set bit 0 for "calculated"
289+
if (passed) {
290+
status |= (1 << 1); // Set bit 1 for "passed"
291+
}
292+
293+
cout << "Total Marks: " << totalMarks << endl;
294+
cout << "Average (with bonus): " << average << endl;
295+
cout << "Grade: " << grade << endl;
296+
cout << "Status: " << (passed ? "Passed" : "Failed") << endl;
72297
73-
if (!tired) {
74-
// Code runs if tired is false
298+
return 0;
75299
}
76300
```
77301
78-
> **Note:** Operator overloading is possible in C++. This means that operators can be used with custom types. For example, the `+` operator can be used to add two custom defined classes together. See [overloading](https://www.codecademy.com/resources/docs/cpp/overloading).
302+
This example showcases arithmetic operators calculating the total and average, assignment operators adding bonus points, relational and logical operators determining pass/fail status and grades, and bitwise operators managing status flags in a single comprehensive program.
303+
304+
## Frequently Asked Questions
305+
306+
### 1. What is the difference between `++i` and `i++`?
307+
308+
`++i` (pre-increment) increments the variable first and then returns the new value, while `i++` (post-increment) returns the current value first and then increments the variable.
309+
310+
### 2. Can I use the modulo operator with floating-point numbers?
311+
312+
No, the modulo operator (`%`) only works with integer types in C++. For floating-point remainder operations, use the `fmod()` function from the `<cmath>` library.
313+
314+
### 3. Why does `5 / 2` return `2` instead of `2.5`?
315+
316+
When both operands are integers, C++ performs integer division and truncates the decimal part. To get the decimal result, make at least one operand a floating-point number: `5.0 / 2` or `5 / 2.0`.
317+
318+
### 4. What happens with bitwise operators on negative numbers?
319+
320+
Bitwise operators work on the binary representation of numbers. For negative numbers, C++ uses two's complement representation, which can produce unexpected results for beginners. The bitwise NOT operator (`~`) flips all bits, including the sign bit.
321+
322+
### 5. How do logical operators handle non-boolean values?
79323
80-
Below are some other operators that are used in C++:
324+
In C++, any non-zero value is considered `true` in a boolean context, and zero is considered `false`. Logical operators can work with any data type, converting them to boolean values for evaluation.

0 commit comments

Comments
 (0)