Facing runtime error during this code

#include <bits/stdc++.h>
using namespace std;

int main()
{
int i,n;
int count=0;
int j=0;

cin>>n;
int arr[n];

for(i=1;i<=n;i++)
{
    
    if(n%i==0)
    {
        arr[j]=i;
        j++;
        count++;
        
    }
}

cout<<count<<endl;
for(i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}

return 0;

}

1 Like

This is the reason as array size can’t be a variable

If you want to make an array of n size where n is a variable then you can use


int *a = new int[n];

@chetan06 With recent C/C++ versions, we can also

declare an array of user specified size`

1 Like

Don’t know whether you were in hurry or not…but reason is quite simple…
in the loop statement indexing is problem according to your code you are accessing arr[n] i.e. (n+1)th element of array (remember indexing is always 0 based in cpp), and since you’ve allocated memory for n elements only it’s showing runtime error.
I guess it must be a SIGSEGV runtime error(it is caused due to invalid memory access).
Hope it helped! Cheers!

1 Like