Please refer to the c++ program and the output below. I understand the program but I have a small doubt regarding the output of the program. pls help.
# 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,j=0;
clrscr();
while (i++ < 5)
{
cout<<i<<"\n";
result [i] = x [i] + y [i];
}
cout <<"\n The contents of the array are: \n";
do
{
cout << "\t" << x [j];
cout<< "\t" << y [j];
cout<<"\t"<< result [j]<<"\n";
j++;
} while (j<5);
getch ( );
}
While executing the output of the program is:-
1 -1 0
2 4 -2
3 3 0
4 2 2
5 1 4
How i get the output as 1 -1 0 in the first row especially I presume the output should be 1 5 0 in the first row. Please help.
Well, you are accessing beyond the end of the arrays.
1 2 3 4
while( i++ < 5 ) {
cout << i << "\n";
result[ i ] = x[ i ] + y[ i ];
}
What is the output you get from this loop? Is it not 1, 2, 3, 4, and 5?
You are then accessing elements 1, 2, 3, 4, and 5 from x and y and writing
the sum to the same position in result. But the valid indices in these three
arrays are 0 - 4, not 1 - 5.