Introduction to C Programming Branching and Looping
If statements and while loops in C both rely on the idea of Boolean expressions, as they do in Pascal. In C, however, there is no Boolean type: You use plain integers instead. The integer value 0 in C is false, while any other integer value is true.
Here is a simple translation from Pascal to C. First, the Pascal code:
The C translation looks very similar, but there are some important differences, which we will discuss next.
Notice that = in Pascal became == in C. This is a very import 15515q1619p ant difference, because C will accept a single = when you compile, but will behave differently when you run the program. The and in Pascal becomes && in C. Also note that z=1; in C has a semicolon, that C drops the then, and that the Boolean expression must be completely surrounded by parentheses.
The following chart shows the translation of all boolean operators from Pascal to C:
Pascal |
C |
< |
< |
> |
> |
<= |
<= |
>= |
>= |
<> | |
and |
&& |
or | |
not |
The == sign is a problem because every now and then you may forget and type just =. Because integers replace Booleans, the following is legal in C:
if a is anything other than 0, the code that blah blah blah represents gets executed. Suppose you take the following Pascal statement:
and incorrectly translate it to C as:
In C, this statement means "Assign b to a, and then test a for its Boolean value." So if a becomes 0, the if statement is false; otherwise, it is true. The value of a changes as well. This is not the intended behavior (although this feature is useful when used correctly), so be careful with your = and == conversions.
While statements are just as eay to translate. For example, the following Pascal code:
in C becomes:
C also provides a "do-while" structure to replace Pascal's "repeat-until," as shown below:
The for loop in C is somewhat different from a Pascal for loop, because the C version is simply a shorthand way of expressing a while statement. For example, suppose you have the following code in C:
You can convert this into a for loop as follows:
Note that the while loop contains an initialization step (x=1 ), a test step (x<10), and an increment step (x++ ). The for loop lets you put all three parts onto one line, but you can put anything into those three parts. For example, suppose you have the following loop:
You can place this into a for statement as well:
It is confusing, but it is possible. The comma operator lets you separate several different statements in the initialization and increment sections of the for loop (but not in the test section). Many C programmers like to pack a lot of information into a single line of C code. I think it makes the code harder to understand, so I break it up.
only prints out one value because of the semicolon after the for statement.
|