Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

pls fix my code cant get desired output..

+2 votes
asked Oct 7, 2022 by Arshpreet (140 points)
/*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 Answer

+1 vote
answered Oct 10, 2022 by Peter Minarik (86,130 points)

I've fixed your code.

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. ;)

I've also formatted your code, your input and output as well.

#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;
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...