C Tutorial/Array/Array Initializing
Initialize the elements of array to the even integers from 2 to 20
<source lang="cpp">#include <stdio.h>
- define SIZE 10
int main() {
int s[ SIZE ]; int j; for ( j = 0; j < SIZE; j++ ) { s[ j ] = 2 + 2 * j; } for ( j = 0; j < SIZE; j++ ) { printf( "%7d%13d\n", j, s[ j ] ); } return 0;
}</source>
0 2 1 4 2 6 3 8 4 10 5 12 6 14 7 16 8 18 9 20
Initializing an array in declaration
<source lang="cpp">#include <stdio.h>
- define SIZE 12
int main() {
int a[ SIZE ] = { 1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45 }; int i; int total = 0; for ( i = 0; i < SIZE; i++ ) { total += a[ i ]; } printf( "Total of array element values is %d\n", total ); return 0;
}</source>
Total of array element values is 383
Initializing an array using for loop
<source lang="cpp">#include <stdio.h> int main() {
int n[ 10 ]; int i; /* initialize elements of array n to 0 */ for ( i = 0; i < 10; i++ ) { n[ i ] = 0; } printf( "%s%13s\n", "Element", "Value" ); for ( i = 0; i < 10; i++ ) { printf( "%7d%13d\n", i, n[ i ] ); } return 0;
}</source>
Element Value 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0