One-Dimensional Arrays

One-dimensional arrays in C++ are used to store multiple values of the same data type in a single variable. They help organize data efficiently and make programs easier to manage.

What is a One-Dimensional Array?

A one-dimensional array is a collection of elements stored in a single row of memory locations.

Each element in the array is accessed using an index number.

Why Use Arrays?

Arrays are useful because they:

  • Store multiple values in one variable
  • Reduce the need for many separate variables
  • Make data handling easier
  • Improve code organization

Syntax of One-Dimensional Array

data_type array_name[size];

Example of Array Declaration

int numbers[5];

This creates an array named numbers that can store 5 integer values.

Initializing an Array

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

Accessing Array Elements

Array elements are accessed using index numbers.

  • First element index = 0
  • Second element index = 1
cout << numbers[0];
cout << numbers[2];

Example Program

#include <iostream>
using namespace std;

int main() {

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

cout << numbers[0] << endl;
cout << numbers[1] << endl;
cout << numbers[2] << endl;

return 0;
}

Output

10
20
30

Using Loop with Array

Loops are commonly used to access all array elements.

#include <iostream>
using namespace std;

int main() {

int numbers[5] = {1, 2, 3, 4, 5};

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

return 0;
}

Taking User Input in Array

#include <iostream>
using namespace std;

int main() {

int marks[3];

for (int i = 0; i < 3; i++) {
cin >> marks[i];
}

for (int i = 0; i < 3; i++) {
cout << marks[i] << endl;
}

return 0;
}

Important Points About Arrays

  • Array size is fixed after declaration
  • All elements must be of the same data type
  • Indexing starts from 0
  • Arrays store data in contiguous memory locations

Advantages of One-Dimensional Arrays

  • Easy data storage
  • Fast access using index
  • Simplifies repetitive tasks
  • Useful for loops and calculations

Disadvantages of Arrays

  • Fixed size
  • Cannot store different data types together
  • Insertion and deletion can be difficult

Why One-Dimensional Arrays are Important

Arrays are important because they:

  • Form the base of advanced data structures
  • Improve data management
  • Are widely used in programming
  • Help in sorting and searching algorithms

Real-Life Example

Think of a row of lockers:

  • Each locker stores one item
  • Every locker has a number

Similarly, an array stores multiple values, and each value has an index number.

Conclusion

One-dimensional arrays in C++ are essential data structures used to store multiple values efficiently. They simplify data handling, improve program organization, and are widely used in real-world programming applications.

Home » Intermediate C++ > Arrays and Strings >One-Dimensional Arrays