#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();
}
output:
The contents of the array are:
1 -1 0
2 4 -2
3 3 0
4 2 2
5 1 4
The above program is executed the following output are displayed. How this executed plz explain this. Why first element of the array are displayed
and a crash. The problem is this line: while(i++<5) When i is 0, the condition '0<5' is evaluated, but then the '++' is applied and the loop body uses i=1. What happens when i=4? '4<5' evaulates as true, then '++' is applied, and the loop body uses i=5. However, an index of 5 falls out of bounds for all the arrays you're using.
You're not getting the correct results because you're not referencing your arrays correctly as booradley60 already explained.
1 2 3
int i=0;
while(i++<5)
result[i]=x[i]-y[i];
This loop will reference array elements [1] - [5]. Your array elements are [0] - [4]. A reference to [5] is UNDEFINED.
PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post. http://www.cplusplus.com/articles/jEywvCM9/