printing array

i am having trouble with a bubble sort program i am trying to write. i think i have found the way to enter integers into the array but i cannot ssem to get them back out all at once. here is my code so far

#include <iostream>


using namespace std;


const int c=1000; //
int main(){
int x,y,n;
int myarray[c]; // array declaration




for (x=0;x<=c;++x ) { // entering integers into array
cout << "Please enter an integer (0 to end) : " << endl ;

cin >> y ;
myarray[x] = y;
if (y==0)
{

break; // stops if 0 is entered
}

}

cout << "The unsorted array is " <<endl ;// write out unsorted array
for (n=y;n<=x;x++){


cout<< "element"<< myarray[n] << '\n';

}

}

any help is much appriciated
solved by messing about still not sure what i was doing wrong though so any comments would still be of great help
well first of all in this line of code

for (x=0;x<=c;++x ) { // entering integers into array

c here is 1000 and you used it to declare the size of your array.
If you iterate through that loop till it satisfies the condition then in this line of code

myarray[x] = y;

will actually end up being

myarray[1000] = y;

and since the size of your array is 1000, then the valid indices would be 0 - 999. So your program will crash at that point.

Secondly, the main reason why your program isn't printing out the elements of the array correctly is because of this.

1
2
3
4
cout << "The unsorted array is " << endl ;// write out unsorted array
for (n=y;n<=x;x++){
    cout<< "element"<< myarray[n] << '\n';
}


In the initialization part of your loop you have n = y. y here is equal to 0 if and only if you used it to break out from the loop that reads in the integers. However if you didn't type in 0 and filled it up with 1000 non-zero integers then your program will have a serious problem, because then you can't guarantee that y == 0, So your starting index may actually be an invalid array index like say -5. It would be better to just do n = 0 instead.

Next, you have the condition part of your loop which is n <= x. Here x would be the number of iterations your first loop stopped on. Then finally on the increment part of your loop you have x++, which means x will be increasing by 1 every time. If you notice n never changes so you got an infinite loop over there because n will never be less than x because x keeps getting larger.

So when it reaches this part

cout<< "element"<< myarray[n] << '\n';

it would print out the value inside myarray[0], but since n never changes it just keeps printing that out continuously. I hope that explains what's going on in your program and helps you fix it correctly. ^_^
Last edited on
Topic archived. No new replies allowed.