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?
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.
i isn't an array.
i<=5should bei<5