C++ Program To Implement Array Out of Bounds

Array Out Of Bound

It happens when the index used to address array things surpasses the permitted esteem. It's the region outside the array bounds which is being tended to, that is the reason this circumstance is viewed as an instance of unclear conduct. Nonattendance of array invade control in C and C++ is the factor that makes this mistake conceivable.


Array Out of Bounds - Raw Arrays

#include<iostream>
#include<stdexcept>
using namespace std;
 int main()
{
    int a[20],n,p;
    cout<<"Enter the number of elements : ";
    cin>>n;
    cout<<"Enter the elements : ";
    for(int i=0;i<n;i++)    cin>>a[i];
    try
    {
     cout<<"Enter the index of element to display : ";
     cin>>p;
     if(p>=n || p<0) throw out_of_range("Invalid index.\n");
     cout<<"Element at index "<<p<<" is "<<a[p]<<endl;
    }
    catch(out_of_range r)
    {
     cout<<r.what();
    }
    return 0;
}

OUTPUT:
Enter the number of elements : 5
Enter the elements : 1 2 3 4 5
Enter the index of element to display : 10
Invalid index.



Array Out Of Bounds  - Vectors

#include<iostream>
#include<stdexcept>
#include<vector>
using namespace std;
int main()
{
    int n,p;
    cout<<"Enter the number of elements : ";
    cin>>n;
    vector<int> a(n);
    cout<<"Enter the elements : ";
    for(int i=0;i<n;i++)    cin>>a[i];
    try
    {
     cout<<"Enter the index of element to display : ";
     cin>>p;
     cout<<"Element at index "<<p<<" is "<<a.at(p)<<endl;
    }
    catch(out_of_range r)
    {
     cout<<"Array out of Bound.\n";
    }
    return 0;
}

OUTPUT:
Enter the number of elements : 5
Enter the elements : 1 2 3 4 5
Enter the index of element to display : -2
Array out of Bound.

Post a Comment

Previous Post Next Post