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;
}
  • 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. – Algirdas Preidžius Jan 21 '21 at 15:36
  • It should not even compile... – U. W. Jan 21 '21 at 15:45

2 Answers2

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++.

john
  • 85,011
  • 4
  • 57
  • 81
  • You can, but you really shouldn't... :-) – U. W. Jan 21 '21 at 15:43
  • Even this rewrite still relies on a nonstandard extension of C++, [variable-length arrays](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard). Perhaps an `std::vector` would be appropriate. – Nathan Pierson Jan 21 '21 at 15:44
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.

tboschi
  • 124
  • 11