How will execute this program?

#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. Why this stored in First element in

1 -1 0 --> Explain this step only

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];
Each time the loop iterates, the arrays inside are using a larger value of i than before. This is bad because it could possibly cause a seg fault
Thanz . But I cant understand this part.
Why this stored in I element 1 -1 0 in this output..

1 -1 0
2 4 -2
3 3 0
4 2 2
5 1 4
The problem is in the statement

while(i++<5)

This reads the value of i, then compares it to 5, and then increments i.

This means that, the first time you execute the contents of the loop, i is already set to 1, so you never actually calculate the value of result[0].

Also, it means that the last time you enter the loop, i starts out as 4, so (i < 5) is true, but is then incremented to 5 before the contents of the loop begin to execute. You are therefore attempting to set the value of result[5], which is beyond the end of the array. You're writing that value into memory that may be allocated for something else, which can cause all sorts of chaos.

Fix that problem, and then see if it works.

Frankly, you're better off using std::vector objects instead of arrays anyway.

Last edited on
Topic archived. No new replies allowed.