4

Check If Index Exists in an Array in C++

 1 year ago
source link: https://thispointer.com/check-if-index-exists-in-an-array-in-c/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Check If Index Exists in an Array in C++

This tutorial will discuss about a unique way to check if index exists in an array in C++.

While using an array in C++, many times we need to access an element from array based on the index position.

But if we try to access an element at an index position that is invalid or that does not exist in the array, then it can result in undefined behaviour.

Therefore it is must to check if a given index position exists in the array or not before accessing element at that index position.

To check if index position is valid or not, first we need to fetch the size of the array, and then we can check, if the given index position is either greater than or equal to zero and less than the size of the array. If both condition satisfies then it means the index is valid

Advertisements

Let’s see the complete example,

Copy to clipboard
#include <iostream>
int main()
int arr[] = {4, 6, 2, 4, 8, 3, 3, 9, 10};
int index = 3;
// Get the size of array
size_t len = sizeof(arr)/sizeof(arr[0]);
// Check if index is less than the size
// and greater than or equal to 0
if(index >= 0 && index < len)
std::cout << "Yes, index is valid, and exists in Array. \n";
std::cout << "No, index is not valid, and does not exists in Array. \n";
return 0;
#include <iostream>

int main()
{
    int arr[] = {4, 6, 2, 4, 8, 3, 3, 9, 10};

    int index = 3;

    // Get the size of array
    size_t len = sizeof(arr)/sizeof(arr[0]);

    // Check if index is less than the size
    // and greater than or equal to 0
    if(index >= 0 && index < len)
    {
        std::cout << "Yes, index is valid, and exists in Array. \n";
    }
    else
    {
        std::cout << "No, index is not valid, and does not exists in Array. \n";
    }
    return 0;
}

Output :

Copy to clipboard
Yes, index is valid, and exists in Array.
Yes, index is valid, and exists in Array.

Summary

Today we learned about a way to check if index exists in an array in C++. Thanks.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK