Академический Документы
Профессиональный Документы
Культура Документы
CSCI 230
Arrays
Declarations
Dale Roberts, Lecturer
IUPUI
droberts@cs.iupui.edu
Dale Roberts
Arrays
Array
Group of consecutive memory locations
Same name and type, ex: an array of integers
Format:
array_name[ position number ]
c[ 0 ], c[ 1 ]...c[ n 1 ]
Example: int my_array[12]
my_array[0]= -45 value stored
my_array[0]
-45
my_array[1]
my_array[2]
my_array[3]
72
my_array[4]
1543
my_array[5]
-89
my_array[6]
my_array[7]
62
my_array[8]
-3
my_array[9]
Example:
my_array[1.5] ERROR!!
my_array[i+j] valid if i and j are integers
6453
78
Dale Roberts
Arrays (cont.)
Array elements are like normal variables
my_array[8] = -3;
scanf("%d", &my_array[8]); printf("%d",my_array[8]);
Perform operations in subscript. If x equals 3:
my_array[ 5 - 2 ] == my_array[ 3 ] == my_array[ x ]
Declaring Arrays
When declaring arrays, specify
Name
Type of array
Number of elements: arrayType
arrayName[numberOfElements];
Examples:
Dale Roberts
Arrays (cont.)
Declaring multiple arrays of same type: format similar to regular variables
Example: int b[ 100 ], x[ 27 ];
Dale Roberts
Arrays (cont.)
Initializers
int n[5] = {1, 2, 3, 4, 5};
Example: main()
{
int i, a[10]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (i=0; i<10; i++)
printf(Element: %d\n, a[i]);
}
If there are fewer initializations than elements in the array, then the
remaining elements are automatically initialized to 0.
Dale Roberts
Arrays (cont.)
Example:
#include <stdio.h>
#define SIZE 100
main()
{
int i, a[SIZE];
int sum = 0;
Dale Roberts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
1. Initialize array
2. Loop
3. Print
Program output
Element
0
1
2
3
4
5
6
7
8
9
Value
19
3
15
7
11
9
13
5
17
1
Histogram
*******************
***
***************
*******
***********
*********
*************
*****
*****************
*
Dale Roberts