Code:
#include <stdio.h>
main()
{
int x;
int array[20];
for(int x=0; x<20; x++)
cout<<array[x];
}
1) 'cout<<' is defined in <iostream>, so you have to #include <iostream> not <stdio.h>. In addition, the modern rules of C++ require that the standard header file names not end in ".h".
2) It's
int main() ---> not main()
and main() should have a return statement. Here is the program template all beginners should use:
Code:
#include <iostream>
using namespace std;
int main()
{
//Your code here
return 0;
}
3) Always initialize your variables. That means set them to a value when you declare them, for example:
If you don't know what value to set them to, then set them to 0. Otherwise, they can contain random junk values. To set all the elements of an array to 0, do this:
Code:
int array[20] = {0};
4) Your array: array[20] is really like 20 variables: array[0], array[1], array[2].....array[19]. The numbers 0,1, 2,.....19 are called the index positions. For a variable to have a value, you have to "assign" the variable a value:
array[0] = 10;
array[15] = 3;
5) For-loops can be used with great effect with arrays. For-loops have a variable that changes with each loop:
Code:
for(int i=0; i <10; i++)
{
}
'i' increases by one after every loop. You can also make the index position of an array a variable:
array[ i];
As 'i' changes in the for-loop, it will change the index position in the array. In the for-loop, 'i' is initially set to 0, which corresponds to the first index position in an array(arrays start at index position 0--not index position 1). After the first loop,'i' is increased by 1 and then the loop executes again. The second time through the loop the int i = 0 part is skipped--that only executes the first time through the loop. As 'i' counts upwards, array[ i] will change from array[0] to array[1] to array[2], etc.
It's very important to remember that since arrays start at 0, an array of size 20 will have index positions 0-19, and therefore array[20] is undefined.