1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M4 1d Arrays
45% OFFBLACK FRIDAY SALE
Sale ends in
02Days
22Hrs
13Mins
15Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M4 1d Arrays

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

02Days
22Hrs
13Mins
15Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Arrays

Overview

If you need to store the scores of 1,000 players in a video game, creating 1,000 individual variables (int p1, p2...) is impossible. An Array solves this by allocating a single, massive block of contiguous (side-by-side) memory to store multiple elements of the exact same data type.

Because the memory is contiguous, the CPU can instantly jump to any element mathematically by calculating its 'offset' from the start of the array. This is why arrays offer blazing fast $O(1)$ random access time. However, classic C-style arrays are notorious for being structurally rigid; their size is permanently locked the moment they are created and cannot grow or shrink dynamically.

Syntax

cpp
// 1. Declaration and Initialization
// The size [5] is permanently locked!
int scores[5] = {10, 20, 30, 40, 50};

// 2. Auto-sizing based on initialization elements
int autoSized[] = {1, 2, 3}; // Size is exactly 3

// 3. Accessing Elements (Arrays are 0-Indexed!)
int firstScore = scores[0]; // 10

// 4. Modifying Elements
scores[4] = 99; // Changes 50 to 99

Common Pitfalls

  • Accessing out of bounds (Memory Corruption). If an array has 5 elements, its highest index is 4. If you try to read or write scores[5], C++ does NOT stop you! It blindly jumps to that memory address and corrupts whatever data belongs to another variable sitting there.
  • Arrays losing their size. In raw C++, arrays do not 'know' their own length. If you pass an array to a function, it strictly degrades (decays) into a raw memory pointer to its first element, completely forgetting how big it originally was.

Interview Questions

Why are arrays in C++ (and most programming languages) 0-indexed instead of 1-indexed?

Array indices aren't just abstract numbers; they are mathematically literal memory 'offsets'. The address of the first element is exactly at the start of the array block (Offset of 0 memory blocks). The second element is offset by 1 block, etc. Starting at 0 eliminates a subtraction operation (index - 1), slightly speeding up CPU calculations for every single array access.

Why does the modern C++ industry aggressively advocate for std::vector instead of raw C-style arrays?

Raw arrays are fundamentally unsafe and rigid. They don't track their own size, don't perform bounds checking, and cannot dynamically resize. std::vector is a modern, dynamic array wrapper that automatically grows when full, perfectly manages its own memory size, and provides safety functions.

Real-World Example

Dynamically calculating the size of an array without hardcoding it.

example
cpp
#include <iostream>

int main() {
    int scores[] = {85, 92, 78, 90, 88}; 
    
    // Total size of array in bytes (5 * 4 = 20) divided by the size of one element (4)
    // Equals 5 elements!
    int numElements = sizeof(scores) / sizeof(scores[0]);
    
    int sum = 0;
    for (int i = 0; i < numElements; i++) {
        sum += scores[i];
    }
    
    std::cout << "Average: " << (float)sum / numElements << "\n";
    return 0;
}

Check Your Knowledge

Test your understanding of Arrays with these quick questions.

Question 1

What is the catastrophic result of executing `int arr[3] = {1,2,3}; arr[10] = 99;` in C++?

Take C++ Quiz
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Arrays

Overview

If you need to store the scores of 1,000 players in a video game, creating 1,000 individual variables (int p1, p2...) is impossible. An Array solves this by allocating a single, massive block of contiguous (side-by-side) memory to store multiple elements of the exact same data type.

Because the memory is contiguous, the CPU can instantly jump to any element mathematically by calculating its 'offset' from the start of the array. This is why arrays offer blazing fast $O(1)$ random access time. However, classic C-style arrays are notorious for being structurally rigid; their size is permanently locked the moment they are created and cannot grow or shrink dynamically.

Syntax

cpp
// 1. Declaration and Initialization
// The size [5] is permanently locked!
int scores[5] = {10, 20, 30, 40, 50};

// 2. Auto-sizing based on initialization elements
int autoSized[] = {1, 2, 3}; // Size is exactly 3

// 3. Accessing Elements (Arrays are 0-Indexed!)
int firstScore = scores[0]; // 10

// 4. Modifying Elements
scores[4] = 99; // Changes 50 to 99

Common Pitfalls

  • Accessing out of bounds (Memory Corruption). If an array has 5 elements, its highest index is 4. If you try to read or write scores[5], C++ does NOT stop you! It blindly jumps to that memory address and corrupts whatever data belongs to another variable sitting there.
  • Arrays losing their size. In raw C++, arrays do not 'know' their own length. If you pass an array to a function, it strictly degrades (decays) into a raw memory pointer to its first element, completely forgetting how big it originally was.

Interview Questions

Why are arrays in C++ (and most programming languages) 0-indexed instead of 1-indexed?

Array indices aren't just abstract numbers; they are mathematically literal memory 'offsets'. The address of the first element is exactly at the start of the array block (Offset of 0 memory blocks). The second element is offset by 1 block, etc. Starting at 0 eliminates a subtraction operation (index - 1), slightly speeding up CPU calculations for every single array access.

Why does the modern C++ industry aggressively advocate for std::vector instead of raw C-style arrays?

Raw arrays are fundamentally unsafe and rigid. They don't track their own size, don't perform bounds checking, and cannot dynamically resize. std::vector is a modern, dynamic array wrapper that automatically grows when full, perfectly manages its own memory size, and provides safety functions.

Real-World Example

Dynamically calculating the size of an array without hardcoding it.

example
cpp
#include <iostream>

int main() {
    int scores[] = {85, 92, 78, 90, 88}; 
    
    // Total size of array in bytes (5 * 4 = 20) divided by the size of one element (4)
    // Equals 5 elements!
    int numElements = sizeof(scores) / sizeof(scores[0]);
    
    int sum = 0;
    for (int i = 0; i < numElements; i++) {
        sum += scores[i];
    }
    
    std::cout << "Average: " << (float)sum / numElements << "\n";
    return 0;
}

Check Your Knowledge

Test your understanding of Arrays with these quick questions.

Question 1

What is the catastrophic result of executing `int arr[3] = {1,2,3}; arr[10] = 99;` in C++?

Take C++ Quiz

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A