notes5

Notes5

Info iconThis preview shows page 1. Sign up to view the full content.

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

Unformatted text preview: Arrays • New topic: ARRAYS – Reading for this week: CHAPTER 6 Arrays • Arrays – – – – – – – Structures of related data items Group of consecutive memory locations Same name and type Name Type of array Number of elements Examples: int b[ 3 ]; float myArray[ 27 ]; a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] -12 23 4 15 -1 53 0 -7 • Array • When defining arrays, specify • Defining multiple arrays of same type int c[ 5 ], x[ 12 ]; Arrays • Array elements – – – Consider the array defined by: int c[ n ]; The elements of c are: c[ 0 ], c[ 1 ],…, c[ n-2 ], c[ n-1 ] First element is c[ 0 ], 2nd element is c[ 1 ], nth element is c[ n-1 ] • Defining and referring to array elements – – – Specify array name and position number Array elements can be treated like normal variables Example: c[ 0 ] = 3; c[ 1 ] = 5; printf( “%d %d”, c[ 0 ], c[ 1 ] ); Arrays • Defining array elements – – Initializers • int n[ 5 ] = { 1, 0, -2, 5, 7 }; If not enough elements, rightmost elements become 0 • int m[ 5 ] = { 1, 2 }; is the same as int m[ 5 ] = { 1, 2, 0, 0, 0 }; • int p[ 3 ] = { 0 }; → all elements 0 – – If too many elements are defined, a syntax error is produced If size is omitted, initializers determine it • int r[ ] = { 1, 0, 3 }; – 3 initializers, therefore 3 elements Arrays Example #1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 /* initializing an array */ #include <stdio.h> int main() { int n[ 10 ]; int m[ 10 ]; int i; /* n is an array of 10 integers */ /* m is an array of 10 integers */ /* counter */ /* initialize elements of the array */ for( i = 0 ; i <= 9 ; i++ ) { n[ i ] = 2*i; m[ i ] = 3*i + 1; } /* end for */ printf( "\n%3s%11s%11s%11s\n", "i", "n[i]", "m[i]", "n[i]+m[i]" ); for( i = 0 ; i <= 9 ; i++ ) { printf( "%3d%11d%11d%11d\n", i, n[i], m[i], m[i]+n[i] ); } /* end for */ return 0; /* indicate successful termination */ } /* end main */ Arrays Example #1 - Output % a.out i 0 1 2 3 4 5 6 7 8 9 % n[i] 0 2 4 6 8 10 12 14 16 18 m[i] 1 4 7 10 13 16 19 22 25 28 n[i]+...
View Full Document

This note was uploaded on 03/02/2009 for the course ENGR 3 taught by Professor Ben-yaakov during the Fall '08 term at UCSB.

Ask a homework question - tutors are online