0

I wrote a program of Insertion sort in c++ but output screen does not showing any Statement.I am facing this problem in few another program.

This is the code:

#include<iostream>
using namespace std;
int main()
{
    int n;
    int arr[n];

    cout<<"Enter the number of the element of the Array:";
    cin>>n;

    cout<<"Enter the element of the Array:";
    for(int i=0;i<n;i++){
        cin>>arr[i];
    }

    for(int i=0;i<n;i++){
        int current=arr[i];
        int j=i-1;
        while(arr[j]>current && j>=0){
            arr[j+1]=arr[j];
            j--;
        }
        arr[j+1]=current;
    }

    for(int i=0;i<n;i++){
        cout<<arr[i]<<" ";
    }cout<<endl;
    return 0;
}
2
  • 5
    int n; int arr[n]; is undefined behavior (not to mention, that it is non standard C++, due to arr being a VLA). Value of n is indeterminate at the point of array arr creation, and reading it alone (not even using to create an array with it) is undefined behavior. Commented Jan 21, 2021 at 15:36
  • It should not even compile... Commented Jan 21, 2021 at 15:45

2 Answers 2

2

You are using the value of n before it has a value. Change your code to this

int n;          // n does not have a value
cout<<"Enter the number of the element of the Array:";
cin>>n;         // n gets value here
int arr[n];     // n is used here

You cannot use any variable before it has a value. That's a fundamental rule of C++.

Sign up to request clarification or add additional context in comments.

2 Comments

You can, but you really shouldn't... :-)
Even this rewrite still relies on a nonstandard extension of C++, variable-length arrays. Perhaps an std::vector would be appropriate.
1

You cannot creat variable C-style arrays during run time.

You should either create them with the new operator or switch to STL containers like std::vector.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.