From d0dd9bd3c5a7c5188d3f803a5fd3b6f051a800d3 Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Wed, 21 May 2025 16:08:19 +0530 Subject: [PATCH 1/4] [Edit] SQL: DATEDIFF() --- .../concepts/dates/terms/datediff/datediff.md | 191 ++++++++++++++---- 1 file changed, 154 insertions(+), 37 deletions(-) diff --git a/content/sql/concepts/dates/terms/datediff/datediff.md b/content/sql/concepts/dates/terms/datediff/datediff.md index 66f952e9b2e..9426633b080 100644 --- a/content/sql/concepts/dates/terms/datediff/datediff.md +++ b/content/sql/concepts/dates/terms/datediff/datediff.md @@ -1,72 +1,189 @@ --- Title: 'DATEDIFF()' -Description: 'Calculates and returns the difference between two date values. Available in SQL Server and MySQL.' +Description: 'Calculates the difference between two date or timestamp values and returns the result as an integer.' Subjects: - - 'Data Science' + - 'Computer Science' + - 'Web Development' Tags: - 'Database' - 'Date' - - 'Queries' - - 'MySQL' - - 'SQL Server' + - 'Functions' + - 'SQL' CatalogContent: - 'learn-sql' - 'paths/analyze-data-with-sql' - - 'paths/design-databases-with-postgresql' --- -**`DATEDIFF()`** is a function found in SQL Server and MySQL that calculates and returns the difference between two date values. +The **`DATEDIFF()`** function calculates the difference between two date or timestamp values and returns the result as an integer in a specified unit of time. This powerful function allows developers and analysts to easily measure time intervals between dates, which is essential for reporting, data analysis, and application development. -## SQL Server Syntax +`DATEDIFF()` serves as a cornerstone for date-based calculations in SQL Server, enabling users to perform operations like calculating ages, measuring durations of events, determining time elapsed between transactions, and creating date-based business metrics. Its versatility makes it invaluable for virtually any application that deals with temporal data. + +## Syntax ```pseudo -DATEDIFF(datePart, date1, date2) +DATEDIFF(interval, date1, date2) ``` -The `DATEDIFF()` function in SQL Server has three required parameters: +**Parameters:** + +- `interval`: The time unit in which the difference will be calculated. Valid values include: + - `year`, `yy`, `yyyy`: Years + - `quarter`, `qq`, `q`: Quarters + - `month`, `mm`, `m`: Months + - `dayofyear`, `dy`, `y`: Day of the year + - `day`, `dd`, `d`: Days + - `week`, `wk`, `ww`: Weeks + - `hour`, `hh`: Hours + - `minute`, `mi`, `n`: Minutes + - `second`, `ss`, `s`: Seconds + - `millisecond`, `ms`: Milliseconds + - `microsecond`, `mcs`: Microseconds + - `nanosecond`, `ns`: Nanoseconds +- `date1`: The start date for the calculation. Can be a date, datetime, datetime2, smalldatetime, or time data type, or an expression that resolves to one of these types. +- `date2`: The end date for the calculation. Can be a date, datetime, datetime2, smalldatetime, or time data type, or an expression that resolves to one of these types. + +**Return value:** -- `datePart` is the part of the date to return. It can be one of the following formats: - - Year: `year`, `yyyy`, `yy` - - Quarter: `quarter`, `qq`, `q` - - Week: `week`, `ww`, `wk` - - Weekday: `weekday`, `dw`, `w` - - Second: `second`, `ss`, `s` - - Month: `month`, `mm`, `m` - - Minute: `minute`, `mi`, `n` - - Millisecond: `millisecond`, `ms` - - Hour: `hour`, `hh` - - Day of Year: `dayofyear` - - Day: `day`, `dy`, `y` -- `date1` and `date2` are the dates to compare. It can be in several formats, one being the `yyyy/mm/dd` format. +The `DATEDIFF()` function returns an integer representing the number of time units (specified by the interval parameter) between date1 and date2. -### Example 1 +## Example 1: Basic Date Difference Calculation -The following example calculates the difference in months between `2020/05/18` and `2022/05/18`: +This example demonstrates how to calculate the difference between two dates in various time intervals: ```sql -SELECT DATEDIFF(month, '2020/05/18', '2022/05/18'); /* Output: 24 */ +-- Calculate difference between two dates in years, months, and days +SELECT + DATEDIFF(year, '2020-01-15', '2023-09-20') AS YearDiff, + DATEDIFF(month, '2020-01-15', '2023-09-20') AS MonthDiff, + DATEDIFF(day, '2020-01-15', '2023-09-20') AS DayDiff; ``` -### Example 2 +Output produced by this code will be: + +| YearDiff | MonthDiff | DayDiff | +| -------- | --------- | ------- | +| 3 | 44 | 1344 | + +This example calculates the difference between January 15, 2020, and September 20, 2023, in years, months, and days. The results show there are 3 years, 44 months, or 1344 days between these dates. + +## Example 2: Calculating Age in Years -The following example returns the difference in seconds between `2021/09/30 08:22:04` and `2021/09/30 08:25:06`: +This example demonstrates how to use `DATEDIFF()` to calculate a person's age in years from their birthdate. ```sql -SELECT DATEDIFF(second, '2021/09/30 08:22:04', '2021/09/30 08:25:06'); /* Output: 182 */ +-- Create a sample table with employee data +CREATE TABLE Employees ( + EmployeeID INT PRIMARY KEY, + FirstName VARCHAR(50), + LastName VARCHAR(50), + BirthDate DATE, + HireDate DATE +); + +-- Insert sample data +INSERT INTO Employees (EmployeeID, FirstName, LastName, BirthDate, HireDate) +VALUES + (1, 'John', 'Smith', '1985-06-15', '2010-03-20'), + (2, 'Sarah', 'Johnson', '1992-11-30', '2015-07-10'), + (3, 'Michael', 'Brown', '1978-02-23', '2005-09-15'); + +-- Calculate ages as of current date +SELECT + EmployeeID, + FirstName + ' ' + LastName AS EmployeeName, + BirthDate, + DATEDIFF(year, BirthDate, GETDATE()) AS Age +FROM + Employees +ORDER BY + Age DESC; ``` -## MySQL Syntax +The output generated by this code will be: -MySQL only requires two date parameters in the `DATEDIFF()` function and will return the number of days between `date1` and `date2`. +| EmployeeID | EmployeeName | BirthDate | Age | +| ---------- | ------------- | ---------- | --- | +| 3 | Michael Brown | 1978-02-23 | 47 | +| 1 | John Smith | 1985-06-15 | 39 | +| 2 | Sarah Johnson | 1992-11-30 | 32 | -```pseudo -DATEDIFF(date1, date2) -``` +This example shows how to calculate an employee's age by finding the difference in years between their birthdate and the current date. Note that this calculation provides the raw year difference and doesn't account for whether the birthday has occurred yet in the current year. -### Example +## Example 3: Business Metrics with `DATEDIFF()` -The following example returns the difference in days between `2019-07-05` and `2018-12-24`: +This example demonstrates how to use `DATEDIFF()` for business reporting metrics, such as calculating order processing times and identifying delayed shipments. ```sql -SELECT DATEDIFF("2019-07-05", "2018-12-24"); /* Output: 193 */ +-- Create sample orders table +CREATE TABLE Orders ( + OrderID INT PRIMARY KEY, + CustomerID INT, + OrderDate DATETIME, + ShipDate DATETIME, + DeliveryDate DATETIME +); + +-- Insert sample data +INSERT INTO Orders (OrderID, CustomerID, OrderDate, ShipDate, DeliveryDate) +VALUES + (1001, 101, '2023-01-10 09:30:00', '2023-01-11 14:15:00', '2023-01-15 11:20:00'), + (1002, 102, '2023-01-12 13:45:00', '2023-01-13 10:30:00', '2023-01-14 16:45:00'), + (1003, 103, '2023-01-15 11:20:00', '2023-01-18 09:45:00', '2023-01-22 13:10:00'), + (1004, 104, '2023-01-16 14:55:00', '2023-01-17 16:30:00', '2023-01-21 09:30:00'), + (1005, 105, '2023-01-18 10:15:00', NULL, NULL); + +-- Calculate processing, shipping, and total handling times +SELECT + OrderID, + OrderDate, + ShipDate, + DeliveryDate, + -- Processing time (from order to shipment) + DATEDIFF(hour, OrderDate, ShipDate) AS ProcessingHours, + -- Shipping time (from shipment to delivery) + DATEDIFF(day, ShipDate, DeliveryDate) AS ShippingDays, + -- Total time (from order to delivery) + DATEDIFF(day, OrderDate, DeliveryDate) AS TotalDays, + -- Identify delayed shipments (processing > 24 hours) + CASE + WHEN DATEDIFF(hour, OrderDate, ShipDate) > 24 THEN 'Delayed' + ELSE 'On Time' + END AS ShipmentStatus +FROM + Orders +WHERE + ShipDate IS NOT NULL; ``` + +The output of this code will be: + +| OrderID | OrderDate | ShipDate | DeliveryDate | ProcessingHours | ShippingDays | TotalDays | ShipmentStatus | +| ------- | ------------------- | ------------------- | ------------------- | --------------- | ------------ | --------- | -------------- | +| 1001 | 2023-01-10 09:30:00 | 2023-01-11 14:15:00 | 2023-01-15 11:20:00 | 29 | 4 | 5 | Delayed | +| 1002 | 2023-01-12 13:45:00 | 2023-01-13 10:30:00 | 2023-01-14 16:45:00 | 21 | 1 | 2 | On Time | +| 1003 | 2023-01-15 11:20:00 | 2023-01-18 09:45:00 | 2023-01-22 13:10:00 | 70 | 4 | 7 | Delayed | +| 1004 | 2023-01-16 14:55:00 | 2023-01-17 16:30:00 | 2023-01-21 09:30:00 | 26 | 4 | 5 | Delayed | + +This example demonstrates how `DATEDIFF()` can be used to calculate important business metrics for order processing. The query calculates the processing time in hours, shipping time in days, and total handling time in days. It also identifies delayed shipments based on processing times exceeding 24 hours. + +## Frequently Asked Questions + +### 1. How to calculate date difference between two dates in SQL? + +In SQL Server, use the `DATEDIFF()` function with an appropriate interval parameter like day, month, or year. For example, `DATEDIFF(day, '2023-01-01', '2023-01-15')` will return 14 days. + +### 2. Does `DATEDIFF()` include both the start and end dates in its calculation? + +`DATEDIFF()` counts the number of interval boundaries crossed between the two dates. For example, when using 'day', it counts the number of midnight boundaries crossed, not the full 24-hour periods. + +### 3. Why does `DATEDIFF(year, '2022-12-31', '2023-01-01')` return 1 even though it's just one day apart? + +Because `DATEDIFF()` counts calendar boundaries, not complete intervals. Since the dates span across a year boundary, it returns 1 year, even though the difference is only one day. + +### 4. Does `DATEDIFF()` take time zones into account? + +No, SQL Server's `DATEDIFF()` does not account for time zones or daylight saving time transitions. All calculations are done in the server's local time zone. + +### 5. Can I use `DATEDIFF()` with time-only values? + +Yes, you can use time data types with `DATEDIFF()`, but only with time-related intervals like second, minute, and hour. Using day or larger intervals with time-only values will always return 0. From 9f5c19b395cbdcf9e0abd067a634bc9778ddb33c Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Wed, 21 May 2025 16:09:54 +0530 Subject: [PATCH 2/4] Update datediff.md --- .../concepts/dates/terms/datediff/datediff.md | 191 ++++-------------- 1 file changed, 37 insertions(+), 154 deletions(-) diff --git a/content/sql/concepts/dates/terms/datediff/datediff.md b/content/sql/concepts/dates/terms/datediff/datediff.md index 9426633b080..66f952e9b2e 100644 --- a/content/sql/concepts/dates/terms/datediff/datediff.md +++ b/content/sql/concepts/dates/terms/datediff/datediff.md @@ -1,189 +1,72 @@ --- Title: 'DATEDIFF()' -Description: 'Calculates the difference between two date or timestamp values and returns the result as an integer.' +Description: 'Calculates and returns the difference between two date values. Available in SQL Server and MySQL.' Subjects: - - 'Computer Science' - - 'Web Development' + - 'Data Science' Tags: - 'Database' - 'Date' - - 'Functions' - - 'SQL' + - 'Queries' + - 'MySQL' + - 'SQL Server' CatalogContent: - 'learn-sql' - 'paths/analyze-data-with-sql' + - 'paths/design-databases-with-postgresql' --- -The **`DATEDIFF()`** function calculates the difference between two date or timestamp values and returns the result as an integer in a specified unit of time. This powerful function allows developers and analysts to easily measure time intervals between dates, which is essential for reporting, data analysis, and application development. +**`DATEDIFF()`** is a function found in SQL Server and MySQL that calculates and returns the difference between two date values. -`DATEDIFF()` serves as a cornerstone for date-based calculations in SQL Server, enabling users to perform operations like calculating ages, measuring durations of events, determining time elapsed between transactions, and creating date-based business metrics. Its versatility makes it invaluable for virtually any application that deals with temporal data. - -## Syntax +## SQL Server Syntax ```pseudo -DATEDIFF(interval, date1, date2) +DATEDIFF(datePart, date1, date2) ``` -**Parameters:** - -- `interval`: The time unit in which the difference will be calculated. Valid values include: - - `year`, `yy`, `yyyy`: Years - - `quarter`, `qq`, `q`: Quarters - - `month`, `mm`, `m`: Months - - `dayofyear`, `dy`, `y`: Day of the year - - `day`, `dd`, `d`: Days - - `week`, `wk`, `ww`: Weeks - - `hour`, `hh`: Hours - - `minute`, `mi`, `n`: Minutes - - `second`, `ss`, `s`: Seconds - - `millisecond`, `ms`: Milliseconds - - `microsecond`, `mcs`: Microseconds - - `nanosecond`, `ns`: Nanoseconds -- `date1`: The start date for the calculation. Can be a date, datetime, datetime2, smalldatetime, or time data type, or an expression that resolves to one of these types. -- `date2`: The end date for the calculation. Can be a date, datetime, datetime2, smalldatetime, or time data type, or an expression that resolves to one of these types. - -**Return value:** +The `DATEDIFF()` function in SQL Server has three required parameters: -The `DATEDIFF()` function returns an integer representing the number of time units (specified by the interval parameter) between date1 and date2. +- `datePart` is the part of the date to return. It can be one of the following formats: + - Year: `year`, `yyyy`, `yy` + - Quarter: `quarter`, `qq`, `q` + - Week: `week`, `ww`, `wk` + - Weekday: `weekday`, `dw`, `w` + - Second: `second`, `ss`, `s` + - Month: `month`, `mm`, `m` + - Minute: `minute`, `mi`, `n` + - Millisecond: `millisecond`, `ms` + - Hour: `hour`, `hh` + - Day of Year: `dayofyear` + - Day: `day`, `dy`, `y` +- `date1` and `date2` are the dates to compare. It can be in several formats, one being the `yyyy/mm/dd` format. -## Example 1: Basic Date Difference Calculation +### Example 1 -This example demonstrates how to calculate the difference between two dates in various time intervals: +The following example calculates the difference in months between `2020/05/18` and `2022/05/18`: ```sql --- Calculate difference between two dates in years, months, and days -SELECT - DATEDIFF(year, '2020-01-15', '2023-09-20') AS YearDiff, - DATEDIFF(month, '2020-01-15', '2023-09-20') AS MonthDiff, - DATEDIFF(day, '2020-01-15', '2023-09-20') AS DayDiff; +SELECT DATEDIFF(month, '2020/05/18', '2022/05/18'); /* Output: 24 */ ``` -Output produced by this code will be: - -| YearDiff | MonthDiff | DayDiff | -| -------- | --------- | ------- | -| 3 | 44 | 1344 | - -This example calculates the difference between January 15, 2020, and September 20, 2023, in years, months, and days. The results show there are 3 years, 44 months, or 1344 days between these dates. - -## Example 2: Calculating Age in Years +### Example 2 -This example demonstrates how to use `DATEDIFF()` to calculate a person's age in years from their birthdate. +The following example returns the difference in seconds between `2021/09/30 08:22:04` and `2021/09/30 08:25:06`: ```sql --- Create a sample table with employee data -CREATE TABLE Employees ( - EmployeeID INT PRIMARY KEY, - FirstName VARCHAR(50), - LastName VARCHAR(50), - BirthDate DATE, - HireDate DATE -); - --- Insert sample data -INSERT INTO Employees (EmployeeID, FirstName, LastName, BirthDate, HireDate) -VALUES - (1, 'John', 'Smith', '1985-06-15', '2010-03-20'), - (2, 'Sarah', 'Johnson', '1992-11-30', '2015-07-10'), - (3, 'Michael', 'Brown', '1978-02-23', '2005-09-15'); - --- Calculate ages as of current date -SELECT - EmployeeID, - FirstName + ' ' + LastName AS EmployeeName, - BirthDate, - DATEDIFF(year, BirthDate, GETDATE()) AS Age -FROM - Employees -ORDER BY - Age DESC; +SELECT DATEDIFF(second, '2021/09/30 08:22:04', '2021/09/30 08:25:06'); /* Output: 182 */ ``` -The output generated by this code will be: +## MySQL Syntax -| EmployeeID | EmployeeName | BirthDate | Age | -| ---------- | ------------- | ---------- | --- | -| 3 | Michael Brown | 1978-02-23 | 47 | -| 1 | John Smith | 1985-06-15 | 39 | -| 2 | Sarah Johnson | 1992-11-30 | 32 | +MySQL only requires two date parameters in the `DATEDIFF()` function and will return the number of days between `date1` and `date2`. -This example shows how to calculate an employee's age by finding the difference in years between their birthdate and the current date. Note that this calculation provides the raw year difference and doesn't account for whether the birthday has occurred yet in the current year. +```pseudo +DATEDIFF(date1, date2) +``` -## Example 3: Business Metrics with `DATEDIFF()` +### Example -This example demonstrates how to use `DATEDIFF()` for business reporting metrics, such as calculating order processing times and identifying delayed shipments. +The following example returns the difference in days between `2019-07-05` and `2018-12-24`: ```sql --- Create sample orders table -CREATE TABLE Orders ( - OrderID INT PRIMARY KEY, - CustomerID INT, - OrderDate DATETIME, - ShipDate DATETIME, - DeliveryDate DATETIME -); - --- Insert sample data -INSERT INTO Orders (OrderID, CustomerID, OrderDate, ShipDate, DeliveryDate) -VALUES - (1001, 101, '2023-01-10 09:30:00', '2023-01-11 14:15:00', '2023-01-15 11:20:00'), - (1002, 102, '2023-01-12 13:45:00', '2023-01-13 10:30:00', '2023-01-14 16:45:00'), - (1003, 103, '2023-01-15 11:20:00', '2023-01-18 09:45:00', '2023-01-22 13:10:00'), - (1004, 104, '2023-01-16 14:55:00', '2023-01-17 16:30:00', '2023-01-21 09:30:00'), - (1005, 105, '2023-01-18 10:15:00', NULL, NULL); - --- Calculate processing, shipping, and total handling times -SELECT - OrderID, - OrderDate, - ShipDate, - DeliveryDate, - -- Processing time (from order to shipment) - DATEDIFF(hour, OrderDate, ShipDate) AS ProcessingHours, - -- Shipping time (from shipment to delivery) - DATEDIFF(day, ShipDate, DeliveryDate) AS ShippingDays, - -- Total time (from order to delivery) - DATEDIFF(day, OrderDate, DeliveryDate) AS TotalDays, - -- Identify delayed shipments (processing > 24 hours) - CASE - WHEN DATEDIFF(hour, OrderDate, ShipDate) > 24 THEN 'Delayed' - ELSE 'On Time' - END AS ShipmentStatus -FROM - Orders -WHERE - ShipDate IS NOT NULL; +SELECT DATEDIFF("2019-07-05", "2018-12-24"); /* Output: 193 */ ``` - -The output of this code will be: - -| OrderID | OrderDate | ShipDate | DeliveryDate | ProcessingHours | ShippingDays | TotalDays | ShipmentStatus | -| ------- | ------------------- | ------------------- | ------------------- | --------------- | ------------ | --------- | -------------- | -| 1001 | 2023-01-10 09:30:00 | 2023-01-11 14:15:00 | 2023-01-15 11:20:00 | 29 | 4 | 5 | Delayed | -| 1002 | 2023-01-12 13:45:00 | 2023-01-13 10:30:00 | 2023-01-14 16:45:00 | 21 | 1 | 2 | On Time | -| 1003 | 2023-01-15 11:20:00 | 2023-01-18 09:45:00 | 2023-01-22 13:10:00 | 70 | 4 | 7 | Delayed | -| 1004 | 2023-01-16 14:55:00 | 2023-01-17 16:30:00 | 2023-01-21 09:30:00 | 26 | 4 | 5 | Delayed | - -This example demonstrates how `DATEDIFF()` can be used to calculate important business metrics for order processing. The query calculates the processing time in hours, shipping time in days, and total handling time in days. It also identifies delayed shipments based on processing times exceeding 24 hours. - -## Frequently Asked Questions - -### 1. How to calculate date difference between two dates in SQL? - -In SQL Server, use the `DATEDIFF()` function with an appropriate interval parameter like day, month, or year. For example, `DATEDIFF(day, '2023-01-01', '2023-01-15')` will return 14 days. - -### 2. Does `DATEDIFF()` include both the start and end dates in its calculation? - -`DATEDIFF()` counts the number of interval boundaries crossed between the two dates. For example, when using 'day', it counts the number of midnight boundaries crossed, not the full 24-hour periods. - -### 3. Why does `DATEDIFF(year, '2022-12-31', '2023-01-01')` return 1 even though it's just one day apart? - -Because `DATEDIFF()` counts calendar boundaries, not complete intervals. Since the dates span across a year boundary, it returns 1 year, even though the difference is only one day. - -### 4. Does `DATEDIFF()` take time zones into account? - -No, SQL Server's `DATEDIFF()` does not account for time zones or daylight saving time transitions. All calculations are done in the server's local time zone. - -### 5. Can I use `DATEDIFF()` with time-only values? - -Yes, you can use time data types with `DATEDIFF()`, but only with time-related intervals like second, minute, and hour. Using day or larger intervals with time-only values will always return 0. From f2911f79ffcb79ed188b684ea017d44f0e0a81a2 Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Fri, 13 Jun 2025 19:02:08 +0530 Subject: [PATCH 3/4] [Edit] C++: Operators --- content/cpp/concepts/operators/operators.md | 312 +++++++++++++++++--- 1 file changed, 273 insertions(+), 39 deletions(-) diff --git a/content/cpp/concepts/operators/operators.md b/content/cpp/concepts/operators/operators.md index 162b20742ea..432b4145af2 100644 --- a/content/cpp/concepts/operators/operators.md +++ b/content/cpp/concepts/operators/operators.md @@ -1,80 +1,314 @@ --- Title: 'Operators' -Description: 'C++ supports different types of operators such as arithmetic, relational, and logical operators.' +Description: 'Perform operations on operands to manipulate data, make calculations, and control program flow in C++ programming.' Subjects: - 'Computer Science' - - 'Game Development' + - 'Web Development' Tags: - - 'Operators' - 'Arithmetic' - - 'Comparison' - - 'Logical' + - 'Logic' + - 'Operators' + - 'Programming' CatalogContent: - 'learn-c-plus-plus' - 'paths/computer-science' --- -C++ supports different types of **operators** such as arithmetic, relational, and logical operators. +**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. + +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. ## Arithmetic Operators -Arithmetic operators can be used to perform common mathematical operations: +**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. -- `+` addition -- `-` subtraction -- `*` multiplication -- `/` division -- `%` modulo (yields the remainder) +| Name | Symbol | Description | +| -------------- | ------ | -------------------------------------------- | +| Addition | `+` | Adds two operands together | +| Subtraction | `-` | Subtracts the second operand from the first | +| Multiplication | `*` | Multiplies two operands | +| Division | `/` | Divides the first operand by the second | +| Modulo | `%` | Returns the remainder after integer division | +| Increment | `++` | Increases the value of the operand by 1 | +| Decrement | `--` | Decreases the value of the operand by 1 | + +### Example ```cpp -int x = 0; +#include +using namespace std; + +int main() { + int a = 15, b = 4; -x = 4 + 2; // x is now 6 -x = 4 - 2; // x is now 2 -x = 4 * 2; // x is now 8 -x = 4 / 2; // x is now 2 -x = 4 % 2; // x is now 0 + cout << "Addition: " << (a + b) << endl; + cout << "Subtraction: " << (a - b) << endl; + cout << "Multiplication: " << (a * b) << endl; + cout << "Division: " << (a / b) << endl; + cout << "Modulo: " << (a % b) << endl; + + cout << "Pre-increment: " << (++a) << endl; + cout << "Post-decrement: " << (b--) << endl; + + return 0; +} +``` + +Output of this code will be: + +```shell +Addition: 19 +Subtraction: 11 +Multiplication: 60 +Division: 3 +Modulo: 3 +Pre-increment: 16 +Post-decrement: 4 ``` ## Relational Operators -Relational operators can be used to compare two values and return true or false depending on the comparison: +**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. + +| Name | Symbol | Description | +| ------------------------ | ------ | -------------------------------------------------------- | +| Equal to | `==` | Checks if two operands are equal | +| Not equal to | `!=` | Checks if two operands are not equal | +| Greater than | `>` | Checks if left operand is greater than right | +| Less than | `<` | Checks if left operand is less than right | +| Greater than or equal to | `>=` | Checks if left operand is greater than or equal to right | +| Less than or equal to | `<=` | Checks if left operand is less than or equal to right | -- `==` equal to -- `!=` not equal to -- `>` greater than -- `<` less than -- `>=` greater than or equal to -- `<=` less than or equal to +### Example ```cpp -if (a > 10) { - // ☝️ means greater than +#include +using namespace std; + +int main() { + int x = 10, y = 20; + + cout << "x == y: " << (x == y) << endl; + cout << "x != y: " << (x != y) << endl; + cout << "x > y: " << (x > y) << endl; + cout << "x < y: " << (x < y) << endl; + cout << "x >= y: " << (x >= y) << endl; + cout << "x <= y: " << (x <= y) << endl; + + return 0; } ``` +The output of this code is: + +```shell +x == y: 0 +x != y: 1 +x > y: 0 +x < y: 1 +x >= y: 0 +x <= y: 1 +``` + ## Logical Operators -Logical operators can be used to combine two different conditions. +**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. + +| Name | Symbol | Description | +| ----------- | ------ | ------------------------------------------------- | +| Logical AND | `&&` | Returns true only if both operands are true | +| Logical OR | `\|\|` | Returns true if at least one operand is true | +| Logical NOT | `!` | Returns the opposite boolean value of the operand | -- `&&` requires both to be true (`and`) -- `||` requires either to be true (`or`) -- `!` negates the result (`not`) +### Example ```cpp -if (coffee > 0 && donut > 1) { - // Code runs if both are true +#include +using namespace std; + +int main() { + bool p = true, q = false; + + cout << "p && q: " << (p && q) << endl; + cout << "p || q: " << (p || q) << endl; + cout << "!p: " << (!p) << endl; + cout << "!q: " << (!q) << endl; + + return 0; } +``` + +The output of this code is as follows: + +```shell +p && q: 0 +p || q: 1 +!p: 0 +!q: 1 +``` + +## Assignment Operators + +**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. + +| Name | Symbol | Description | +| ------------------- | ------ | ------------------------------------------------------------ | +| Assignment | `=` | Assigns the right operand value to left operand | +| Add and assign | `+=` | Adds right operand to left operand and assigns result | +| Subtract and assign | `-=` | Subtracts right operand from left operand and assigns result | +| Multiply and assign | `*=` | Multiplies left operand by right operand and assigns result | +| Divide and assign | `/=` | Divides left operand by right operand and assigns result | +| Modulo and assign | `%=` | Performs modulo operation and assigns result | + +### Example + +```cpp +#include +using namespace std; + +int main() { + int num = 10; + + cout << "Initial value: " << num << endl; + + num += 5; + cout << "After += 5: " << num << endl; + + num -= 3; + cout << "After -= 3: " << num << endl; + + num *= 2; + cout << "After *= 2: " << num << endl; + + num /= 4; + cout << "After /= 4: " << num << endl; -if (coffee > 0 || donut > 1) { - // Code runs if either is true + return 0; } +``` + +The output generated by this code will be: + +```shell +Initial value: 10 +After += 5: 15 +After -= 3: 12 +After *= 2: 24 +After /= 4: 6 +``` + +## Bitwise Operators + +**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. + +| Name | Symbol | Description | +| ----------- | ------ | --------------------------------------------------------- | +| Bitwise AND | `&` | Performs AND operation on each pair of corresponding bits | +| Bitwise OR | `\|` | Performs OR operation on each pair of corresponding bits | +| Bitwise XOR | `^` | Performs XOR operation on each pair of corresponding bits | +| Bitwise NOT | `~` | Flips all bits (1 becomes 0, 0 becomes 1) | +| Left shift | `<<` | Shifts bits to the left by specified positions | +| Right shift | `>>` | Shifts bits to the right by specified positions | + +### Example + +```cpp +#include +using namespace std; -if (!tired) { - // Code runs if tired is false +int main() { + int a = 12, b = 7; // 12 = 1100, 7 = 0111 in binary + + cout << "a & b: " << (a & b) << endl; // 0100 = 4 + cout << "a | b: " << (a | b) << endl; // 1111 = 15 + cout << "a ^ b: " << (a ^ b) << endl; // 1011 = 11 + cout << "~a: " << (~a) << endl; // Bitwise NOT + cout << "a << 2: " << (a << 2) << endl; // Left shift by 2 + cout << "a >> 2: " << (a >> 2) << endl; // Right shift by 2 + + return 0; } ``` -> **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). +The output by this code will be: + +```shell +a & b: 4 +a | b: 15 +a ^ b: 11 +~a: -13 +a << 2: 48 +a >> 2: 3 +``` + +## Codebyte Example: Student Grade Calculator + +This example demonstrates how different operator types work together in a practical application that calculates and categorizes student grades: + +```codebyte/cpp +#include +using namespace std; + +int main() { + // Arithmetic operators for calculations + int math = 85, science = 92, english = 78; + int totalMarks = math + science + english; + double average = totalMarks / 3.0; + + // Assignment operators for score adjustment + int bonus = 5; + average += bonus; // Add bonus points + + // Relational and logical operators for grade determination + char grade; + bool passed = (average >= 60); + + if (average >= 90 && passed) { + grade = 'A'; + } else if (average >= 80) { + grade = 'B'; + } else if (average >= 70) { + grade = 'C'; + } else { + grade = 'F'; + } + + // Bitwise operator for status flag + int status = 0; + status |= (1 << 0); // Set bit 0 for "calculated" + if (passed) { + status |= (1 << 1); // Set bit 1 for "passed" + } + + cout << "Total Marks: " << totalMarks << endl; + cout << "Average (with bonus): " << average << endl; + cout << "Grade: " << grade << endl; + cout << "Status: " << (passed ? "Passed" : "Failed") << endl; + + return 0; +} +``` + +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. + +## Frequently Asked Questions + +### 1. What is the difference between `++i` and `i++`? + +`++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. + +### 2. Can I use the modulo operator with floating-point numbers? + +No, the modulo operator (`%`) only works with integer types in C++. For floating-point remainder operations, use the `fmod()` function from the `` library. + +### 3. Why does `5 / 2` return `2` instead of `2.5`? + +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`. + +### 4. What happens with bitwise operators on negative numbers? + +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. + +### 5. How do logical operators handle non-boolean values? -Below are some other operators that are used in C++: +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. From f069a2f87ef268a9cf18b08fc9e9727d941dd4e4 Mon Sep 17 00:00:00 2001 From: Avdhoot Fulsundar Date: Fri, 20 Jun 2025 23:17:33 +0530 Subject: [PATCH 4/4] Changes --- content/cpp/concepts/operators/operators.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/content/cpp/concepts/operators/operators.md b/content/cpp/concepts/operators/operators.md index 432b4145af2..d1128489242 100644 --- a/content/cpp/concepts/operators/operators.md +++ b/content/cpp/concepts/operators/operators.md @@ -34,6 +34,8 @@ C++ operators are extensively used in various programming scenarios including ma ### Example +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: + ```cpp #include using namespace std; @@ -54,7 +56,7 @@ int main() { } ``` -Output of this code will be: +The output of this code will be: ```shell Addition: 19 @@ -81,6 +83,8 @@ Post-decrement: 4 ### Example +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: + ```cpp #include using namespace std; @@ -122,6 +126,8 @@ x <= y: 1 ### Example +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: + ```cpp #include using namespace std; @@ -162,6 +168,8 @@ p || q: 1 ### Example +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: + ```cpp #include using namespace std; @@ -212,6 +220,8 @@ After /= 4: 6 ### Example +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: + ```cpp #include using namespace std;