0% found this document useful (0 votes)
26 views31 pages

M5 Arrays

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views31 pages

M5 Arrays

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Programming in C

Module 5
Arrays

1
Introduction to Arrays
. A collection of variable data
 Same name
 Same type
 Contiguous block of memory
. Can manipulate or use
 Individual variables or
 ‘List’ as one entity

Celsius
temperatures:
I’ll name it c.
Type is int.
2
Introduction to Arrays
. Used for lists of like items
 Scores, speeds, weights, etc.
 Avoids declaring multiple simple variables
. Used when we need to keep lots of values in memory
 Sorting
 Determining the number of scores above/below the
mean
 Printing values in the reverse order of reading
 Etc.

3
Declaring Arrays
. General Format for declaring arrays
<data type> <variable> [<size>];
. Declaration
 Declaring the array  allocates memory
 Static entity - same size throughout program
. Examples
Type is int.
Name is c.

4
Defined Constant as Array Size
. Use defined/named constant for array size
 Improves readability
 Improves versatility
 Improves maintainability
. Examples:

5
Powerful Storage Mechanism
. Can perform subtasks like:
 "Do this to i-th indexed variable"
where i is computed by program
 "Fill elements of array scores from user input"
 "Display all elements of array scores“
 “Sort array scores in order”
 “Determine the sum or average score”
 "Find highest value in array scores"
 "Find lowest value in array scores"

6
Accessing Array Elements
. Individual parts called many things:
. Elements of the array
. Indexed or
subscripted variables
. To refer to an element:
 Array name and subscript or in
 Format: arrayname[subscript]
. Zero based
 c[0] refers to c0, c sub zero
the first element of array c

7
Accessing Array Elements
. Example

. Note two uses of brackets:


. In declaration, specifies SIZE of array
. Anywhere else, specifies a subscript/index

8
Accessing Array Elements
. Example
 Given the declaration

 We reference elements of scores by

scores [0]

scores [1]

… subscript/index

scores [11]

9
Accessing Array Elements
. Size, subscript need not be literal constant
. Can be named constant or expression

10
Major Array Pitfall
. Array indexes go from 0 through size-1!
. C will 'let' you go out of the array’s bounds
. Unpredictable results – may get segmentation fault
. Compiler will not detect these errors!
. Up to programmer to 'stay in bounds‘
?

11
for-loops with Arrays
. Natural counting loop
 Naturally works well 'counting thru' elements
of an array
. General form for forward direction
 for (subscript = 0; subscript < size; subscript++)
. General form for reverse direction
 for (subscript = size-1; subscript >= 0; subscript--)

12
for-loops with Arrays Examples

Score 1 is 56 Score 12 is 87
Score 2 is 52 Score 11 is 97
Score 3 is 80 Score 10 is 86
Score 4 is 74 Score 9 is 80
... ...
Score 12 is 87 Score 1 is 56

13
Uses of Defined Constant
. Use everywhere size of array is needed
. In for-loop for traversal:

. In calculations involving size:

. When passing array a function:

14
Uses of Defined Constant
. Use everywhere size of array is needed
. In for-loop for traversal:

. In calculations involving size:

. When passing array a function:

14
Exercise: Array of counters
• Suppose you took a telephone survey to discover how people felt about a
particular television show and you asked each respondent to rate the show
on a scale from 1 to 10, inclusive. After interviewing 5,000 people, you
accumulated a list of 5,000 numbers. Now, you want to analyze the results.
• One of the first pieces of data you want to gather is a table showing the
distribution of the ratings: you want to know how many people rated the
show a 1, how many rated it a 2, and so on up to 10.
• You want to develop a program to count the number of responses for each
rating.
response
ratingCounters

++

0 1 2 9 10

15
Exercise: Array of counters
#include <stdio.h>
int main (void) {
int ratingCounters[11], i, response;
for ( i = 1; i <= 10; ++i )
ratingCounters[i] = 0;
printf ("Enter your responses\n");
for ( i = 1; i <= 20; ++i ) {
scanf ("%i", &response);
if ( response < 1 || response > 10 )
printf ("Bad response: %i\n", response);
else
++ratingCounters[response];
}
printf ("\n\nRating Number of Responses\n");
printf ("------ -------------------\n");
for ( i = 1; i <= 10; ++i )
printf ("%4i%14i\n", i, ratingCounters[i]);
return 0;
}
16
Exercise: Fibonacci numbers
// Program to generate the first 15 Fibonacci numbers
#include <stdio.h>
int main (void)
{
int Fibonacci[15], i;
Fibonacci[0] = 0; // by definition
Fibonacci[1] = 1; // ditto
for ( i = 2; i < 15; ++i )
Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1];
for ( i = 0; i < 15; ++i )
printf ("%i\n", Fibonacci[i]);
return 0;
}

17
Exercise: Prime numbers
• An improved method for generating prime numbers involves the notion that
a number p is prime if it is not evenly divisible by any other prime number
• Another improvement: a number p is prime if there is no prime number
smaller than its square root, so that it is evenly divisible by it

If you can find a


Is p the next
primes[i] < sqrt(p)
prime number
that divides evenly
here ?
p, than p is not
prime
primes

2 3 5 7 11

0 1 2

primeIndex
18
Exercise: Prime numbers
#include <stdio.h>
#include <stdbool.h>
// Modified program to generate prime numbers
int main (void) {
int p, i, primes[50], primeIndex = 2;
bool isPrime;
primes[0] = 2;
primes[1] = 3;
for ( p = 5; p <= 50; p = p + 2 ) {
isPrime = true;
for ( i = 1; isPrime && p / primes[i] >= primes[i]; ++i )
if ( p % primes[i] == 0 )
isPrime = false;
if ( isPrime == true ) {
primes[primeIndex] = p;
++primeIndex;
} }
for ( i = 0; i < primeIndex; ++i )
printf ("%i ", primes[i]);
printf ("\n");
return 0;
19 }
Sum & Average Example
. Verify positive count before computing average
 Protects against division by zero

20
Extremes
. Techniques:
 Assume first is extreme
 Compare others to current extreme
 Replace extreme when finding new extreme

21
Extremes: Find Maximum Example

22
Initializing Arrays
. Arrays can be initialized at declaration

. Size cannot be variable or named constant


. Equivalent to

23
Auto-Initializing Arrays
. If fewer values than size supplied:
. Fills from beginning
. Fills 'rest' with zero of array base type
. Declaration

. Performs initialization

24
Auto-Initializing Arrays
. If array size is left out
. Declares array with size required based on number of
initialization values
. Example:

. Allocates array scores with size of 3

25
Multidimensional Arrays
. Arrays with more than one dimension
 Declaration: Additional sizes each enclosed in brackets
. Two dimensions
 Table or ‘array of arrays’

 Requires two subscripts – row and column

26
Initializing
Multidimensional
. Nested lists
 Unspecified values set to zero
. 2D Example:

27
Three-dimensional Visualization

28
Multidimensional Array Parameters
. Must specify size after first dimension

29
Programming in C

Module 5
Arrays

THE END

30

You might also like