# Arrays - x Finding largest smallest max = x[0 the largest...

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

Arrays

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

View Full Document
What is an Array? An array is a set of contiguous variables Each variable is the same type (i.e., same size, same encoding) The array has a name Individual variables do not have a name The individual variables can be referenced using “array indexing”
Example int x[10]; // an array of 10 ints int k = 0; while (k < 10) { x[k] = 0; k = k + 1; } Arrays are indexed using integers between 0 and size-1

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

View Full Document
Loop/Array idioms Find the sum of values in an array: int sum = 0; int k = 0; while (k < size) { sum = sum + x[k]; k = k + 1; } Note “< size” in loop guard I assume size is a variable declared somewhere and initialized to be the number of variables in the array

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

View Full Document

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.

Unformatted text preview: x . Finding largest, smallest max = x[0]; // the largest value max_pos = 0; // the position of the value int k = 1; // no need to check zero again. while (k < size) { if (x[k] > max) { max = x[k]; max_pos = k; } k = k + 1; } Find first occurrence of v int k = 0; int v_pos; // in case we don’t find it while (k < size && x[k] != v) { k = k + 1; } if (k < size) { v_pos = k; } else { v_pos = -1; } Count occurrences of v int count = 0; int k = 0; while (k < size) { if (x[k] == v) { count = count + 1; } k = k + 1; } Histogram int scores[101]; // initialize to zero k = 0; while (k < size) { scores[x[k]] = scores[x[k]] + 1; k = k + 1; }...
View Full Document

{[ snackBarMessage ]}

### Page1 / 8

Arrays - x Finding largest smallest max = x[0 the largest...

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

View Full Document
Ask a homework question - tutors are online