C++ Beginner

cpp_010: Arrays in C++

codeaddict 2025. 1. 26. 19:09
Arrays are one of the most fundamental data structures in C++, allowing you to store multiple values of the same type in a single container. In this lesson, we’ll introduce arrays, explain their syntax, and provide two examples — one basic and one advanced — to showcase their usage.

1. What is an Array?

An array is a collection of elements stored in contiguous memory locations, all of which share the same data type. You can think of it as a list of values indexed starting from 0.

2. Declaring and Initializing an Array

To declare an array in C++, use the following syntax:

type arrayName[size];
  • type: The data type of the array elements (e.g., int, float, char).
  • arrayName: The name of the array.
  • size: The number of elements the array can hold.

You can initialize an array during declaration:

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

3. Example 1: Basic Array

Let’s create a program that prints all elements of an integer array.

#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {10, 20, 30, 40, 50}; // Declaration and initialization

    cout << "Array Elements:" << endl;
    for (int i = 0; i < 5; i++) { // Loop through the array
        cout << "numbers[" << i << "] = " << numbers[i] << endl;
    }
    return 0;
}

Output:

Array Elements:  
numbers[0] = 10  
numbers[1] = 20  
numbers[2] = 30  
numbers[3] = 40  
numbers[4] = 50

Explanation:

  • The for loop iterates over the array indices from 0 to 4.
  • The array elements are accessed using numbers[i].

4. Example 2: Array with User Input

In this example, we’ll calculate the average of numbers entered by the user.

#include <iostream>
using namespace std;

int main() {
    const int SIZE = 5;
    float numbers[SIZE];
    float sum = 0.0;

    cout << "Enter " << SIZE << " numbers:" << endl;

    // Taking user input
    for (int i = 0; i < SIZE; i++) {
        cin >> numbers[i];
        sum += numbers[i]; // Accumulating the sum
    }

    // Calculating the average
    float average = sum / SIZE;

    // Displaying the array and average
    cout << "Array Elements:" << endl;
    for (int i = 0; i < SIZE; i++) {
        cout << "numbers[" << i << "] = " << numbers[i] << endl;
    }
    cout << "Average: " << average << endl;

    return 0;
}

Output (Example):

Enter 5 numbers:  
10  
20  
30  
40  
50  
Array Elements:  
numbers[0] = 10  
numbers[1] = 20  
numbers[2] = 30  
numbers[3] = 40  
numbers[4] = 50  
Average: 30

Explanation:

  • The program prompts the user to input 5 numbers.
  • The for loop calculates the sum while storing the numbers in the array.
  • The average is computed and displayed along with the array elements.