Arrays - x . Finding largest, smallest max = x[0]; // the...

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

View Full Document Right Arrow Icon
Arrays
Background image of page 1

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

View Full DocumentRight Arrow Icon
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”
Background image of page 2
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
Background image of page 3

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

View Full DocumentRight Arrow Icon
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
Background image of page 4
Background image of page 5

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

View Full DocumentRight Arrow Icon
Background image of page 6
Background image of page 7

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

View Full DocumentRight Arrow Icon
Background image of page 8
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 &lt; size) { if (x[k] &gt; max) { max = x[k]; max_pos = k; } k = k + 1; } Find first occurrence of v int k = 0; int v_pos; // in case we dont find it while (k &lt; size &amp;&amp; x[k] != v) { k = k + 1; } if (k &lt; size) { v_pos = k; } else { v_pos = -1; } Count occurrences of v int count = 0; int k = 0; while (k &lt; size) { if (x[k] == v) { count = count + 1; } k = k + 1; } Histogram int scores[101]; // initialize to zero k = 0; while (k &lt; size) { scores[x[k]] = scores[x[k]] + 1; k = k + 1; }...
View Full Document

Page1 / 8

Arrays - x . Finding largest, smallest max = x[0]; // the...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online