Arrays

Sequential collection of same data type variables.

 

Declared by use of [square brackets]: data type array Name[array size] ;

 

Values in the array are referred to as elements, and ALWAYS START FROM ZERO!

 

int myArray[10] ;  //declares an array called myArray that can contains 10 elements of the int data type

 

Defined by assiging values, separated by a comma, within {curly braces}:

 

int myArray[10] = {2, 3, 7, 12, 14, 17, 42, 63, 70, 99} ; //must have exact number of elements

 

int myArray[] = {3, 13, 1, 56, 33} ; // array will be automatically sized to hold the number of elements defined

 

Single values can be defined by assigning the value to the specific element number, starting from zero!

 

myArray[6] = 21 ;

 

Specific elements can be accessed by assigning an array element to a variable

 

int myVar = myArray[4] ;

 

Or they can be used just on their own

 

printf("The value of the element in array position 5 is %d n", myArray[4]) ;

 

#include <stdio.h>

int main() {

	int myArray[10] ; //declare a 10 element blank array

	for (int i = 0; i < 10; i++) { //10 step itterative loop

		myArray[i] = i + 20 ; //assign a value of i + 20 the element

		printf("Array element %d has a value of %d n", i, myArray[i] ) ;
	}

	return 0;
}

Leave a Reply