Is this possible or im just stupid c++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Is this possible or im just stupid c++

include<iostream> using namespace std; int n, i; int main(){ cin>>n; int arr[n]; for(i=1;i<=n;i++) arr[i]=i; cout<<arr[i]<<endl; } }

5th Oct 2018, 1:19 PM
Salt MyMan
Salt MyMan - avatar
4 Answers
+ 8
You had an extra closing curly brace like Jerid told. Secondly, array indexes starts from 0 and you need to change the condition i < n like Anna said. Lastly, this code will work fine here in CPG because it take all inputs before compilation so, you can create an array of n size but this code will not work in other compilers. It's because array is created on the compilation time so you need to define the size of array before code compilation. If you need to create array in that way you need to create a dynamic array, and then it's size can be defined on the runtime. I would suggest you to use vectors instead of dynamic arrays as vectors are much more easy to use.
5th Oct 2018, 2:43 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 2
You should change the for loop to for i=0; i < n. If n is 5, the array has 5 elements and the index of the last item is 4. With the for loop you try to access the sixth element (index 5). Also I think that not all compilers will allow you to create an array with n elements if n is just a normal variable (and not a constant).
5th Oct 2018, 1:49 PM
Anna
Anna - avatar
+ 1
It is possible, but your program currently has one opening curly bracket and two closing brackets. You just need to add a curly bracket after your for loop parameters.
5th Oct 2018, 1:29 PM
Jerid Derply
Jerid Derply - avatar
+ 1
thank you
6th Oct 2018, 3:00 PM
Salt MyMan
Salt MyMan - avatar