Lesson 39 of 60 – Arrays in C++
65%

Arrays in C++

An array is a collection of multiple values of the same data type stored under one variable name. Instead of creating separate variables for every value, we can store related values together in an array.

Note: C++ arrays have a fixed size. The size of a built-in array is normally determined when the array is created and cannot be changed later.

1. What is an Array?

An array stores multiple values of the same data type in a single variable.

int marks[5];

Here, marks is an array that can store five integer values.

2. Why Use Arrays?

Arrays are useful when we need to store many related values.

  • Store multiple values using one variable name.
  • Reduce repeated variable declarations.
  • Make it easier to process collections of data.
  • Allow values to be accessed using indexes.
  • Work naturally with loops.

For example, five marks can be stored in one array instead of five separate variables.

3. Declaring an Array

The basic syntax for declaring an array is:

dataType arrayName[size];

Example:

int numbers[5];

Here:

  • int is the data type.
  • numbers is the array name.
  • 5 is the number of elements.

4. Initializing an Array

We can initialize an array when we declare it.

int numbers[5] = {10, 20, 30, 40, 50};

The five values are stored in the five array elements.

5. Array Index

An array uses an index to identify each element. C++ array indexes start from 0.

int numbers[5] = {10, 20, 30, 40, 50};
Index Value
0 10
1 20
2 30
3 40
4 50

6. Accessing an Array Element

Use the index inside square brackets to access an element.

int numbers[5] = {10, 20, 30, 40, 50};

std::cout << numbers[0];

Output:

10

The expression numbers[0] accesses the first element.

7. Accessing the Last Element

int numbers[5] = {10, 20, 30, 40, 50};

std::cout << numbers[4];

Output:

50

For an array containing five elements, the last index is 4.

8. Changing an Array Element

An array element can be changed by assigning a new value to its index.

int numbers[5] = {10, 20, 30, 40, 50};

numbers[2] = 100;

std::cout << numbers[2];

Output:

100

9. Printing All Array Elements

A loop can be used to print every element of an array.

int numbers[5] = {10, 20, 30, 40, 50};

for (int i = 0; i < 5; i++) {

    std::cout << numbers[i] << std::endl;
}

Output:

10
20
30
40
50

10. Array with User Input

We can use a loop to take values from the user.

int numbers[5];

for (int i = 0; i < 5; i++) {

    std::cin >> numbers[i];
}

Each input value is stored at a different index.

11. Taking and Displaying Array Values

#include <iostream>

int main() {

    int numbers[5];

    std::cout << "Enter 5 numbers: ";

    for (int i = 0; i < 5; i++) {
        std::cin >> numbers[i];
    }

    std::cout << "Numbers are:" << std::endl;

    for (int i = 0; i < 5; i++) {
        std::cout << numbers[i] << " ";
    }

    return 0;
}

12. Finding the Sum of Array Elements

int numbers[5] = {10, 20, 30, 40, 50};

int sum = 0;

for (int i = 0; i < 5; i++) {

    sum += numbers[i];
}

std::cout << "Sum = " << sum;

Output:

Sum = 150

13. Finding the Average

int marks[5] = {70, 80, 90, 60, 75};

int sum = 0;

for (int i = 0; i < 5; i++) {

    sum += marks[i];
}

double average = sum / 5.0;

std::cout << "Average = "
          << average;

Using 5.0 helps produce a decimal result.

14. Finding the Largest Element

int numbers[5] = {25, 80, 45, 90, 30};

int largest = numbers[0];

for (int i = 1; i < 5; i++) {

    if (numbers[i] > largest) {
        largest = numbers[i];
    }
}

std::cout << "Largest = "
          << largest;

Output:

Largest = 90

15. Finding the Smallest Element

int numbers[5] = {25, 80, 45, 90, 30};

int smallest = numbers[0];

for (int i = 1; i < 5; i++) {

    if (numbers[i] < smallest) {
        smallest = numbers[i];
    }
}

std::cout << "Smallest = "
          << smallest;

Output:

Smallest = 25

16. Counting Even Numbers

int numbers[6] = {10, 15, 20, 25, 30, 35};

int count = 0;

for (int i = 0; i < 6; i++) {

    if (numbers[i] % 2 == 0) {
        count++;
    }
}

std::cout << "Even numbers = "
          << count;

The modulus operator checks whether an element is divisible by 2.

17. Counting Odd Numbers

int numbers[6] = {10, 15, 20, 25, 30, 35};

int count = 0;

for (int i = 0; i < 6; i++) {

    if (numbers[i] % 2 != 0) {
        count++;
    }
}

std::cout << "Odd numbers = "
          << count;

18. Reversing an Array

int numbers[5] = {10, 20, 30, 40, 50};

for (int i = 4; i >= 0; i--) {

    std::cout << numbers[i] << " ";
}

Output:

50 40 30 20 10

The loop starts from the last index and moves toward index 0.

19. Character Array

An array can also store characters.

char letters[5] = {'A', 'B', 'C', 'D', 'E'};

for (int i = 0; i < 5; i++) {

    std::cout << letters[i] << " ";
}

Output:

A B C D E

20. String Literal with Character Array

A character array can be initialized using a string literal.

char name[] = "Rahul";

std::cout << name;

C++ stores the characters along with a terminating null character '\0'.

For modern C++ programs, std::string is generally more convenient for working with text.

21. Array Size and sizeof

The sizeof operator can be used to determine the total number of bytes occupied by an array.

int numbers[5] = {10, 20, 30, 40, 50};

std::cout << sizeof(numbers);

To calculate the number of elements in an array in the same scope, we can use:

int size = sizeof(numbers) / sizeof(numbers[0]);

22. Partially Initialized Arrays

If an array is initialized with fewer values than its declared size, the remaining elements are value-initialized.

int numbers[5] = {10, 20};

for (int i = 0; i < 5; i++) {

    std::cout << numbers[i] << " ";
}

Output:

10 20 0 0 0

23. Omitting the Array Size

When an array is initialized with values, its size can be omitted. The compiler determines the size from the initializer.

int numbers[] = {10, 20, 30, 40, 50};

This array contains five elements.

24. Passing an Array to a Function

void display(int numbers[], int size) {

    for (int i = 0; i < size; i++) {

        std::cout << numbers[i] << " ";
    }
}

int main() {

    int numbers[5] = {
        10, 20, 30, 40, 50
    };

    display(numbers, 5);

    return 0;
}

An array can be passed to a function along with its size.

25. Searching an Array

int numbers[5] = {
    10, 20, 30, 40, 50
};

int search = 30;
bool found = false;

for (int i = 0; i < 5; i++) {

    if (numbers[i] == search) {

        found = true;
        break;
    }
}

if (found) {
    std::cout << "Value found";
}
else {
    std::cout << "Value not found";
}

26. Common Array Mistakes

  • Using an index outside the valid range.
  • Forgetting that array indexes start from 0.
  • Using the wrong array size in a loop.
  • Reading an element before assigning a meaningful value.
  • Confusing the number of elements with the last index.
  • Accidentally modifying an element at the wrong index.
Important: For an array of five elements, valid indexes are 0 through 4. Accessing an invalid index can cause undefined behavior.

27. Practical Student Marks Program

#include <iostream>

int main() {

    int marks[5];

    int sum = 0;

    std::cout << "Enter marks of 5 subjects:"
              << std::endl;

    for (int i = 0; i < 5; i++) {

        std::cin >> marks[i];

        sum += marks[i];
    }

    double average = sum / 5.0;

    std::cout << "Total = "
              << sum << std::endl;

    std::cout << "Average = "
              << average;

    return 0;
}

28. Practical Largest Number Program

#include <iostream>

int main() {

    int numbers[5];

    std::cout << "Enter 5 numbers:"
              << std::endl;

    for (int i = 0; i < 5; i++) {

        std::cin >> numbers[i];
    }

    int largest = numbers[0];

    for (int i = 1; i < 5; i++) {

        if (numbers[i] > largest) {

            largest = numbers[i];
        }
    }

    std::cout << "Largest = "
              << largest;

    return 0;
}

29. Best Practices for Arrays

  • Use meaningful array names.
  • Keep track of the number of elements.
  • Use loops instead of repeating the same code.
  • Remember that indexes start at 0.
  • Never intentionally access an index outside the valid range.
  • Initialize arrays when appropriate.
  • Pass the array size when a function needs it.
  • Use std::array or std::vector when their features are more suitable than a built-in array.

30. Arrays – Final Summary

Concept Meaning
Array A collection of values of the same data type.
Index Position used to access an array element.
First Index Always 0 for a built-in C++ array.
Last Index Size minus 1.
Initialization Giving initial values to array elements.
sizeof Returns the size in bytes of its operand.
Loop Commonly used to process array elements.
int numbers[5] = {
    10, 20, 30, 40, 50
};

for (int i = 0; i < 5; i++) {

    std::cout << numbers[i] << " ";
}

📌 Key Points

  • An array stores multiple values of the same data type.
  • Array indexes start from 0.
  • The last index of an array is one less than its number of elements.
  • Array elements can be accessed and modified using indexes.
  • Loops are commonly used to process arrays.
  • Arrays can store integers, characters, floating-point values, and other types.
  • An array can be initialized when it is declared.
  • Arrays can be passed to functions.
  • sizeof can help determine the total size of an array in bytes.
  • Accessing an array outside its valid range can cause undefined behavior.

🧠 Quick Quiz

Question: What is the index of the first element in a C++ array?