How will execute this pgm?

#include<iostream.h>
#include<conio.h>
void main()
{
int x[5]={1,2,3,4,5}, y[5]={5,4,3,2,1}, result[5]={0,0,0,0,0};
int i=0;
while(i++<5)
result[i]=x[i]-y[i];
clrscr();
cout<<"\n The contents of the aray are:\n";
i=0;
do
{
cout<<"\t"<<x[i]<<"\t"<<y[i]<<"\t"<<result[i]<<"\n";
i++;
}
while(i<5);
getch();
}

The above program is executed the following output are displayed. How this executed plz explain this.

The contents of the array are:
1 -1 0
2 4 -2
3 3 0
4 2 2
5 1 4

How will execute the following lines
while(i++<5)
result[i]=x[i]-y[i];
1
2
3
int i = 0; 
while (i++ < 5)
  result[i] = x[i]-y[i];


Will do the same thing as this:
1
2
3
4
5
result[1] = x[1]-y[1];
result[2] = x[2]-y[2];
result[3] = x[3]-y[3];
result[4] = x[4]-y[4];
result[5] = x[5]-y[5];


You should not that you go out of bounds of the array. Why? Because you increment i in the while statement which happens before the first operation on result,x,y.

This is probably what you are looking for:
1
2
3
int i;
for (i = 0; i < 5; i++)
  result[i] = x[i]-y[i];
Topic archived. No new replies allowed.