Sams Teach Yourself C in 24 Hours (29 page)

BOOK: Sams Teach Yourself C in 24 Hours
9.69Mb size Format: txt, pdf, ePub

4. Write a program to display negative integers in hex format along with their signed int equivalents.

5. Given an angle of 30 degrees, write a program to calculate its sine and tangent values.

6. Write a program to calculate the non-negative square root of 0x19A1.

13 067231861x CH10 4.10.2000 11:02 AM Page 155

HOUR 10

Controlling Program

Flow

It is harder to command than to obey.

—F. Nietzsche

In Hour 7, “Working with Loops,” you learned to use the while, do-while, and for statements to do the same things over and over. These three statements can be grouped into the category of
looping
statements that are used for
control flow
in C.

In this lesson you’ll learn about the statements that belong to another group of the control flow statements—
conditional branching
(or
jumping
), such as

• The if statement

• The if-else statement

• The switch statement

• The break statement

• The continue statement

• The goto statement

13 067231861x CH10 4.10.2000 11:02 AM Page 156

156

Hour 10

Always Saying “
if
…”

If life were a straight line, it would be very boring. The same thing is true for programming. It would be too dull if the statements in your program could only be executed in the order in which they appear.

In fact, an important task of a program is to instruct the computer to
branch
(that is, jump) to different portions of the code and work on different jobs whenever the specified conditions are met.

However, in most cases, you don’t know in advance what will come next. What you do know is that something is bound to happen if certain conditions are met. Therefore, you can just write down tasks and conditions in the program. The decisions of when to perform the tasks are made by the conditional branching statements.

In C, the if statement is the most popular conditional branching statement; it can be used to evaluate the conditions as well as to make the decision whether the block of code controlled by the statement is going to be executed.

The general form of the if statement is

if (expression) {

statement1;

statement2;

.

.

.

}

Here expression is the conditional criterion. If expression evaluates to a nonzero value, the statements inside the braces ({ and }), such as statement1 and statement2, are executed. If expression evaluates to a value of zero, the statements are skipped.

Note that the braces ({ and }) form a block of statements that is under the control of the if statement. If there is only one statement inside the block, the braces can be omitted.

The parentheses (( and )), however, must be always used to enclose the conditional expression.

For instance, the following expression:

if (x > 0.0)

printf(“The square root of x is: %f\n”, sqrt);

tells the computer that if the value of the floating point variable x is greater than 0.0

(that is, positive), it should calculate the square root of x by calling the sqrt() function, and then print out the result. Here the conditional criterion is the relational expression 13 067231861x CH10 4.10.2000 11:02 AM Page 157

Controlling Program Flow

157

x > 0.0, which evaluates to a value of 1 (logically true) if x is greater than zero, and evaluates to a value of 0 (logically false) if x is less than or equal to zero.

Listing 10.1 gives you another example of using the if statement.

LISTING 10.1

Using the if Statement in Decision Making

1: /* 10L01.c Using the if statement */

2: #include

3:

4: main()

5: {

6: int i;

7:

8: printf(“Integers that can be divided by both 2 and 3\n”);

9: printf(“(within the range of 0 to 100):\n”);

10

10: for (i=0; i<=100; i++){

11: if ((i%2 == 0) && (i%3 == 0))

12: printf(“ %d\n”, i);

13: }

14: return 0;

15: }

After 10L01.exe, the executable of the program in Listing 10.1, is created and run, the following output is displayed on the screen:

Integers that can be divided by both 2 and 3

OUTPUT
(within the range of 0 to 100):

0

6

12

18

24

30

36

42

48

54

60

66

72

78

84

90

96

As you see in Listing 10.1, line 6 declares an integer variable, i. Lines 8 and 9

ANALYSIS
print out two headlines. Starting in line 10, the for statement keeps looping 101

times.

13 067231861x CH10 4.10.2000 11:02 AM Page 158

158

Hour 10

Within the for loop, the if statement in lines 11 and 12 evaluates the logical expression (i%2 == 0) && (i%3 == 0). If the expression evaluates to 1 (that is, the value of i can be divided by both 2 and 3 completely), the value of i is displayed on the screen by calling the printf() function in line 12. Otherwise, the statement in line 12 is skipped.

Note that the braces ({ and }) are not used because there is only one statement under the control of the if statement.

The result shown on the screen gives all integers within the range of 0 to 100 that can be evenly divided by both 2 and 3.

The
if-else
Statement

In the if statement, when the conditional expression evaluates to a nonzero value, the computer will jump to the statements controlled by the if statement and execute them right away. If the expression evaluates to a value of zero, the computer will ignore those statements controlled by the if statement.

You will often want the computer to execute an alternate set of statements when the conditional expression of the if statement evaluates to logically false. To do so, you can use another conditional branching statement in C—the if-else statement.

As an expansion of the if statement, the if-else statement has the following form: if (expression) {

statement1;

statement2;

.

.

.

}

else {

statement_A;

statement_B;

.

.

.

}

If expression evaluates to a nonzero value, the statements controlled by if, including statement1 and statement2, are executed. However, if expression evaluates to a value of zero, statement_A and statement_B following the else keyword are executed instead.

The program in Listing 10.2 shows how to use the if-else statement.

13 067231861x CH10 4.10.2000 11:02 AM Page 159

Controlling Program Flow

159

LISTING 10.2

Using the if-else Statement

1: /* 10L02.c Using the if-else statement */

2: #include

3:

4: main()

5: {

6: int i;

7:

8: printf(“Even Number Odd Number\n”);

9: for (i=0; i<10; i++)

10: if (i%2 == 0)

11: printf(“%d”, i);

12: else

13: printf(“%14d\n”, i);

14:

15: return 0;

10

16: }

The following result is obtained by running the executable file 10L02.exe: Even Number Odd Number

OUTPUT

0 1

2 3

4 5

6 7

8 9

Line 6 of Listing 10.2 declares an integer variable, i. The printf() function in
ANALYSIS
line 8 displays a headline on the screen.

The integer variable i is initialized in the first expression of the for statement in line 9.

Controlled by the for statement, the if-else statement in lines 10–13 is executed 10

times. According to the if-else statement, the printf() call in line 11 prints out even numbers if the relational expression i%2 == 0 in line 10 evaluates to 1 (logically true). If the relational expression evaluates to 0 (logically false), the printf() call controlled by the else keyword in line 13 outputs odd numbers to the standard output.

Because the if-else statement is treated as a single statement, the braces { and } are not needed to form a block of statements under the for statement. Likewise, there are no braces used in the if-else statement because the if and else keywords each control a single statement in lines 11 and 13 respectively.

Note that the minimum width of 14 is specified in the printf() function in line 13, so the output of the odd numbers is listed to the right side of the even numbers, as you can see in the output section. The program in Listing 10.2 checks numbers in a range of 0 to 9, and shows that 0, 2, 4, 6, and 8 are even numbers, and 1, 3, 5, 7, and 9 are odd ones.

13 067231861x CH10 4.10.2000 11:02 AM Page 160

160

Hour 10

Nested
if
Statements

As you saw in the previous sections, one if statement enables a program to make one decision. In many cases, a program has to make a series of related decisions. For this purpose, you can use nested if statements.

Listing 10.3 demonstrates the usage of nested if statements.

LISTING 10.3

Using Nested if Statements

1: /* 10L03.c Using nested if statements */

2: #include

3:

4: main()

5: {

6: int i;

7:

8: for (i=-5; i<=5; i++){

9: if (i > 0)

10: if (i%2 == 0)

11: printf(“%d is an even number.\n”, i);

12: else

13: printf(“%d is an odd number.\n”, i);

14: else if (i == 0)

15: printf(“The number is zero.\n”);

16: else

17: printf(“Negative number: %d\n”, i);

18: }19: return 0;

20: }

After running the executable file 10L03.exe, I obtain the following output: Negative number: -5

OUTPUT

Negative number: -4

Negative number: -3

Negative number: -2

Negative number: -1

The number is zero.

1 is an odd number.

2 is an even number.

3 is an odd number.

4 is an even number.

5 is an odd number.

Listing 10.3 contains a for loop, starting in line 8 and ending in line 18.

ANALYSIS
According to the expressions of the for statement in line 8, any tasks controlled by the for statement are executed up to 11 times.

13 067231861x CH10 4.10.2000 11:02 AM Page 161

Controlling Program Flow

161

First, a decision has to be made based on the evaluation of the relational expression i > 0

in the if statement of line 9. The i > 0 expression is used to test whether the value of i is positive or anything else (negative numbers including zero.) If the expression evaluates to 1, the computer jumps to the second (that is, nested) if statement in line 11.

Note that line 11 contains another relational expression, i%2 == 0, which tests whether the integer variable i is even or odd. Therefore, the second decision of displaying even numbers or odd numbers has to be made according to the evaluation of the second relational expression, i%2 == 0. If this evaluation yields 1, the printf() call in line 11

prints out an even number. Otherwise, the statement in line 13 is executed, and an odd number is shown on the screen.

The computer branches to line 14 if the i > 0 expression from line 9 evaluates to 0; that is, if the value of i is not greater than 0. In line 14, another if statement is nested within
10

an else phrase, and the relational expression i == 0 is evaluated. If i == 0 evaluates to logically true, which means i does contain the value of zero, the string The number is zero is displayed on the screen. Otherwise, the value of i must be negative, according to the previous evaluation of the i > 0 expression in line 9. The statement in line 17 then outputs the negative number to the standard output.

As you can see in the example, the value of i is within the range of 5 to -5. Thus, -5, -4,

-3, -2, and -1 are printed out as negative numbers. Then a message is printed when i is zero, and then the odd numbers 1, 3, and 5, as well as the even numbers 2 and 4 are printed out.

The
switch
Statement

In the last section, you saw that nested if statements are used when there are successive, related decisions to be made. However, the nested if statements can become very complex if there are many decisions that need to be made. Sometimes, a programmer will have problems just keeping track of a series of complex nested if statements.

Fortunately there is another statement in C, the switch statement, which you can use to make unlimited decisions or choices based on the value of a conditional expression and specified cases.

Other books

Her Heart's Desire by Lisa Watson
All Smoke No Fire by Randi Alexander
Hear Me by Skye Warren
A Feral Darkness by Doranna Durgin
To Love and Protect by Tamra Rose
Children of the Old Star by David Lee Summers
Guns 'N' Tulips by Kristine Cayne