Arrays in C++

Mannan Ul Haq
0

Arrays in C++ are used to store multiple elements of the same data type in a contiguous memory block. They provide a convenient way to work with collections of values and are widely used in programming. Arrays can be one-dimensional or multi-dimensional.


1. One-Dimensional Arrays:

A one-dimensional array, also known as a linear array, is a collection of elements of the same data type arranged in a single row.

Array Length = 4
First Index = 0
Last Index = 3

In C++, each element in an array is associated with a number known as an array Index. We can access elements by using those indices.


Declaration and Initialization:

To declare a one-dimensional array in C++, you need to specify the data type of the elements and the size of the array. The size represents the number of elements the array can hold. The syntax for declaring a one-dimensional array is as follows: 


dataType arrayName[arraySize];

 

Here, dataType refers to the type of data the array will store, such as int, char, float, etc. arrayName is the name given to the array, and arraySize denotes the number of elements the array can hold. 


After declaring the array, you can initialize it with different methods:


1. In C++, its possible to initialize an array during declaration. For example:


int arr[5] = { 19, 10, 8, 7, 9 };

 

2. Another method to initialize array during declaration is:


int arr[] = { 19, 10, 8, 7, 9 };


Here, we have not mentioned the size of the array. In such cases, the compiler automatically computes the size. (alert-success)

 

3. Taking inputs from the user and store them in an array.

  • For this first of all initialize the size of array:
int arr[5]; or int arr[SIZE];

          Where SIZE is an constant variable.

  • Secondly, initialize the elements using loops:
for (int index = 0; index < SIZE; index++)
    cin >> arr[index];


For example:


#include <iostream>
using namespace std;

const int arraySize = 5;  // Size of the array

int main()
{
    int numbers[arraySize];  // Declare the array to store user input

    // Prompt the user to enter values for the array
    cout << "Enter " << arraySize << " numbers:" << endl;

    // Read user input and store it in the array
    for (int i = 0; i < arraySize; i++)
    {
        cout << "Number " << i + 1 << ": ";

        cin >> numbers[i];
    }

    return 0;
}


Partial Initialization:

int list[25] = { 4, 7 };


  • Declares "list" to be an array of 25 components
  • The first two components are initialized to 4 and 7 respectively.
  • All other components are initialized to 0.

Accessing Elements:

Elements in a one-dimensional array can be accessed using the index.

Example:

 

int num = numbers[2]; // Accessing the element at index 2


Printing Array Elements:

We can print array using loop:

for (index = 0; index < SIZE; index++)
    cout << arr[index] << " ";


For example:


#include <iostream>
using namespace std;

const int arraySize = 5;  // Size of the array

int main()
{
    int numbers[arraySize];  // Declare the array to store user input

    // Prompt the user to enter values for the array
    cout << "Enter " << arraySize << " numbers:" << endl;

    // Read user input and store it in the array
    for (int i = 0; i < arraySize; i++)
    {
        cout << "Number " << i + 1 << ": ";

        cin >> numbers[i];
    }

    // Print the array elements
    cout << "The array elements are: ";

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

    return 0;
}


Finding SIZE of Array:

To find the size of an array using the sizeof operator, you can divide the total size of the array by the size of its individual elements. The sizeof operator provides the size of the array in bytes. By dividing it by the size of a single element, you can determine the number of elements in the array.

int arr[] = { 1, 3, 5, 7 };
int SIZE = sizeof(arr) / sizeof(arr[0]);

 


Arrays as Parameters to Functions:

  • Arrays are passed by reference only and the symbol '&' is not used when declaring an array as a formal parameter.
int Function(int arr[], int SIZE)
  • The reserved word "const" in the declaration of the formal parameter can prevent the function from changing the actual parameter.
int Function(const int arr[], int SIZE)

  • Individual array elements passed by call-by-value i.e. pass myArray[3] to function.
  • The actual parameter is written as: 
Function(arr, SIZE);


For example:


#include <iostream>
using namespace std;

// Function to calculate the sum of the elements in an array
int calculateSum(int arr[], int size)
{
    int sum = 0;

    for (int i = 0; i < size; i++)
    {
        sum += arr[i];
    }

    return sum;
}

int main()
{
    const int size = 5;

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

    // Call the function and pass the array as a parameter
    int sum = calculateSum(numbers, size);

    cout << "Sum of array elements: " << sum << endl;

    return 0;
}


 

2. Two-Dimensional Arrays:

A two-dimensional array, also known as a matrix, is a collection of elements arranged in rows and columns. It can be visualized as a table or a grid.

Declaration and Initialization:

To declare a two-dimensional array in C++, you need to specify the data type of the elements, the number of rows, and the number of columns. The syntax for declaring a two-dimensional array is as follows:

dataType arrayName[rowSize][columnSize];

Here, `dataType` represents the type of data the array will store, such as `int`, `char`, `float`, etc. `arrayName` is the name given to the array, `rowSize` denotes the number of rows, and `columnSize` represents the number of columns.


After declaring the array, you can initialize it with values using the following methods:

1. Initialize an array during declaration. For example:

int arr[2][3] = { 2, 4, 5, 9, 0, 19 };

 

0R
int arr[2][3] = { {2, 4, 5}, {9, 0, 19} };

Here, each set of curly braces represents a row, and the values inside them represent the elements of that row. The number of elements in each row should match the number of columns specified during the declaration. (alert-success)

2. Taking inputs from the user using loops:

for (int i = 0; i < ROWS; i++)
{
    for (int j = 0; j < COLUMNS; j++)
    {
        cin >> arr[i][j];
    }
}

 

For example:


#include <iostream>
using namespace std;

const int rows = 3;    // Number of rows in the array
const int columns = 3; // Number of columns in the array

int main()
{
    int matrix[rows][columns];  // Declare the 2D array to store user input

    // Prompt the user to enter values for the array
    cout << "Enter " << rows * columns << " numbers for the 2D array:" << endl;

    // Read user input and store it in the 2D array
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            cout << "Element (" << i << ", " << j << "): ";

            cin >> matrix[i][j];
        }
    }

    return 0;
}

 

Accessing Elements:

In a two-dimensional array, elements are accessed using both the row and column indices. The row index specifies the row's position, and the column index specifies the column's position. The indices start from 0.

To access an element, you can use the array name followed by the row and column indices in square brackets:

arrayName[rowIndex][columnIndex];

For example, to access the element in the second row and third column of a 2D array named `matrix`, you would use `matrix[1][2]` because the indices start from 0.


Printing Array Elements:

To print the elements of a two-dimensional array, you can use nested loops. The outer loop iterates over the rows, and the inner loop iterates over the columns.

for (int i = 0; i < rowSize; i++)
{
    for (int j = 0; j < columnSize; j++)
    {
        cout << arrayName[i][j] << " ";
    }
    cout << endl; // Move to the next line after printing each row
}

For example:

#include <iostream>
using namespace std;

const int rows = 3;    // Number of rows in the array
const int columns = 3; // Number of columns in the array

int main()
{
    int matrix[rows][columns];  // Declare the 2D array to store user input

    // Prompt the user to enter values for the array
    cout << "Enter " << rows * columns << " numbers for the 2D array:" << endl;

    // Read user input and store it in the 2D array
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            cout << "Element (" << i << ", " << j << "): ";
            cin >> matrix[i][j];
        }
    }

    // Print the 2D array elements
    cout << "The 2D array elements are:" << endl;
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

Arrays as Parameters to Functions:

  • 2D-Arrays are also passed by reference only.
int Function(int arr[rows][columns])

  • The actual parameter is written as:

Function(arr);

  • When declaring a Two-Dimensional array as a formal parameter we can omit size of first dimension(rows), but no the second(columns).


3. Character Arrays or C-Strings:

Character arrays, also known as C-strings, are arrays of characters terminated by a null character '\0'. They are used to represent and manipulate strings in C++. In C++, C-strings are null terminated; that is, the last character in a C-string is always the null character. C-strings are stored in (One-Dimensional) character arrays.


Difference between 'A' and "A":

  • The first one is character A; and the second one is C-string A.
  • Because C-strings are null terminated, "A" represents two characters: 'A' and '\0'. So it takes two memory cells.

Declaration and Initialization:

// Declaration
char arrayName[arraySize];


   Following are the methods to initialize the character array:


1. We can also initialize a character array at the time of declaration, either by providing a string literal or by assigning individual characters.


char name[5] = { 'J', 'o', 'h', 'n', '\0' };


OR

char name[5] = "John";


The size of the array is automatically determined based on the length of the string literal, including the null character.


OR 

char name[] = "John";


 2. Input by user:


char name[10];
cin >> name;


  • Stores the next input C-string into "name".
  • The length of the input C-string must be less than or equal to 9.
  • If the length of the input is string is 4, the computer stores the four characters that are input and the null character '\0'.

Printing Array Elements:

cout << arrayName; // Printing the character array as a string


For example:


#include <iostream>
using namespace std;

int main()
{
    char myArray[] = "Hello World!";

    cout << "The character array: " << myArray << endl;

    return 0;
}

 

NOTE: C++ provides the `std::string` class for more convenient string manipulation, which is often preferred over character arrays in modern C++ programming. (alert-success)


Usage of "getline" and "ignore" Functions in Character Arrays:

The extraction operator, >>, skips all leading whitespaces and stops reading data into the current variable as soon as it finds the first whitespace character.

The `getline` function is a useful tool in C++ that allows you to read an entire line of text, including spaces, from the input stream. It is commonly used to read input from the user.

To use `getline` with character arrays, you need to provide three arguments: the input stream, the character array to store the line, and the delimiter character. The delimiter character is optional and defaults to the newline character ('\n').


Here's an example of how to use `getline` with a character array:


#include <iostream>
using namespace std;

int main()
{
    const int MAX_LENGTH = 100;
    char input[MAX_LENGTH];

    cout << "Enter a line of text: ";
    cin.getline(input, MAX_LENGTH);

    cout << "You entered: " << input << endl;

    return 0;
}


In the above code, we declare a character array called `input` with a maximum length of 100 characters. We prompt the user to enter a line of text using `cout`, and then we use `cin.getline` to read the input into the `input` array.


Why do we need to use cin.ignore() before getline?

Now, let's discuss why we need to use `cin.ignore()` before using `getline` in some cases. The `cin.ignore()` function is used to discard characters from the input stream, and it can be helpful in situations where there are leftover characters in the stream after using `cin` to read input.


One common scenario where `cin.ignore()` is used before `getline` is when you are mixing different types of input methods. For example, if you read an integer using `cin >> someInt`, and then you want to use `getline` to read a line of text, you may encounter issues.

The problem arises because when you enter an integer, say "123", and press enter, the newline character ('\n') is left in the input stream. When you subsequently call `getline`, it will see the newline character as the first character and immediately terminate, resulting in an empty string.


To solve this, you can use `cin.ignore()` to discard the leftover newline character before calling `getline`. Here's an example:


#include <iostream>
using namespace std;

int main()
{
    const int MAX_LENGTH = 100;
    char input[MAX_LENGTH];
    int someInt;

    cout << "Enter an integer: ";
    cin >> someInt;

    cin.ignore(); // Ignore the newline character

    cout << "Enter a line of text: ";
    cin.getline(input, MAX_LENGTH);

    cout << "You entered: " << input << endl;

    return 0;
}


Find length of String:

To find the length of a string using the `strlen` function, you need to include the `<cstring>` header file, which provides the declaration for the `strlen` function. The `strlen` function takes a null-terminated character array (string) as its argument and returns the number of characters in the string, excluding the null character ('\0').


Here's an example that demonstrates how to use `strlen` to find the length of a string:


#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char str[] = "Hello world!";

    int length = strlen(str) + 1; //We are adding 1 because the 'strlen' function excludes the null character

    cout << "The length of the Character Array is: " << length << endl;

    return 0;
}


2D-Character Array:

A 2D character array, also known as a matrix or grid of characters, is an array where each element is itself an array of characters. It can be used to store and manipulate strings or characters in a two-dimensional structure.


Initialization of a 2D character array:

1. During declaration of array:


char list[3][7] = { "Mango", "Apple", "Banana" };

 

2. Using loops:


char arr[rows][columns];
for (int i = 0; i < rows; i++)
    cin.getline(arr[i], columns);


Printing Elements of Array:

for (int i = 0; i < rows; i++)
    cout << arr[i] << endl;



Arrays in C++ provide a powerful tool for storing and manipulating collections of elements. They are versatile and widely used in various programming tasks.


Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !