An array is a collection of variables of the same type stored contiguously in memory.
One-dimensional array is like a list of elements.
All elements have the same data type.
Arrays help to store multiple values in a single variable, instead of creating many separate variables.
Analogy: Think of an array as a row of boxes, where each box has a number (index) and stores a value.
Declaration of One-Dimensional Arrays
Syntax:
data_type→ type of elements (int, float, char, etc.)array_name→ name of the arraysize→ number of elements
Examples:
Important Notes:
Array index starts from 0 and goes to
size-1.Size must be a positive integer.
All elements are of the same data type.
Accessing Elements of an Array
Access elements using index number in square brackets
[ ].
Syntax:
Example:
Explanation:
marks[0]→ first elementmarks[4]→ fifth elementArrays are zero-indexed
Modifying Elements
Examples of One-Dimensional Arrays
Example 1: Initialize and Print All Elements
Output: 1 2 3 4 5
Example 2: Input Elements from User
Example 3: Sum of Array Elements
Example 4: Find Maximum Element
Example 5: Find Minimum Element
Example 6: Average of Array Elements
Example 7: Reverse an Array
Output: 5 4 3 2 1
Example 8: Count Positive Numbers
Example 9: Check if Array Contains a Value
Example 10: Copy Array to Another Array
Example 11: Multiply Each Element by 2
Example 12: Print Even Elements
Output: 2 4 6
Example 13: Print Odd Elements
Output: 1 3 5
Example 14: Sum of Even and Odd Separately
Output: Even sum = 6, Odd sum = 9
Example 15: Shift Elements Right
Output: Array becomes 5,1,2,3,4
Example 16: Shift Elements Left
Output: Array becomes 2,3,4,5,1
Example 17: Merge Two Arrays
Example 18: Find Second Largest Element
Example 19: Count Frequency of a Value
Example 20: Remove Duplicate Elements
Array becomes: 1,2,3
Extra Details About One-Dimensional Arrays
Arrays are zero-indexed
Size must be known at compile time in traditional C++ arrays
Use loops to process arrays efficiently
Arrays can be passed to functions (by value or reference)
Arrays can store integers, floats, doubles, chars, strings
For dynamic size, use vectors instead of arrays
Best Practices
Always initialize arrays
Use loops for processing, not manual access
Avoid out-of-bounds access
Prefer constants for array size to make code maintainable
Use functions for repetitive array tasks (sum, max, min, search)