# pls fix my code cant get desired output..

/*sorted array 2 ds*/
#include <iostream>

using namespace std;

int main()
{
int i,j,num,temp,arr[10];
cout<<"enter the number of elements";
cin>>num;
cout<<"enter the elements";
for(i=0;i<num;i++)
{
cin>>arr[i];
}
for(i=0;i<num-1;i++)
{
temp=arr[i];
j=i-1;

while((temp<arr[j])&&(j>=0))
{
arr[j+1]=arr[j];
j=j-1;
}
arr[j+1]=temp;
}
cout<<"\nSorted elements";
for(i=0;i<num;i++)
{
cout<<arr[i]<<" ";
}
return 0;
}

+1 vote
answered Oct 10 by (63,140 points)

The main problem is that in your 2nd loop you should not stop your iteration at num - 1, but num instead.

There's another problem: you can only support 10 numbers. What if the user enters more numbers?

You should initialize your array to the desired size after you know how many elements you have. This, however, does not work in MS Windows. But since you're using C++, you could utilize the std::vector<T> type here.

I've also noticed that you check if j >= 0 after you've already read the element of arr[j]. You potentially read outside from the array. It's better to check first and read later. ;)

```#include <iostream>

using namespace std;

int main()
{
cout << "Enter the number of elements: ";
int num;
cin >> num;
int arr[num]; // Setting the size properly. Does not work in Windows. Use std::vector<int> instead?!
cout << "Enter the elements, one per line." << endl;
for (int i = 0; i < num; i++)
{
cin >> arr[i];
}
for (int i = 0; i < num; i++) // num - 1 is not enough, we want to end at num
{
int temp = arr[i];
int j = i - 1;

while (j >= 0 && temp < arr[j]) // Check for valid index first before reading the array from a potential invalid index
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
cout << "Sorted elements:";
for (int i = 0; i < num; i++)
{
cout << " " << arr[i];
}
cout << endl;
return 0;
}```