Transcript Document

CS1061 C Programming Lecture 6: Operators and Expressions

A. O’Riordan, 2004

Two Short Programs

We begin with some example programs to illustrate what we have covered so far.

Problem 1: Write a program that takes in a value for the radius of a circle, computes the area and outputs this to the terminal.

Problem 2: Write a program that takes in a distance in miles and yards, converts this to kilometers and outputs the metric distance to the terminal.

These problems are straightforward so we jump rightaway to the code.

Problem 1

/* calculate the area of a circle */ #include int main(){ float radius; float area; printf("Please enter the length of the radius: "); scanf ("%f", &radius); area = 3.14*radius*radius; printf("The area is %f\n", area); return 0; }

Problem 2

#include #define yardsTomiles 1760.0 #define milesTokms 1.609 void main(){ int miles, yards; float kilometers; printf(“Enter number of miles and yards: “); scanf(“%f %f”,&miles, &yards); } kilometers = milesTokms * (miles + yards/yardsTomiles); printf(“%d miles and %d yards is %f kilometers”, miles, yards, kilometers);

Assignment Operators

We have seen the assignment statement already. Assignment operators abbreviate assignment expressions.

c = c + 3;

can be abbreviated as

c += 3;

assignment operator using the addition Examples of other assignment operators:

d -= 4 (d = d - 4) e *= 5 (e = e * 5) f /= 3 (f = f / 3) g %= 9 (g = g % 9)

Expressions

In C almost everything is an expression. For example, assignment = “returns” the value of its right-hand side. As a “side-effect” it also sets the value of the left-hand variable. Thus, int x; x = 12; sets the value of example: x to 12 . Since the assignment is also an expression, we can combine several assignments as illustrated in the following int x, y, z; x = y = z = 12;

Expression Associativity

The first assignment assigns This is the value that is then assigned to to-left associativity. We could rewrite this statement to make the order of execution explicit.

z the value of its right-hand side, 12.

y, etc. Note the right x= (y = (z = 12))); Statements may be split across multiple lines in a file. This is so because the new-line character is considered to be a white-space character, the same as the space and tabulation characters. This feature can aid readability.

The null statement is also valid C, but of little use: ; /* The null statement */

Increment/Decrement Operators

Increment operator ( ++ ) can be used instead of

c+=1

Decrement operator (

--

) can be used instead of

c-=1

Pre-increment (++c)  Operator is used before the variable/expression i.e. variable is changed before the expression it is in is evaluated.

Post-increment (c++)  Operator is used after the variable/expression, i.e. expression evaluated before the variable is changed.

The pre-decrement and post-decrement work analogously.

Examples:

Increment/Decrement Operators (2)

If c equals 5, then printf( "%d", ++c); prints 6 and printf( "%d", c++); prints 5 If c equals 5, then ++c; evaluates to 6 and c++; also evaluates to 6.

When variable not in an expression pre-incrementing and post incrementing have the same effect.

Logical Operators

Logical operators are useful in compound expressions.

example: print value of x if x is less than 10 and is also an even number: if ((x < 10) && (x%2 == 0)) printf(“The value of x is %d\n”, x); The && is a logical operator. It takes two Boolean expressions as operands and returns a Boolean value, i.e. either true or false.

Another example with negation (! operator): if (!false) printf(“Always displayed”);

Logical Operators(2)

In C, non-zero expressions evaluate to true (and 0 evaluates to false). Thus you will often see code like this: if (my_int){ /* do something here */ } which is equivalent to: if (my_int != 0){ /* do something here */ }

Logical Operators(3)

&& (logical AND)  Returns true if both conditions are true || ( logical OR)  Returns true if either of its conditions are true ! (logical NOT, logical negation )   Reverses the truth/falsity of its condition ! is a unary operator, meaning has only one operand These are all useful as conditions in loops, e.g.: Expression Result true && false true || false !false

false true true

Truth Tables

The meaning of logical expressions can be given in a truth table: opd1 false true false true opd2 false false true true AND false false false true OR false true true true NOT (uses only op1) true false true false

Comma Operator

The comma operator is used for specifying two expressions, which are evaluated in turn, left to right, e.g.: count = 0, max = 0; is equivalent is count = 0; max = 0; We will see an important use for this later.

Note on expressions with operators

Multiple operators cannot be combined in a single expression. For example the follow line of code would cause a compiler error: /* check if x is between 0 and 1.0 */ if (0 <= x <= 1.0) /* illegal - causes error */ The correct way to implement this is: if (0 <= x && x <= 10)

Operator Precedence

All of the operators have a defined precedence. Each row in the table below is a different precedence level. The first row gives the operators with the highest precedence. the second the second-most, etc. (Associativity on far right) . -> ++ - * / [] not % () –(unary) *(de-ref) & sizeo

f left ight left

+ << >> < <= == != & ^ | and or ?: > >=

left left left left left left left left left right