How to output contents of array

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;
}
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
array subscripts are always like this:

for array int iArray[N] you can access iArray[0] through iArray[N-1]

1
2
3
4
5
int iCount[10] = {0,1,2,3,4,5,6,7,8,9};
for(int idx = 0; idx < 10; idx++) // array subscript will mirror array value 0..9
{
  cout << iCount[idx];
}
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;
}
see in texans for loop he initilized the the idx value as int in the for loop
Some basic understanding of arrays and indexes.

when you want to create an array of a known size and initialize the array to 0:
 
int a[10] = {0};

when you want to access an element at position 5:
 
int p = a[5];

when you want to set the value of an array at position 7:
 
a[7] = 12;

when you want to set the value of the array at position i to the value of i:
 
a[i] = i;

when you want to print the array at position i:
 
cout<<a[i];

this:
1
2
int i;
int a[]={i};


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

 
int a[10] = {0};


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.
Topic archived. No new replies allowed.