My project is to create a bubble sort that puts the numbers in ascending order.
My code works but the text "Please enter 6 numbers in any order" repeats 5 times before the text "sorted" can someone please explain why this happens and how to fix it?
#include <iostream>
using namespace std;
int n[9];
int i, j;
int main()
{
for (i=0;i,i<=5; i++)
{
cout << "Please enter 6 numbers in any order:";
cin >> n[i];
}
for (i=0; i<=4; i++)
{
for (j=i+1;j<=5; j++)
{
int temp;
things that are inside the scope of loops tend to repeat ;D
Look carefully where your "Please enter 6 numbers..." statement is and perhaps move it somewhere else. Also, in the future, please indent and use [code] ... [/code]
I have tried to move the statement before the for and after it. When I move it before the statement the program closes instead of displaying the sorted values this doesn't fix when I add another getchar();. When I move it after the statement still displays 5 times. I'm probably just being dumb but if you could help me a little more that would be greatly appreciated.
@Caesar est mortuus
Don't know where you tried moving the line requesting the numbers input, but here is where it should be. ( Shown in code )
I adjusted the input to 10 numbers, since you already had set it to 9.
#include <iostream>
usingnamespace std;
int n[10];
int i, j;
int main()
{
char ch; // Use to keep console open by requesting an input
cout << "Please enter 10 numbers in any order:" << endl;
for (i = 0;i < 10; i++)
{
// cout << "Please enter 6 numbers in any order:"; // Moved to before i loop
cin >> n[i];
}
for (i=0; i < 9; i++)
{
for (j=i+1;j< 10; j++)
{
int temp;
if(n[i] > n[j])
{
temp=n[i];
n[i]=n[j];
n[j]=temp;
}
}
}
cout << endl << "Sorted "; // Added a space after the word, for readability
for(i=0;i< 10;i++)
{
cout << n[i];
if(i!=9)
cout << ", ";// comma only if another number is to be printed
}
cout << endl;
cin >> ch;
//getchar(); Just need a cin to the char, above
}