Programming in C

(Barry) #1

106 Chapter 7 Working with Arrays


Program 7.4 Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

The expression
p / primes[i] >= primes[i]
is used in the innermost forloop as a test to ensure that the value of pdoes not exceed
the square root of primes[i].This test comes directly from the discussions in the previ-
ous paragraph. (You might want to think about the math a bit.)
Program 7.4 starts by storing 2 and 3 as the first two primes in the array primes.This
array has been defined to contain 50 elements, even though you obviously don’t need
that many locations for storing the prime numbers.The variable primeIndexis initially
set to 2 , which is the next free slot in the primesarray. A forloop is then set up to run
through the odd integers from 5 to 50. After the Boolean variable isPrimeis set to
true, another forloop is entered.This loop successively divides the value of pby all of
the previously generated prime numbers that are stored in the array primes.The index
variable istarts at 1 because it is not necessary to test any values of pfor divisibility by
primes[0](which is 2 ).This is true because our program does not even consider even
numbers as possible primes. Inside the loop, a test is made to see if the value of pis
evenly divisible by primes[i],and if it is, then isPrimeis set false.The forloop con-
tinues execution so long as the value of isPrimeis trueandthe value of primes[i]
does not exceed the square root of p.
After exiting the forloop, a test of the isPrimeflag determines whether to store the
val ue of pas the next prime number inside the primesarray.
After all values of phave been tried, the program displays each prime number that has
been stored inside the primesarray.The value of the index variable ivaries from 0
through primeIndex - 1because primeIndexwas always set pointing to the nextfree
slot in the primesarray.

Initializing Arrays


Just as you can assign initial values to variables when they are declared, so can you assign
initial values to the elements of an array.This is done by simply listing the initial values
of the array, starting from the first element.Values in the list are separated by commas and
the entire list is enclosed in a pair of braces.
The statement
int counters[5] = { 0, 0, 0, 0, 0 };
declares an array called countersto contain five integer values and initializes each of
these elements to zero. In a similar fashion, the statement
int integers[5] = { 0, 1, 2, 3, 4 };
sets the value of integers[0]to 0 ,integers[1]to 1 ,integers[2]to 2 , and so on.
Free download pdf