| vichu99 (10) | |
|
Hi, how do you with an iteration put the numbers into an array in order to print out the contents of the array? #include <iostream> #include <cmath> using namespace std; int main(){ int i; int a[]={i}; for(i=1; i<10; i++){ int a[]={i};} cout <<a[i]; int b; cin >> b; } | |
|
|
|
| Max Edgar (37) | |
|
you could do two different loops for(i=1;i<10;i++) { a[i]=i; cout<<a[i]; } maybe something like that, im a little rusty tho | |
|
|
|
| Texan40 (446) | |||
|
array subscripts are always like this: for array int iArray[N] you can access iArray[0] through iArray[N-1]
| |||
|
|
|||
| vichu99 (10) | |
|
How do you initialize the array? There is the error: Line 10: warning: 'i' is used uninitialized in this function #include <iostream> #include <cmath> using namespace std; int main(){ int i; int a[]={i}; //line 10 for(i=1;i<10;i++) { a[i]=i; cout<<a[i]; } int b; cin >> b; } | |
|
|
|
| Max Edgar (37) | |
| see in texans for loop he initilized the the idx value as int in the for loop | |
|
|
|
| pogrady (410) | |||||||||||||||
|
Some basic understanding of arrays and indexes. when you want to create an array of a known size and initialize the array to 0:
when you want to access an element at position 5:
when you want to set the value of an array at position 7:
when you want to set the value of the array at position i to the value of i:
when you want to print the array at position i:
this:
...is not very good. Remember that when c++ creates a predefined type, if you do not initialize the value, what was in that memory location previously stays there. So, in essence, its filled with crap. The second line copies what is in the location i to the location a. You now have two copies of crap. Arrays start at position 0, not 1. If you want a 10 member array, you would declare
but to access this array, you would start at 0 and loop through until 9. If you went to 10, you would step outside of the array and cause a segmentation fault, which is bad. | |||||||||||||||
|
|
|||||||||||||||