1585665441lesson 5 Arrays and Loops
1585665441lesson 5 Arrays and Loops
1585665441lesson 5 Arrays and Loops
"Statements, Expressions, and Operators," covered in the previous section give you
some control over the flow of your programs. Many times, though, you need more
than just the ability to make true and false decisions. This unit introduces three new
ways to control the flow of the program.
Arrays
So far the data types and variables we've studied have held only a single value. An
array is simply a collection of values. The technical definition of an array would be
something like "an indexed group of data storage locations that have the same name
and are distinguished from each other by a subscript, or index—a number following
the variable name, enclosed in brackets." This definition will become clearer as you
continue.
Array Declarations
Like other C variables, arrays must be declared. An array declaration includes both
the data type and the size of the array (the number of elements in the array).
DON'T declare arrays with subscripts larger than you will need; it wastes memory.
DON'T forget that in C, arrays are referenced starting with subscript 0, not 1.
The statement
int data[1000];
declares an array named data that is type int and has 1,000 elements.
Array Elements
The individual elements are referred to by subscript as data[0] through data[999].
The first element is data[0]—not data[1]. (In a few other languages, such as
BASIC, the first element of an array is 1.)
Each element of this array is equivalent to a normal integer variable and can be used
the same way. The subscript of an array can be another C variable, such as in this
example:
Example
int data[1000];
int count;
count = 100;
data[count] = 12; /* The same as data[100] = 12 */
Syntax
A for statement has the following structure:
for (start; test; increment)
statements
Parameters
start, test, and increment are all C expressions, and statements is a single or compound
C statement.
Process
for (start; test; increment)
statements
When a for statement is encountered during program execution, the following events occur:
Stage Description
1 The expression start is evaluated. start is usually an assignment
statement that sets a variable to a particular value, for example i=1.
2 The expression test is evaluated. test is typically a relational
(conditional) expression, for example, i<=100.
3 If test evaluates as false (that is, as zero), the for statement
terminates, and execution passes to the first statement following
statements.
4 If test evaluates as true (that is, as nonzero), the C statement(s) in
statements are executed.
Schematic Representation
Here is a simple example. The program in Listing 5.1 uses a for statement to print the
numbers 1 through 20. You can see that the resulting code is much more compact than it
would be if a separate printf() statement were used for each of the 20 values.
Output 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Lines 11 and 12 are the for loop. When the for statement is
reached, the initial statement is executed first. In this listing, the
initial statement is count = 1. This initializes count so that it
can be used by the rest of the loop.
Next, the program loops back and checks the condition again. If
it is true, the printf() re-executes, the increment adds to count
(making it 3), and the condition is checked. This loop continues
until the condition evaluates to false, at which point the program
exits the loop and continues to the next line (line 13), which in
this listing is the return statement.
The following for statement prints the elements of an array named array[], stopping
when all elements have been printed or an element with a value of 0 is encountered.
for (count = 0; count < 1000 && array[count] != 0; count++)
printf("%d", array[count]);
You could simplify the previous for loop even further, writing it as follows. (If you
don't understand the change made to the test expression, you need to review ,
"Statements, Expressions, and Operators.")
for (count = 0; count < 1000 && array[count]; count++)
printf("%d", array[count]);
To initialize all elements of a 1,000-element array to the value 50, you could write
for (count = 0; count < 1000; array[count++] = 50)
;
In this for statement, 50 is assigned to each member of the array by the increment part
of the statement.
Imagine that you have two 1,000-element arrays, a[] and b[]. You want to copy the
contents of a[] to b[] in reverse order so that after the copy operation, b[0] =
a[999], b[1] = a[998], and so on. The following for statement does the trick:
for (i = 0, j = 999; i < 1000; i++, j--)
b[j] = a[i];
The comma operator is used to initialize two variables, i and j. It also is used to
increment part of these two variables with each loop.
5.2.2: Nesting for Statements
Nesting
A for statement can be executed within another for statement. This is called nesting.
(You saw this on , "Statements, Expressions, and Operators," with the if statement.)
By nesting for statements, some complex programming can be done.
Listing 5.2 is not a complex program, but it illustrates the nesting of two for
statements.
DON'T put too much processing in the for statement. Although you can use the
comma separator, it is often clearer to put some of the functionality into the body of
the loop.
DO remember the semicolon if you use a for with a null statement. Put the semicolon
placeholder on a separate line or place a space between it and the end of the for
statement.
for(count = 0; count < 1000; array[count] = 50) ;
/* note space! */
Output XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Description The main work of this program is accomplished on line 17.
When you run this program, 280 Xs are printed on the screen,
forming an 8 by 35 square. The program has only one command
to print an X, but it is nested in two loops.
When col is 0, the for loop ends and control goes to line 19.
Line 19 causes the printing on the screen to start on a new line.
(On , "Basic Input/Output," printing is covered in detail). After
moving to a new line on the screen, control reaches the end of
the first for loop's statements, thus executing the increment
expression, which subtracts 1 from row, making it 7. This puts
control back at line 16.
Notice that the value of col was 0 when last used. If column had
been used instead of col, it would fail the condition test because
it will never be greater than 0. Only the first line would be
printed. Take the initializer out of line 16 and change the two
col variables to column to see what actually happens.
Process
while (expression)
statements
When program execution reaches a while statement, the following events occur:
Stage Description
1 expression is evaluated.
2 If expression evaluates as false (that is, as zero), the while statement
terminates and execution passes to the first statement following
statements.
3 If expression evaluates as true (that is, as nonzero), the C
statement(s) in statements are executed.
4 Execution returns to Step 1.
Output 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Description Examine Listing 5.3 and compare it with Listing 5.1, which uses
a for statement to perform the same task.
This outer loop continues to execute while ctr is less than 5 (line
16). As long as ctr is less than 5, line 17 sets nbr to 0, lines 18 –
21 (the nested while statement) gather a number in variable nbr,
line 23 places the number in array, and line 24 increments ctr.
Then the loop starts again. Therefore, the outer loop gathers 5
numbers and places each into array, indexed by ctr.
For additional practice, there are two things you can change in
this program. The first is the values that are accepted by the
program. Instead of 1 to 10, try making it accept from 1 to 100.
You can also change the number of values that it accepts.
Currently it allows for 5 numbers. Try making it accept 10.
Process
do
statements
while (expression);
When program execution reaches a do...while statement, the following events occur:
Stage Description
1 The statements in statements are executed (at least once).
2 expression is evaluated. If it is true, execution returns to step one. If
it is false, the loop terminates.
Exit-Condition Loop
The statements associated with a do...while loop are always executed at least once.
This is because the test condition is evaluated at the end, instead of the beginning, of
the loop. In contrast, for loops and while loops evaluate the test condition at the start
of the loop, and so the associated statements are not executed at all if the test
condition is initially false.
Usage
The do...while loop is used less frequently than while and for loops. It is most
appropriate when the statement(s) associated with the loop must be executed at least
once. You could, of course, accomplish the same thing with a while loop by making
sure that the test condition is true when execution first reaches the loop. A do...while
loop probably would be more straightforward, however.
Example Program
Listing 5.5 shows an example of a do...while loop.
Enter a selection:8
1 - Add a record
2 - Change a record
3 - Delete a record
4 - Quit
Enter a selection:4
You chose Menu Option 4
Description This program provides a menu with four choices. The user
selects one of the four choices, and then the program prints the
number selected. Programs later in this course use and expand
on this concept. For now, you should be able to follow most of
the listing.
5.3: Q&A
* Questions & Answers
Here are some questions to help you review what you have learned in this unit.
* Question 1
How do I know which programming control statement to use, for, the while, or the
do...while?
* Answer
If you look at the syntax boxes provided, you can see that any of the three can be used
to solve a looping problem. Each has a small twist to what it can do, however. The for
statement is best when you know that you need to initialize and increment in your
loop. If you only have a condition that you want to meet, and you are not dealing with
a specific number of loops, while is a good choice. If you know that a set of
statements needs to be executed at least once, a do...while might be best. Because all
three can be used for most problems, the best course is to learn them all and then
evaluate each programming situation to determine which is best.
* Question 2
How deep can I nest my loops?
* Answer
You can nest as many loops as you want. If your program requires more than two
loops, however, consider using a function instead. You might find sorting through all
those braces difficult, and a function is easier to follow in code.
* Question 3
Can I nest different loop commands?
* Answer
You can nest if, for, while, do...while, or any other command. You will find that many
of the programs you try to write will require that you nest at least a few of these.
* Exercise 1
Write a declaration for an array that will hold 50 type long values.
Answer
long array[50];
* Exercise 2
Show a statement that assigns the value of 123.456 to the 50th element in the array
from exercise one.
Answer
Notice that in the following answer, the 50th element is indexed to 49. Remember that
arrays start at 0.
array[49] = 123.456;
* Exercise 3
Write a for statement to count from 1 to 100 by 3s.
Answer
int x;
for(x = 1; x <= 100; x += 3) ;
* Exercise 4
Write a while statement to count from 1 to 100 by 3's.
Answer
int x = 1;
while(x <= 100)
x += 3;
* Exercise 5
Write a do...while statement to count from 1 to 100 by 3's.
Answer
int ctr = 1;
do {
ctr += 3;
} while(ctr < 100);
Summary