1585665441lesson 5 Arrays and Loops

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 16

5.

Basic Program Control

"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.

In this section you will learn

 How to use simple arrays.


 How to use for, while, and do...while loops to execute statements multiple
times.
 How you can nest program control statements: nesting for statements, nesting
while statements and nested loops.

5.1: Arrays: The Basics


The for Statement and Arrays
Before we cover the for statement, let's take a short detour and learn the basics of
arrays. (See , "Numeric Arrays," for a complete treatment of arrays.) The for
statement and arrays are closely linked in C, so it is difficult to define one without
explaining the other. To help you understand the arrays used in the for statement
examples to come, a quick treatment of arrays follows.

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 */

5.2: Controlling Program Execution


Program Control Statements
The default order of execution in a C program is top-down. Execution starts at the
beginning of the main() function and progresses, statement by statement, until the end
of main() is reached. However, this order is rarely encountered in real C programs.
The C language includes a variety of program control statements that enable you to
control the order of program execution. You have already learned how to use C's
fundamental decision operator, the if statement, so let's explore three additional
control statements you will find useful.

5.2.1: The for Statement


The for Loop
The for statement is a C programming construct that executes a block of one or more
statements a certain number of times. It is sometimes called the for loop because
program execution typically loops through the statement more than one time. You've
seen a few for statements used in programming examples earlier in this course. Now
you're ready to see how the for statement works.

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.

5 Finally, the expression increment is evaluated. As you might guess,


increment usually changes the value of the variable used in the start
and test expressions, for example i++. Then, execution returns to
Step 2 with the new variable value.

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.

Listing 5.1: Demonstration of a Simple for Statement


Code 1: /* LIST0601.c: Listing 5.1 */
2: /* Demonstrates a simple for statement */
3:
4: #include <stdio.h>
5:
6: int count;
7:
8: int main(void) {
9: /* Print the numbers 1 through 20. */
10:
11: for (count = 1; count <= 20; count++)
12: printf("\n%d", count);
13: return 0;
14: }

Output 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Description Line 4 includes the standard input/output header file. Line 6


declares a type int variable, named count, that will be used in
the for loop.

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.

The second step in executing this for statement is the evaluation


of the condition count <= 20. Because count was just
initialized to 1, you know that it is less than 20, so the statement
in the for command, the printf(), is executed. <BR
After executing the printing function, the increment expression,
count++, is evaluated. This adds 1 to count, making it 2.

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 Counter Variable


The for statement is frequently used, as in the previous example, to "count up,"
incrementing a counter from one value to another. You also can use it to "count
down," decrementing, rather than incrementing, the counter variable.
for (count = 100; count > 0; count--)
You also can "count by" a value other than 1.
for (count = 0; count < 1000; count += 5)

Omitting the Initialization (start) Expression


The for statement is quite flexible. For example, you can omit the initialization
expression if the test variable has been initialized previously in your program. (You
must still use the semicolon separator, however, as shown.)
count = 1;
for (; count < 1000; count++)
The initialization expression need not be an actual initialization; it can be any valid C
expression. Whatever it is, it is executed once when the for statement is first reached.
The following prints a statement, "Now sorting the array..."
count = 1;
for (printf("Now sorting the array...") ; count < 1000;
count++)
/* Sorting statements here */

Omitting the increment Expression


You can also omit the increment expression, performing the updating in the body of
the for statement. The semicolon, again, must be included.
Example

To print the numbers from 0 to 99, you could write


for (count = 0; count < 100;)
printf("%d", count++);

The test Expression


The test expression that terminates the loop can be any C expression. As long as it
evaluates as true (nonzero), the for statement continues to execute. You can use C's
logical operators to construct complex test expressions.
Example
Using a Null Statement
You can follow the for statement with a null statement, enabling all the work to be
done in the for statement itself. Remember, the null statement is a semicolon alone on
a line.
Example

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.

Using the Comma Operator


, "Statements, Expressions, and Operators," mentioned that C's comma operator is
most often used in for statements. You can create an expression by separating two
subexpressions with the comma operator. The two subexpressions are evaluated (in
left-to-right order), and the entire expression evaluates to the value of the right
subexpression. By using the comma operator, you can make each part of a for
statement perform multiple duty.
Example

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! */

Listing 5.2: Demonstration of Nested for Statements


Code 1: /* LIST0602.c: Listing 5.2 */
2: /* Demonstrates nesting two for statements */
3:
4: #include <stdio.h>
5:
6: void draw_box(int row, int column);
7:
8: int main(void) {
9: draw_box(8, 35);
10: return 0;
11: }
12:
13: void draw_box(int row, int column) {
14: int col;
15: for(; row > 0; row--) {
16: for(col = column; col > 0; col--)
17: printf("X");
18:
19: printf("\n");
20: }
21: }

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.

In this listing, a function prototype for draw_box() is declared


on line 6. This function takes two type int variables, row and
column, which contain the dimensions of the box of Xs to be
drawn. In line 9, main() calls draw_box() and passes the value 8
as the row and the value 35 as the column.

Looking closely at the draw_box() function, you might see a


couple things you don't readily understand. The first is why the
local variable col was declared. The second is why the second
printf() in line 19 was used. Both of these will become clearer
after looking at the two for loops.

Line 15 starts the first for loop. The initialization is skipped


because the initial value of row was passed to the function.
Looking at the condition, you see that this for loop is executed
until the row is 0. On first executing line 15, row is 8; therefore,
the program continues to line 16.

Line 16 contains the second for statement. Here the passed


parameter, column, is copied to a local variable, col, of type int.
The value of col is 35 initially (the value passed via column),
and column retains its original value. Because col is greater than
0, line 17 is executed, printing an X. col is then decremented
and the loop continues.

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.

5.2.3: The while Statement


The while Loop
The while statement, also called the while loop, executes a block of statements as long
as a specified condition is true.
Syntax
The while statement has the following form:
while (expression)
statements
Parameters
The expression is any C expression, and statements is a single or compound C
statement.

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.

Listing 5.3: Demonstration of a Simple while Statement


Code 1: /* LIST0603.c: Listing 5.3 */
2: /* Demonstrates a simple while statement */
3:
4: #include <stdio.h>
5:
6: int count;
7:
8: int main(void) {
9: /* Print the numbers 1 through 20. */
10:
11: count = 1;
12:
13: while (count <= 20) {
14: printf("\n%d", count);
15: count++;
16: }
17: return 0;
18: }

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.

In line 11, count is initialized to 1. Because the while statement


does not contain an initialize section, you must take care of
initializing any variables before starting the while.

Line 13 is the actual while statement, and it contains the same


condition statement from Listing 5.1, count <= 20. In the
while loop, line 15 takes care of incrementing count.

What do you think would happen if you forgot to put line 15 in


this program? Your program would not "know" when to stop
because count would always be 1, which is always less than 20.

while Versus for


You might have noticed that a while statement is essentially a for statement without
the initialization (start) and increment components. Thus,
for (; test ;)
is equivalent to
while (expression)
Because of this equivalence, anything that can be done with a for statement can also
be done with a while statement. When you use a while statement, any needed
initialization must first be performed in a separate statement, and the updating must be
performed by a statement that is part of the while loop.

Preference: Use a for Statement


When initialization and updating are required, most experienced C programmers
prefer to use a for statement rather than a while statement. This preference is based
primarily on source code readability. When you use a for statement, the
initialization (start), test, and increment expressions are located together and
are easy to find and modify. With a while statement, the initialization and update
expressions are located separately and may be less obvious.

5.2.4: Nesting while Statements


Nesting
Just like the for and if statements, while statements can also be nested.
Listing 5.4 shows an example of nested while statements. Although this is not the best
use of a while statement, the example does present some new ideas.
DON'T use the following convention if it is not necessary.
while(x)
Instead use
while(x != 0)
Although both work, the second is clearer when debugging the code. When compiled,
these produce virtually the same code.
DO use the for statement instead of the while statement if you need to initialize and
increment within your loop. The for statement keeps the initialization, condition, and
increment statements all together. The while statement does not.

Listing 5.4: Demonstration of Nested while Statements


Code 1: /* LIST0604.c: Listing 5.4 */
2: /* Demonstrates nested while statements */
3:
4: #include <stdio.h>
5:
6: int array[5];
7:
8: int main(void) {
9: int ctr = 0,
10: nbr = 0;
11:
12: printf("This program prompts you to enter 5 "
13: "numbers\n");
14: printf("Each number should be from 1 to 10\n");
15:
16: while (ctr < 5) {
17: nbr = 0;
18: while (nbr < 1 "" nbr > 10) {
19: printf("\nEnter number %d of 5: ", ctr + 1);
20: scanf("%d", &nbr);
21: }
22:
23: array[ctr] = nbr;
24: ctr++;
25: }
26:
27: for(ctr = 0; ctr < 5; ctr++)
28: printf("\nValue %d is %d", ctr + 1,
29: array[ctr]);
30: return 0;
31: }

Output This program prompts you to enter 5 numbers


Each number should be from 1 to 10
Enter number 1 of 5: 3
Enter number 2 of 5: 6
Enter number 3 of 5: 3
Enter number 4 of 5: 9
Enter number 5 of 5: 2
Value 1 is 3
Value 2 is 6
Value 3 is 3
Value 4 is 9
Value 5 is 2

Description Like previous listings, lines 1 – 2 contain a comment with a


description of the program, and line 4 contains a #include
statement for the standard input/output header file. Line 6
contains a declaration for an array (named array) that can hold 5
integer values. The function main() contains two additional
local variables, ctr and nbr (lines 9 and 10). Notice that these
variables are initialized to zero at the same time they are
declared. Also notice that the comma operator is used as a
separator at the end of line 9, allowing nbr to be declared as an
int without restating the int type command. Stating declarations
in this manner is a common practice for many C programmers.
Lines 12 – 14 print messages stating what the program does and
what is expected of the user. Lines 16 – 25 contain the first
while command and its statements. Lines 18 – 21 also contain a
nested while loop with its own statements that are all part of the
outer while.

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.

The inner loop is a good use of a while statement. Only the


numbers from 1 to 10 are valid, so until the user enters a valid
number, there is no point continuing the program. Lines 18 – 21
prevent continuation. This while statement states that while the
number is less than 1 or while it is greater than 10, the program
should print a message to enter a number, and then get the
number.

Lines 27 – 29 print the values that are stored in array. Notice


that because the while statements are done with the variable ctr,
the for command can reuse it. Starting at zero and incrementing
by one, the for loops five times, printing the value of ctr plus
one (because the count started at zero), and printing the
corresponding value in array.

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.

5.2.5: The do...while Loop


The do...while Loop
C's third loop construct is the do...while loop, which executes a block of statements as
long as a specified condition is true. The do...while loop tests the condition at the end
of the loop rather than at the beginning as is done by the for loop and the while loop.
Syntax
The structure of the do...while loop is as follows:
do
statements
while (expression);
Parameters
expression is any C expression, and statements is a single or compound C statement.

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.

Listing 5.5: Demonstration of a Simple do...while Loop


Code 1: /* LIST0605.c: Listing 5.5 */
2: /* Demonstrates a simple do...while statement */
3:
4: #include <stdio.h>
5:
6: int get_menu_choice(void);
7:
8: int main(void) {
9: int choice;
10:
11: choice = get_menu_choice();
12:
13: printf("You chose Menu Option %d", choice);
14: return 0;
15: }
16:
17: int get_menu_choice(void) {
18: int selection = 0;
19:
20: do {
21: printf("\n");
22: printf("\n1 - Add a record");
23: printf("\n2 - Change a record");
24: printf("\n3 - Delete a record");
25: printf("\n4 - Quit");
26: printf("\n");
27: printf("\nEnter a selection:");
28:
29: scanf("%d", &selection);
30:
31: }while (selection < 1 "" selection > 4);
32:
33: return selection;
34: }

Output 1 - Add a record


2 - Change a record
3 - Delete a record
4 - Quit

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.

The main() function (lines 8 – 15) adds nothing to what you


already know. All of main() could have been written into one
line.

printf("You chose Menu Option %d",


get_menu_choice());

If you were to expand this program, and act on the selection,


you would need the value returned by get_menu_choice(), so it
is wise to assign the value to a variable (such as choice).

Lines 17 – 34 contain get_menu_choice(). This function


displays a menu on the screen (lines 21 – 27), and then gets a
selection. Because you have to display a menu at least once to
get an answer, it is appropriate to use a do...while loop. In the
case of this program, the menu is displayed until a valid choice
is entered.

Line 31 contains the while part of the do...while statement and


validates the value of the selection, appropriately named
selection. If the value entered is not between 1 and 4, the menu
is redisplayed and the user is prompted for a new value. When a
valid selection is entered, the program continues to line 33,
which returns the value in the variable selection.

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.

5.4: Practice Examples


* Practice Examples
Now, take some time to perform the following exercises. They will provide you with
experience in using what you've learned.

* 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

Controlling Program Execution


C has three loop statements that control program execution: for, while, and do...while.
Each of these constructs enables your program to execute a block of statements zero,
one, or more than one time, based on the condition of certain program variables.
Many programming tasks are well served by the repetitive execution allowed by these
loop statements.
The for, while and do...while Statements
Although all three can be used to accomplish the same task, each is different. The for
statement enables you to initialize, evaluate, and increment all in one command. The
while statement operates as long as a condition is true. The do...while statement
always executes its statements at least once and continues to execute them until a
condition is false.
Nested Loops
Nesting is the placing of one command within another. C allows for the nesting of any
of its commands. Nesting the if statement was demonstrated on , "Statements,
Expressions, and Operators." In this unit, the for, while, and do...while statements
were nested.

You might also like