Programming in C

(Barry) #1

108 Chapter 7 Working with Arrays


Program 7.5 Output
array_values[0] = 0
array_values[1] = 1
array_values[2] = 4
array_values[3] = 9
array_values[4] = 16
array_values[5] = 25
array_values[6] = 36
array_values[7] = 49
array_values[8] = 64
array_values[9] = 81

In the declaration of the array array_values, the first five elements of the array are ini-
tialized to the square of their element number (for example, element number 3 is set
equal to 3^2 or 9).The first forloop shows how this same type of initialization can be
performed inside a loop.This loop sets each of the elements 5 through 9 to the square of
its element number.The second forloop simply runs through all 10 elements to display
their values at the terminal.

Character Arrays
The purpose of Program 7.6 is to simply illustrate how a character array can be used.
However, one point is worthy of discussion. Can you spot it?

Program 7.6 Introducing Character Arrays
#include <stdio.h>

int main (void)
{
char word[] = { 'H', 'e', 'l', 'l', 'o', '!' };
int i;

for ( i = 0; i < 6; ++i )
printf ("%c", word[i]);

printf ("\n");

return 0;
}

Program 7.6 Output
Hello!
Free download pdf