0

Lets say we have array with 5 elements and I have to iterate this array using for loop as given below:

int A[5]{2,3,5,9,1};
for(int i = 0; i<5; i++)
{
    cout<<i[A];
}

I am able to iterate using this(i[A]), please explain how it works?

4
  • 1
    In what language? (Add the tag.) Commented Jun 10, 2020 at 18:27
  • 1
    No, you are accessing out of bounds because i<=5 should be i<5 Commented Jun 10, 2020 at 20:16
  • 1
    What happened when you ran that code? Commented Jun 10, 2020 at 20:17
  • It works in code, but I don't know how it is working? Commented Jun 13, 2020 at 12:48

2 Answers 2

1

Your errors:

int A[5]{2,3,5,9,1};
for(int i = 0; i<=5; i++) // accessing i <= 5 (out of bound of array), do it i < 5
{
    cout<<i[A]; // print A[i] not i[A], that's incorrect, i ain't an array
}

If you're doing the same in C++, then you could use std::vector<> instead.

Consider this program:

#include <iostream>
#include <vector>

int main(void)
{
    std::vector<int> A{2, 3, 5, 9, 1};

    for (int i = 0; i < A.size(); i++)
        std::cout << A[i] << ' ';

    std::cout << std::endl;

    return 0;
}

std::vector<> has a lot of usage in today's C++. No longer you need to stick with static size of arrays.

As an alternative, you could do the same thing (like C-style):

#include <iostream>

int main(void)
{
    int A[]{2, 3, 5, 9, 1};
    size_t len = sizeof(A) / sizeof(A[0]);

    for (int i = 0; i < len; i++)
        std::cout << A[i] << ' '; // you're trying to access elements of 'A' not of 'i'

    std::cout << std::endl;

    return 0;
}

This program dynamically allocates the size of array and iterates over A[i] until i is reached the size of array defined.

Sign up to request clarification or add additional context in comments.

3 Comments

I got your point, but I guess my question was not correct as I wanted to know how this i[A] works fine.
@RahulBalyan the variable i isn't an array.
yes, but if you try iterate using this particular statement, it is working fine, I am able to print all the elements of an array. Please try it by yourself and u will know.
1

It appears to be legal. Simplistically ptr[count] is *(ptr + count) and it appears you can swap them around. *(count + ptr). One needs to be a pointer, the other an integer. Never ever seen it used in 40 years.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.