Sams Teach Yourself C in 24 Hours (24 page)

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

Q How does a
for
loop work?

A
There are three expressions in the for statement. The first field contains an initializer that is evaluated first and only once before the iteration. The second expression the conditional expression that must evaluate to nonzero (logical true) before the statements controlled by the for statement are executed. If the conditional 10 067231861x CH07 4.10.2000 11:01 AM Page 119

Working with Loops

119

expression evaluates to a nonzero (true) value, which means the specified condition is met, one iteration of the for loop is carried out. After each iteration, the third expression is evaluated, and then the second field is evaluated again. This process with the second and third expressions is repeated until the conditional expression evaluates to zero (logical false).

Q Can the
while
statement end with a semicolon?

A
By definition, the while statement does not end with a semicolon. However, it’s
7

legal in C to put a semicolon right after the while statement like this: while(expression);, which means there is a null statement controlled by the while statement. Remember that the result will be quite different from what you expect if you accidentally put a semicolon at the end of the while statement.

Q If two loops are nested together, which one must finish first, the inner loop or
the outer loop?

A
The inner must finish first. Then the outer loop will continue until the end, and then start another iteration if its specified condition is still met.

Workshop

To help you solidify your understanding of this hour’s lesson, you are encouraged to try to answer the quiz questions and finish the exercises provided in the workshop before you move to next lesson. The answers and hints to the questions and exercises are given in Appendix D, “Answers to Quizzes and Exercises.”

Quiz

1. Can the following while loop print out anything?

int k = 100;

while (k<100){

printf(“%c”, k);

k++;

}

2. Can the following do-while loop print out anything?

int k = 100;

do {

printf(“%c”, k);

k++;

} while (k<100);

3. Do the following two for loops have the same number of iterations?

for (j=0; j<8; j++);

for (k=1; k<=8; k++);

10 067231861x CH07 4.10.2000 11:01 AM Page 120

120

Hour 7

4. Is the following for loop

for (j=65; j<72; j++) printf(“%c”, j);

equivalent to the following while loop?

int k = 65;

while (k<72)

printf(“%c”, k);

k++;

}

Exercises

1. What is the difference between the following two pieces of code?

for (i=0, j=1; i<8; i++, j++)

printf(“%d + %d = %d\n”, i, j, i+j);

for (i=0, j=1; i<8; i++, j++);

printf(“%d + %d = %d\n”, i, j, i+j);

2. Write a program that contains the two pieces of code shown in Exercise 1, and then execute the program. What are you going to see on the screen?

3. Rewrite the program in Listing 7.1. This time, you want the while statement to keep looping until the user enters the character K.

4. Rewrite the program shown in Listing 7.2 by replacing the do-while loop with a for loop.

5. Rewrite the program in Listing 7.6. This time, use a while loop as the outer loop, and a do-while loop as the inner loop.

11 067231861x CH08 4.10.2000 11:02 AM Page 121

HOUR 8

Using Conditional

Operators

Civilization advances by extending the number of important operations we
can perform without thinking about them.

—A. N. Whitehead

In Hour 6, “Manipulating Data,” you learned about some important opera-

tors in C, such as the arithmetic assignment operators, the unary minus operator, the increment and decrement operators, and the relational operators. In this lesson you’ll learn more operators that are very important in C programming, including

• The sizeof operator

• Logical operators

• Bit-manipulation operators

• The conditional operator

11 067231861x CH08 4.10.2000 11:02 AM Page 122

122

Hour 8

Measuring Data Sizes

You may remember in Hour 4, “Understanding Data Types and Keywords,” I mentioned that each data type has its own size. Depending on the operating system and the C compiler you’re using, the size of a data type varies. For example, on most UNIX workstations, an integer is 32 bits long, whereas most C compilers only support 16-bit integers on a DOS-based machine.

So, how do you know the size of a data type on your machine? The answer is that you can measure the data type size by using the sizeof operator provided by C.

The general form of the sizeof operator is

sizeof (expression)

Here expression is the data type or variable whose size is measured by the sizeof operator. The sizeof operator evaluates the size, in bytes, of its operand. The operand of the sizeof operator may be a C language keyword naming a data type (such as int, char, or float), or it may be an expression which refers to a data type whose size can be determined (such as a constant or the name of a variable).

The parentheses are optional in the general form of the operator. If the expression is not a C keyword for a data type, the parentheses can be discarded. For instance, the following statement:

size = sizeof(int);

Places the size, in bytes, of the int data type into a variable named size.The program in Listing 8.1 finds the sizes of the char, int, float, and double data types on my machine.

TYPE

LISTING 8.1

Using the sizeof Operator

1: /* 08L01.c: Using the sizeof operator */

2: #include

3:

4: main()

5: {

6: char ch = ‘ ‘;

7: int int_num = 0;

8: float flt_num = 0.0f;

9: double dbl_num = 0.0;

10:

11: printf(“The size of char is: %d-byte\n”, sizeof(char));

12: printf(“The size of ch is: %d-byte\n”, sizeof ch );

13: printf(“The size of int is: %d-byte\n”, sizeof(int));

14: printf(“The size of int_num is: %d-byte\n”, sizeof int_num);

11 067231861x CH08 4.10.2000 11:02 AM Page 123

Using Conditional Operators

123

15: printf(“The size of float is: %d-byte\n”, sizeof(float));

16: printf(“The size of flt_num is: %d-byte\n”, sizeof flt_num);

17: printf(“The size of double is: %d-byte\n”, sizeof(double));

8

18: printf(“The size of dbl_num is: %d-byte\n”, sizeof dbl_num);

19: return 0;

20: }

After this program is compiled and linked, an executable file, 08L01.exe, is created. The following is the output printed on the screen after the executable is run on my machine: The size of char is: 1-byte

OUTPUT
The size of ch is: 1-byte

The size of int is: 2-byte

The size of int_num is: 2-byte

The size of float is: 4-byte

The size of flt_num is: 4-byte

The size of double is: 8-byte

The size of dbl_num is: 8-byte[ic:analysis]Line 2 in Listing 8.1 includes the header file stdio.h for the printf() function used in the statements inside the main() function body. Lines 6–9 declare a char variable (ch), an int variable (int_num), a float variable (flt_num), and a double variable (dbl_num), respectively. Also, these four variables are initialized. Note that in line 8, the initial value to flt_num is suffixed with f to specify float. (As you learned in Hour 4, you can use f or F to specify the float type for a floating-point number.)

Lines 11 and 12 display the size of the char data type, as well as the char variable ch.

Note that the sizeof operator is used in both line 11 and line 12 to obtain the number of bytes the char data type or the variable ch can have. Because the variable ch is not a keyword in C, the parentheses are discarded for the sizeof operator in line 12.

The first two lines in the output are printed out by the two statements in lines 11 and 12, respectively. From the output, you see that the size of the char data type is 1 byte, which is the same as the size of the variable ch. This is not surprising because the variable ch is declared as the char variable.

Likewise, lines 13 and 14 print out the sizes of the int data type and the int variable int_num by using the sizeof operator. You see that the size of each is 2 bytes.

Also, by using the sizeof operator, lines 15–18 give the sizes of the float data type, the float variable flt_num, the double data type, and the double variable dbl_num, respectively. The results in the output section show that the float data type and the variable flt_num have the same size (4 bytes). The sizes of the double data type and the variable dbl_num are both 8 bytes.

11 067231861x CH08 4.10.2000 11:02 AM Page 124

124

Hour 8

Everything Is Logical

Now, it’s time to learn about a new set of operators:
logical operators
.

There are three logical operators in the C language:

&&

The logical AND operator

||

The logical OR operator

!

The logical NEGATION operator

The first two, the AND and OR operators, are binary operators; that is, they both take two operands (one to the left and one to the right of the operator). The logical AND

operator (&&) is used to evaluate the truth or falsity of a pair of expressions. If either expression evaluates to 0 (that is, logically false), the operator yields a value of 0.

Otherwise, if — and only if — both operand expressions evaluate to nonzero values, the logical AND operator yields a value of 1 (logically true).

The logical OR operator (||) yields a value of 1 whenever one or both of the operand expressions evaluates to nonzero (logically true). The || operator yields 0 only if both operand expressions evaluate to 0 (false). The logical negation operator (!) is a unary operator; that is, it only takes one operand (the expression to its right). If the operand evaluates to any nonzero value, the ! operator yields 0 (logically false); only when the operand expression evaluates to 0, does the operator yield 1 (logically true).

The following three sections contain examples that show you how to use the three logical operators.

The Logical AND Operator (
&&
)

A general format of the logical AND operator is:

exp1 && exp2

where exp1 and exp2 are two operand expressions evaluated by the AND operator.

A good way to understand the AND operator is to look at a table that shows the values yielded by the AND operator depending on the possible values of exp1 and exp2. See Table 8.1, which can be called the
truth table
of the AND operator.

TABLE 8.1

The Values Returned by the AND Operator

exp1

exp2

&& Yields

nonzero

nonzero

1

nonzero

0

0

nonzero

0

0

0

0

11 067231861x CH08 4.10.2000 11:02 AM Page 125

Using Conditional Operators

125

Listing 8.2 is an example of using the logical AND operator (&&).

8

TYPE

LISTING 8.2

Using the Logical AND Operator (&&)

1: /* 08L02.c: Using the logical AND operator */

2: #include

3:

4: main()

5: {

6: int num;

7:

8: num = 0;

9: printf(“The AND operator yields: %d\n”,

10: (num%2 == 0) && (num%3 == 0));

11: num = 2;

12: printf(“The AND operator yields: %d\n”,

13: (num%2 == 0) && (num%3 == 0));

14: num = 3;

15: printf(“The AND operator yields: %d\n”,

16: (num%2 == 0) && (num%3 == 0));

17: num = 6;

18: printf(“The AND operator yields: %d\n”,

19: (num%2 == 0) && (num%3 == 0));

20:

21: return 0;

22: }

After this program is compiled and linked, an executable file, 08L02.exe, is created. The following output is displayed after the executable is run on my machine: The AND operator yields: 1

OUTPUT
The AND operator yields: 0

The AND operator yields: 0

The AND operator yields: 1

In Listing 8.2, an integer variable, num, is declared in line 6 and initialized for the
ANALYSIS
first time in line 8. Lines 9 and 10 print out the value yielded by the logical AND

operator in the following expression:

(num%2 == 0) && (num%3 == 0)

Here you see two relational expressions, num%2 == 0 and num%3 == 0. In Hour 3

“Learning the Structure of a C Program,” you learned that the arithmetic operator % can be used to obtain the remainder after its first operand is divided by the second operand.

Other books

Not a Second Chance by Laura Jardine
Holiday Fling by Victoria H. Smith
Hell's Menagerie by Kelly Gay
The Long Valley by John Steinbeck
Goodbye Isn't Forever by Blake, Melanie
The Aebeling by O'Neill, Michael
Medieval Master Warlords by Kathryn le Veque
Wars of the Irish Kings by David W. McCullough