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 861f1d9e4767737c1a05b04503d265a25d219680 Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Thu, 12 Jun 2025 14:32:12 +0530 Subject: [PATCH 3/4] [Edit] C++: Arrays --- content/cpp/concepts/arrays/arrays.md | 255 ++++++++++++++++++++++---- 1 file changed, 224 insertions(+), 31 deletions(-) diff --git a/content/cpp/concepts/arrays/arrays.md b/content/cpp/concepts/arrays/arrays.md index 8508d8e1d4b..dbccb0fa3b2 100644 --- a/content/cpp/concepts/arrays/arrays.md +++ b/content/cpp/concepts/arrays/arrays.md @@ -1,73 +1,266 @@ --- Title: 'Arrays' -Description: 'Like a vector, an array is a data structure used in C++ to store a sequential collection of elements.' +Description: 'Stores multiple values of the same data type in contiguous memory locations.' Subjects: - 'Computer Science' - - 'Game Development' + - 'Web Development' Tags: - 'Arrays' - - 'Vectors' + - 'Data Structures' + - 'Memory' + - 'Variables' CatalogContent: - 'learn-c-plus-plus' - 'paths/computer-science' --- -Like a vector, an **array** is a data structure used in C++ to store a sequential collection of elements. Unlike vectors, its size cannot be changed. +An **array** is a data structure that stores multiple values of the same data type in contiguous memory locations. Arrays allow storing and accessing a collection of elements efficiently using a single variable name with indexed positions. Instead of declaring separate variables for each value, an array provides a way to manage multiple related values as a single entity. -Being able to store multiple pieces of related information in the same structure is very useful when writing C++ programs. +Arrays are particularly useful when dealing with collections of similar data, such as storing student grades, temperature readings, or inventory items. The size of an array must be known at compile time and cannot be changed during program execution. -## Creating an Array +## Create an Array -When creating an array, two pieces of information have to be kept in mind: +### Syntax -- The type of data to be stored inside it. -- How many items it should be able to hold (its size). +```pseudo +dataType arrayName[arraySize]; +``` + +The syntax consists of the data type, followed by the array name, and the size enclosed in square brackets. The size must be a positive integer constant. + +### Example + +```cpp +#include +using namespace std; + +int main() { + // Create an array of integers + int numbers[5]; + + // Create an array of doubles + double prices[10]; + + // Create an array of characters + char letters[26]; + + return 0; +} +``` + +This example creates three arrays: `numbers` can store 5 integers, `prices` can store 10 double values, and `letters` can store 26 characters. + +## Initialize Array with Values + +### Syntax + +```pseudo +dataType arrayName[arraySize] = {value1, value2, value3, ...}; +``` -An array can be created a lot like how normal variables are created: by specifying the data type, giving it a descriptive name, and also specifying its size: +Values are enclosed in curly braces and separated by commas. The number of values cannot exceed the array size but can be less. + +### Example ```cpp -int favoriteNums[4]; +#include +using namespace std; + +int main() { + // Initialize array with specific values + int scores[5] = {85, 92, 78, 96, 88}; + + // Initialize with fewer values (remaining filled with 0) + int grades[6] = {90, 85, 77}; + + // Let compiler determine size + int ages[] = {25, 30, 35, 28, 33}; + + return 0; +} ``` -In the above code example, an array is created with a size of `4`, meaning it can hold four integers (all four elements will initially have the default `int` value of `0`). +In this example, `scores` is fully initialized, `grades` has the first three elements set with the rest defaulting to 0, and `ages` automatically sizes to 5 elements. + +## Access Array Elements -In many cases, what data needs to go in the array will not be known until after it's created, but if the contents of the array are known ahead of time, it can be initialized with custom values upfront: +Array elements are accessed using the **subscript operator** `[]` with an index number. Array indexing starts at 0, meaning the first element is at index 0, the second at index 1, and so on. + +### Example ```cpp -int favoriteNums[] = {7, 9, 15, 16}; +#include +using namespace std; + +int main() { + int numbers[5] = {10, 20, 30, 40, 50}; + + // Access and print array elements + cout << "First element: " << numbers[0] << endl; + cout << "Third element: " << numbers[2] << endl; + cout << "Last element: " << numbers[4] << endl; + + return 0; +} ``` -This array would also have a size of `4`, but it does not need to be explicitly specified when initialized this way. +This example outputs: + +```shell +First element: 10 +Third element: 30 +Last element: 50 +``` -> **Note:** Even if an array `arr` has a length of `n`, it can be accessed and modified with `arr[n+1]`, which can overwrite other variables or cause undefined behaviour. +## Update Array Elements -## Array Indices +Array elements can be modified by assigning new values to specific indices using the assignment operator. -Like vectors, each element in an array is assigned a specific index starting at zero. To access or modify an element in the array it may be referred to by its index and operated on accordingly: +### Example ```cpp -char vowels[] = {'a', 'e', 'i', 'o', 'u'}; -// indexes: 0 1 2 3 4 +#include +using namespace std; + +int main() { + int numbers[5] = {10, 20, 30, 40, 50}; + + cout << "Original array: "; + for (int i = 0; i < 5; i++) { + cout << numbers[i] << " "; + } + cout << endl; + + // Update specific elements + numbers[0] = 15; + numbers[2] = 35; + numbers[4] = 55; -std::cout << vowels[0]; -// Output: a + cout << "Updated array: "; + for (int i = 0; i < 5; i++) { + cout << numbers[i] << " "; + } + cout << endl; -vowels[0] = 'r'; + return 0; +} +``` + +This example outputs: -std::cout << vowels[0]; -// Output: r +```shell +Original array: 10 20 30 40 50 +Updated array: 15 20 35 40 55 ``` -In the case above, an array of `chars` was initialized with all the vowels, and then the first element in the array at index `0` was printed out. Then the element at index `0` was modified by being assigned a new value of `'r'`, which was then printed out. +## Example 1: Student Grade Calculator + +```cpp +#include +using namespace std; + +int main() { + // Create and initialize array of student grades + double grades[6] = {88.5, 92.0, 76.5, 85.0, 91.5, 89.0}; + double sum = 0.0; + + cout << "Student Grades: "; -Arrays in C++ have a fixed size, meaning elements cannot be added or removed once the array has been created. Only existing elements may be modified without changing the total size or shape of the structure. + // Display grades and calculate sum + for (int i = 0; i < 6; i++) { + cout << grades[i] << " "; + sum += grades[i]; + } -## Uninitialized Elements + double average = sum / 6; -Array elements that are not assigned a value when the array is created are known as uninitialized elements and should not be accessed during runtime. For example: + cout << endl; + cout << "Total: " << sum << endl; + cout << "Average: " << average << endl; + + return 0; +} +``` + +This example outputs: + +```shell +Student Grades: 88.5 92 76.5 85 91.5 89 +Total: 522.5 +Average: 87.0833 +``` + +## Example 2: Interactive Array Management ```cpp -int arr[5] = {0, 1, 2}; +#include +using namespace std; + +int main() { + const int SIZE = 5; + int numbers[SIZE]; + + // Input values from user + cout << "Enter " << SIZE << " integers:" << endl; + for (int i = 0; i < SIZE; i++) { + cout << "Element " << (i + 1) << ": "; + cin >> numbers[i]; + } + + // Display original array + cout << "\nOriginal array: "; + for (int i = 0; i < SIZE; i++) { + cout << numbers[i] << " "; + } + cout << endl; + + // Update every second element + cout << "\nUpdating every second element..." << endl; + for (int i = 1; i < SIZE; i += 2) { + numbers[i] = numbers[i] * 2; + } + + // Display updated array + cout << "Updated array: "; + for (int i = 0; i < SIZE; i++) { + cout << numbers[i] << " "; + } + cout << endl; + + // Find maximum value + int max = numbers[0]; + int maxIndex = 0; + for (int i = 1; i < SIZE; i++) { + if (numbers[i] > max) { + max = numbers[i]; + maxIndex = i; + } + } + + cout << "\nMaximum value: " << max << " at index " << maxIndex << endl; + + return 0; +} ``` -This code initializes an array of five integers in which index `3` and `4` are empty and should not be accessed during the program's runtime. +## Frequently Asked Questions + +### 1. Can array size be changed after declaration? + +No, the size of an array is fixed at compile time and cannot be modified during program execution. If dynamic sizing is needed, consider using `std::vector` instead. + +### 2. What happens if I access an array element beyond its bounds? + +Accessing elements outside the valid index range (0 to size-1) leads to **undefined behavior**, which can cause program crashes or unpredictable results. Always ensure indices are within valid bounds. + +### 3. How to find the length of an array? + +Use the `sizeof` operator: `int length = sizeof(array) / sizeof(array[0]);`. This only works for statically declared arrays, not for arrays passed as function parameters. + +### 4. Can arrays store different data types? + +No, all elements in an array must be of the same data type. To store different types, consider using structures, classes, or `std::variant` (C++17). + +### 5. How are array elements stored in memory? + +Array elements are stored in contiguous memory locations, with each element directly adjacent to the next. This provides efficient memory access and enables pointer arithmetic. From 32f39be92cd422ff85e1d35052fc360b8ff32dc7 Mon Sep 17 00:00:00 2001 From: Avdhoot Fulsundar Date: Fri, 20 Jun 2025 22:38:19 +0530 Subject: [PATCH 4/4] Changes --- content/cpp/concepts/arrays/arrays.md | 44 ++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/content/cpp/concepts/arrays/arrays.md b/content/cpp/concepts/arrays/arrays.md index dbccb0fa3b2..a136c5bbbf5 100644 --- a/content/cpp/concepts/arrays/arrays.md +++ b/content/cpp/concepts/arrays/arrays.md @@ -14,7 +14,7 @@ CatalogContent: - 'paths/computer-science' --- -An **array** is a data structure that stores multiple values of the same data type in contiguous memory locations. Arrays allow storing and accessing a collection of elements efficiently using a single variable name with indexed positions. Instead of declaring separate variables for each value, an array provides a way to manage multiple related values as a single entity. +An **array** is a data structure that stores multiple values of the same [data type](https://www.codecademy.com/resources/docs/cpp/data-types) in contiguous memory locations. Arrays allow storing and accessing a collection of elements efficiently using a single variable name with indexed positions. Instead of declaring separate variables for each value, an array provides a way to manage multiple related values as a single entity. Arrays are particularly useful when dealing with collections of similar data, such as storing student grades, temperature readings, or inventory items. The size of an array must be known at compile time and cannot be changed during program execution. @@ -30,6 +30,8 @@ The syntax consists of the data type, followed by the array name, and the size e ### Example +This example creates three arrays: `numbers` can store 5 integers, `prices` can store 10 double values, and `letters` can store 26 characters. + ```cpp #include using namespace std; @@ -48,8 +50,6 @@ int main() { } ``` -This example creates three arrays: `numbers` can store 5 integers, `prices` can store 10 double values, and `letters` can store 26 characters. - ## Initialize Array with Values ### Syntax @@ -62,6 +62,8 @@ Values are enclosed in curly braces and separated by commas. The number of value ### Example +In the following example, `scores` is fully initialized, `grades` has the first three elements set with the rest defaulting to 0, and `ages` automatically sizes to 5 elements. + ```cpp #include using namespace std; @@ -80,14 +82,14 @@ int main() { } ``` -In this example, `scores` is fully initialized, `grades` has the first three elements set with the rest defaulting to 0, and `ages` automatically sizes to 5 elements. - ## Access Array Elements Array elements are accessed using the **subscript operator** `[]` with an index number. Array indexing starts at 0, meaning the first element is at index 0, the second at index 1, and so on. ### Example +The following code initializes an array of five integers and prints the first, third, and last elements: + ```cpp #include using namespace std; @@ -104,7 +106,7 @@ int main() { } ``` -This example outputs: +The output of the above code will be: ```shell First element: 10 @@ -118,6 +120,8 @@ Array elements can be modified by assigning new values to specific indices using ### Example +The following code initializes an array of five integers, prints the original array, updates specific elements, and then prints the updated array: + ```cpp #include using namespace std; @@ -146,7 +150,7 @@ int main() { } ``` -This example outputs: +The output of the above code will be: ```shell Original array: 10 20 30 40 50 @@ -155,6 +159,8 @@ Updated array: 15 20 35 40 55 ## Example 1: Student Grade Calculator +The following code initializes an array of student grades, calculates their total and average, and prints the results: + ```cpp #include using namespace std; @@ -182,7 +188,7 @@ int main() { } ``` -This example outputs: +The output of the above example will be: ```shell Student Grades: 88.5 92 76.5 85 91.5 89 @@ -192,6 +198,8 @@ Average: 87.0833 ## Example 2: Interactive Array Management +The following code takes 5 integers from the user, doubles every second element in the array, displays the original and updated arrays, and finds and prints the maximum value along with its index: + ```cpp #include using namespace std; @@ -243,6 +251,26 @@ int main() { } ``` +The output of the above code will be: + +```shell +Enter 5 integers: +Element 1: 1 +Element 2: 2 +Element 3: 5 +Element 4: 5 +Element 5: 2 + +Original array: 1 2 5 5 2 + +Updating every second element... +Updated array: 1 4 5 10 2 + +Maximum value: 10 at index 3 +``` + +> **Note:** The output of this program will vary depending on the user’s input values. + ## Frequently Asked Questions ### 1. Can array size be changed after declaration?