# arrays - Arrays Array Group of consecutive memory locations...

This preview shows pages 1–4. Sign up to view the full content.

1 1 Arrays 2 Arrays • Array – Group of consecutive memory locations – Same name and type • To refer to an element, specify – Array name – Position number • Format: arrayname [ position number ] – First element at position 0 n element array named c : c[0] , c[1] ... c[n – 1] 3 Name of array (Note that all elements of this array have the same name, c ) Position number of the element within array c c[6] -45 6 0 72 1543 -89 0 62 -3 1 6453 78 c[0] c[1] c[2] c[3] c[11] c[10] c[9] c[8] c[7] c[5] c[4] 4 Array Elements • Array elements are like normal variables c[0] = 3; printf( "%d", c[0] ); • We can perform operations in subscript. e.g . If x equals 3 c[5-2] == c[3] == c[x] c[x+1] == c[4] c[x-1] == c[2]

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 5 Declaring Arrays • When declaring arrays, specify – Name – Type of array – Number of elements arrayType arrayName[ numberOfElements ]; – Examples: int c[10]; float myArray[3284]; • Declaring multiple arrays of same type – Format similar to regular variables – Example: int b[100], x[27]; 6 Examples Using Arrays • Initializers int n[5] = { 1, 2, 3, 4, 5 }; – If not enough initializers, rightmost elements become 0 int n[5] = { 0 } • All elements 0 – If too many a syntax error is produced syntax error – C arrays have no bounds checking • If size omitted, initializers determine it int n[ ] = { 1, 2, 3, 4, 5 }; – 5 initializers, therefore 5 element array 7 Initializing an Array #include <stdio.h> int main( void ) { int n[100], i; for (i=0; i < 100; i++) n[i] = i; for (i=0; i < 100; i++) printf(“Element %d has value %d.\n”,i, n[i]); return 1; } 8 Examples Reading values into an array int i, x[100]; for (i=0; i < 100; i=i+1) { printf("Enter an integer: "); scanf("%d",&x[i]); } Summing up all elements in an array int sum = 0; for (i=0; i<=99; i=i+1) sum = sum + x[i];
3 9 Examples (contd.) • Shifting the elements of an array to the left.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 04/30/2008 for the course C CMPE 150 taught by Professor Tuna during the Spring '08 term at Boğaziçi University.

### Page1 / 6

arrays - Arrays Array Group of consecutive memory locations...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online