1. Home
C++ Tutorial

Explore C++ Tutorials: Exploring the World of C++ Programming

Discover comprehensive C++ tutorials designed for beginners and advanced programmers alike. Enhance your coding skills with step-by-step guides and practical examples.

  • 77 Lessons
  • 15 Hours
right-top-arrow
14

Arrays in C++: A Complete Guide

Updated on 23/09/2024416 Views

When you start with C++ programming, knowing array in C++ becomes an important part. I can assure you that arrays are similar to the base of data handling in C++. They allow us to keep numerous values in one variable which makes our code neat and effective.

In this tutorial, I aim to remove any confusion that you might have about array in C++. This comprehensive tutorial will walk you through different C++ array program to give you an understanding of how to practically use array in C++ . We’ll also be looking at different types of array in C++ to understand the whole range of array CPP has to offer.

Now, let’s begin!

What is an Array in C++?

An array in C++ is like a row of lockers. Each locker can contain an item, and all lockers are situated together at continuous memory spots. Arrays provide a straightforward method to store numerous values of the same sort under one title. You may access any locker by using its index number.

Arrays are used in various scenarios in programming:

  • Storing data of fixed size: Arrays are great for situations where we know the number of elements beforehand.
  • Matrix operations: For mathematical computations involving matrices, 2D arrays in C++ are commonly used.
  • Data management: Arrays are frequently employed for data storage and handling in applications, like game creation - for example, you could use an array to save the condition of diverse game objects.

Now, you may ask yourself why we even use array in C++? Well, the fact is there are some good reasons. Some of these reasons are:

  • Efficiency: Accessing and modifying elements is very fast due to the direct indexing.
  • Simplicity: Arrays provide a straightforward way to manage multiple values of the same type.
  • Memory Management: With arrays, you can allocate and manage memory efficiently.

Now, let's go further into the technical details of comprehending array in C++. We will start by seeing the definition and declaration of array in C++, then move to learn about various C++ array type and more.

Array Definition in C++

The official explanation may appear somewhat technical, yet do not be worried as I will simplify it. An array in C++ is a kind of data type that saves a set of elements with fixed size in sequence and all have identical types.

<data-type> <array-name>[size_of_array] #syntax to follow.

#for example

int myArray[5];

Here, myArray is an array of 5 integers.

Declaration of Array in C++

Declaring an array in C++ is straightforward. You just specify the type of elements and the number of elements.

int numbers[10];

This line of code declares an array named numbers that can hold 10 integers.

Types of Arrays in C++

1. One-Dimensional Array

This is the simplest form of an array, like a list of items.

float temperatures[7];

2. Two-Dimensional Array (2D Array C++)

A C++ two dimensional array is like a table with rows and columns.

int matrix[3][4];

This C++ two dimensional array has 3 rows and 4 columns, and can therefore hold 12 values of int datatype.

3. Multidimensional Array

You can have arrays with more than two dimensions, but these are less common. These are known as array multidimensional C++.

char hyperCube[5][4][3][2];

Accessing Elements of an Array in C++

In C++, I have learnt that when you are declaring an array in C++ then to access those elements available in the array, you need to use an index. The index remains as a right integer that refers to the zero based array, thus implying that the first element of the array is at index 0.Then, the second item's index becomes 1 and so forth. This indexing method allows for simple retrieval and alteration of stored values in the array.

Let’s look at some examples to understand accessing of elements of array in C++ better.

Example of Accessing Elements of an Array in C++

Let’s take an example of an integer array:

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

Here, numbers[0] represents the first element in the array which us 10 and numbers[1] represents the second element in the array, which is 20 and so on.

Reading Values from an Array

To read values from an array, you use the index of the element you want to access:

int firstNumber = numbers[0]; // firstNumber is now 10

int secondNumber = numbers[1]; // secondNumber is now 20

Modifying Values in an Array

You can also modify the values of an array by accessing them via their index and assigning a new value:

numbers[2] = 35; // Changes the third element to 35

numbers[4] = 55; // Changes the fifth element to 55

After these modifications, the numbers array will be {10, 20, 35, 40, 55}.

Using a Loop to Access Array Elements

Often, you’ll want to perform operations on every element in the array. This is typically done using loops. Here’s an example using a for loop to print all the elements of the array:

Example:

Using a loop to access array in C++

Output:

Output of loop to access array in C++

Code:

#include <iostream>

using namespace std;

int main() {

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

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

cout << "Element at index " << i << ": " << numbers[i] << endl;

}

return 0;

}

This loop goes through every index of the array from 0 to 4, and it prints out what is stored at that specific index. This way of accessing array in C++ is a very common method.

Boundary Checking

For a given array, it is very crucial that whenever accessing a certain position, the index must be within permitted bounds which are between 0 and n-1 and n being the size of the array. If an index accessed lies outside this range then it leads to undefined behavior which can cause program crashes or give unexpected results.

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

// Accessing valid index

cout << numbers[2] << endl; // Output: 30

// Accessing invalid index

cout << numbers[5] << endl; // Undefined behavior

C++ Array Program Example

Let’s look at a simple program that uses an array.

Example:

C++ array program example

Output:

Output of C++ array program example

Code:

#include <iostream>

using namespace std;

int main() {

int scores[5] = {90, 85, 88, 92, 79};

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

cout << "Score " << i + 1 << ": " << scores[i] << endl;

}

return 0;

}

Sorting an Array in C++

Sorting is a common operation. Here’s a quick example using the sort function from the standard library.

#include <algorithm>

sort(scores, scores + 5); // Sorts the array in ascending order

Needless to say, you can also do sorting an array in C++ manually.

Essentially, sorting an array in C++ refers to the ability of arranging the elements of an array in a particular order. This can be done based on size usually in an ascending order, meaning from the smallest size up to the largest size. It is a very important concept in programming because it helps with effective searching, data analysis and general data organization.

Different Ways of Sorting an Array in C++

In C++, there are several methods to sort an array. Each method has its own algorithm and is useful for different situations. Here is a short overview of some frequently used sorting methods:

  • Bubble sort
  • Selection sort
  • Insertion sort
  • Merge sort
  • Quick sort
  • Heap sort
  • Counting sort
  • Radix sort

Understanding the complexities of these sorting algorithms and picking the best one is an area of work itself, so we won’t dive deeper into this in this tutorial, and neither will we explain each of these sorting algorithms for sort an array in C++ in more depth.

For a more in-depth study and practical applications of sorting in C++, consider exploring upGrad’s Software Engineering Courses. These courses provide comprehensive learning experiences to enhance your programming skills and knowledge.

C++ Dynamic Array

A C++ dynamic array is a type of array that can alter its size during the running of a program. In comparison to static arrays, which have their dimensions determined at compile time and remain constant throughout execution, dynamic arrays can be made bigger or smaller as needed in real-time. This flexibility is possible because of pointers and the ability to allocate memory dynamically.

For making a C++ dynamic array, we employ the new operator to assign memory for the array during program execution. Let me present you with an easy illustration:

int* dynamicArray = new int[5];

// Don’t forget to free the memory

delete[] dynamicArray;

It's crucial to free the dynamically allocated memory to avoid memory leaks. This is done using the delete[] operator.

C++ Reverse Array

C++ reverse array involves changing the order of elements in a particular array to make the first element occupy the last position, the second, the second to the last and so forth. It is a common requirement in many algorithms or tasks involving data manipulation.

Here’s one of the ways how C++ reverse array can work.

#include <algorithm>

using namespace std;

int scores[5] = {90, 85, 88, 92, 79};

reverse(scores, scores + 5); // Reverses the array in place

After reversing, scores would be {79, 92, 88, 85, 90}.

Object Array C++

C++ object array can be defined as an aggregate of objects of a certain class wherein every member in the array is an object of the class. It helps you to configure various kinds of objects, which makes it possible to work with multiple objects of a specific class.

To create an object array C++, first, define a class. For example, let's define a simple Student class:

class Student {

public:

string name;

int age;

// Constructor

Student(string n, int a) : name(n), age(a) {}

// Member functions can be added here

};

Now, you can create an array of Student objects:

Student students[3] = {Student("Alice", 20), Student("Bob", 21), Student("Charlie", 22)};

This array, students, contains three Student objects.

With this knowledge, you can manage more complicated data structures and processes in C++. If you are enthusiastic about learning further and improving your abilities, think about investigating upGrad’s Software Engineering Courses.

In Conclusion

The idea and utilization of array in C++ are very important and you will use them often. They might look basic, but their ability and flexibility is strong. Whether it's about one-dimensional arrays, 2D arrays C++ or dynamic arrays - learning how to handle them well leads to being skilled in C++.

Are you prepared to explore further in the domain of C++? Go through upGrad’s Software Engineering Courses for boosting your abilities and understanding.

FAQ: Frequently Asked Questions

1. What is an array in C++?

An array in C++ is a group of items that are kept together at adjoining memory places. You can get to each item using an index.

2. How do you declare an array in C++?

In declaring an array you use the data type of the elements, you want the array to hold then put the number of elements followed by the bracket [].

3. How do you access elements of an array in C++?

The process of accessing elements is done by providing their index, which starts from 0. So, for the initial element we use myArray[0].

4. Can arrays in C++ store elements of different data types?

No, arrays can only store elements of the same type.

5. Can arrays be passed to functions in C++?

Certainly, arrays can be passed to functions by merely naming the array parameter in a function.

6. What is the difference between an array and a vector in C++?

As for the difference, there are arrays and vectors: the former are of a fixed size, whereas the latter can change size during their use.

7. Can arrays in C++ be initialized when declared?

Yes, arrays can be declared with an initial value when they are being created/defined. For example: int myArray[5] = {1, 2, 3, 4, 5};.

8. Are there any standard library functions for working with arrays in C++?

Yes, the C++ Standard Library gives functions such as sort, reverse and others in order to manipulate arrays.

Kechit Goyal

Kechit Goyal

Team Player and a Leader with a demonstrated history of working in startups. Strong engineering professional with a Bachelor of Technology (BTech…Read More

Need Guidance? We're Here to Help!
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...