Please tell my how this program flow work

Q­6 What will be the output of the following program? #include
using namespace std;
int main() {
int arr[]={0,1,2,3,4};
int i, ptr;
for(ptr= arr, i=0; ptr+i <= arr+4; ptr++, i++) cout<<
(ptr+i);
return 0;
}
A) 01234
B) 024
C) 234
D) 12340
why it printing 024 instead of 01234

Hello @dkroy8790,

NOTE:

  1. The name of the array act as the pointer to the first element of the array.
  2. (array_name +i) refers to i location ahead of the location pointed by array_name

Now, coming to the execution:

  1. initially:
    ptr points to location of 0 and i=0
    so, *(ptr+0)=0

  2. ptr after increment points to 1 and i=1
    so, *(ptr+1)=2

  3. ptr after increment points to 2 and i=2
    so, *(ptr+2)=4

  4. ptr after increment points to 3 and i=3
    but, (ptr+i) is a location ahead of(or greater than) the address of (arr+4)
    Terminating loop.

Hence, the ouput is: 024

Hope, this would help.
Give a like if you are satisfied.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.