# My Training Period:  xx hours

The source code for this Module is: . and the related worksheet for your practice is: .

• # Compound Assignment Operators.

#### 3.6    Relational Operators

• Used to compare expressions, asking questions such as, “is x greater than 200?” or  “is y equal to 10”.

• An expression containing a relational operator evaluates as either TRUE (1) or FALSE (0).

• C / C++ has six relational operators as shown in Table 3.5:

 Operator Symbol Means Example Equal == Is operand 1 equal to operand 2? x  == y Greater than > Is operand 1 greater than operand 2? x  >  y Less than < Is operand 1 less than operand 2? x  <  y Greater than >= Is operand 1 greater than or equal to operand 2? x  >= y Less than <= Is operand 1 less than or equal to operand 2? x  <= y Not equal != Is operand 1 not equal to operand 2? x != y Table 3.5: Relational operators
• Another simple examples:

 Expression Evaluates As Read As 5 == 1 0 (false) Is 5 equal to 1? 5 > 1 1 (true) Is 5 greater than 1? 5 != 1 1 (true) Is 5 not equal to 1? ( 5 + 10 ) == ( 3 * 5 ) 1 (true) Is (5 + 10) equal to (3 * 5)?

#### 3.6.1    Expressions And The if Statement

• Relational operators are used mainly to construct the relational expressions used in if and while statements.

• This is the introduction of the basic if statement, used to create program control statements.  Till now we only deal with the top down approach or line by line code but that is not the limitation.

• We will learn more detail about program control in program control Module.  Assume this part as an introduction.

#### 3.6.2    A Program Control Statement: An Introduction

• Modifies the order of the statement execution.

• Can cause other program statements to execute multiple times or not to execute at all, depending on the circumstances, condition imposed.

• Other type of program control includes do, for and while that will be explained in detail in another Module.

• This section introduced because many relational and logical operators are used in the expression of the program control statements.

• The most basic if statement form is:

 if ( expression )       statement(s); next_statement;
1. Evaluate an expression and directs program execution depending on the result of that evaluation.

2. If the expression evaluate as TRUE, statement(s) is executed, if FALSE, statement(s) is not executed, execution then passed to the code follows the if statement, that is the next_statement.

3. So, the execution of the statement(s) depends on the result of expression.

• if statement also can control the execution of multiple statements through the use of a compound statement or a block of code.  A block is a group of two or more statements enclosed in curly braces, { }.

• Typically, if statements are used with relational expressions, in other words, "execute the following statement(s) only if a certain condition is true".

• For example:

 if ( expression ) {           statement1;       statement2;            ...            ...       statement-n; } next_statement;
• A program example:

// demonstrates the use of the if statements

#include <stdio.h>

int main()

{

int x, y;

// input the two values to be tested

printf("\nInput an integer value for x: ");

scanf("%d", &x);

printf("Input an integer value for y: ");

scanf("%d", &y);

// test values and print result

if (x == y)

{

printf("\nx  is equal to y");

}

if (x > y)

{

printf("\nx is greater than y");

}

if (x < y)

{

printf("\nx is smaller than y");

}

printf("\n\n");

return 0;

}

#### Possible outputs:

• We can see that this procedure is not efficient.  Better solution is to use if–else statement as shown below:

 if ( expression ) statement1; else statement2; next_statement;
• The expression can be evaluated to TRUE or FALSE.  The statement1 and statement2 can be compound or a block statement.

• This is called a nested if statement.  Nesting means to place one or more C/C++ statements inside another C/C++ statement.

• A program example:

// demonstrates the use of if-else statement

#include <stdio.h>

int main()

{

int   x, y;

// input two values to be tested

printf("\nInput an integer value for x: ");

scanf("%d", &x);

printf("Input an integer value for y: ");

scanf("%d", &y);

// test the values and print result

if (x == y)

{

printf("\nx is equal to y");

}

else if (x > y)

{

printf("\nx is greater than y ");

}

else {

printf("\nx is smaller than y ");

}

printf("\n\n");

return 0;

}

#### Possible outputs:

• Keep in mind that we will learn if–else statements more detail in program controls Module.  As a pre-conclusion, there are 3 form of if statements.

Form 1:

 if ( expression ) statement1; next_statement;

Form 2:

 if ( expression ) statement1; else statement2; next_statement;

Form 3:

 if ( expression )       statement1; else if ( expression ) statement2; else  if ( … ) statement3; … … … else        statementN; next_statement;

#### 3.7    Relational Expressions

• Expression using relational operators evaluate, by definition, to a value of either FALSE (0) or TRUE (1).

• Normally used in if statements and other conditional constructions.

• Also can be used to produce purely numeric values.

• Another program example:

// demonstrates the evaluation of relational expression

#include <stdio.h>

int main()

{

int  a;

// evaluates to 1, TRUE

a =  (5 == 5);

printf ("\na = (5 == 5)\n  Then a = %d\n", a);

// evaluates to 0, FALSE

a = (5 != 5);

printf ("\na = (5 != 5)\n  Then a = %d\n", a);

// evaluates to 1 + 1, TRUE

a = (12 == 12) + (5 != 1);

printf("\na = (12 == 12) + (5 != 1)\n  Then a = %d\n", a);

return 0;

}

Output:

• x  =  5, evaluates as 5 and assigns the value 5 to x.  This is an assignment expression.

• x  ==  5, evaluates as either 0 or 1 (depending on whether x is equal to 5 or not) and does not change the value of x.  This is comparison expression.

• Consider this, the wrong usage of the assignment operator ( = ),

if(x = 5)

printf("x is equal to 5");

• The message always prints because the expression being tested by the if statement always evaluates as TRUE, no matter what the original value of x happens to be.

• Referring to the above example, the value 5 does equal 5, and true (1) is assigned to 'a'.  "5 does not equal 5" is FALSE, so 0 is assigned to 'a'.

• As conclusion, relational operators are used to create relational expression that asked questions about relationship between expressions.  The answer returned by a relational expression is a numeric value 1 or 0.

#### 3.7.1    Precedence of Relational Operators

• Similar to mathematical operators, in case when there is multiple operator expression.

• Parentheses can be used to modify precedence in expression that uses relational operators.

• All relational operators have a lower precedence than all mathematical operators.

• For example:

(x + 2 > y)

• Better written like this:

((x + 2) > y)

 Operators Relative precedence <     <=     >    >= 1 !=     == 2 Table 3.6: Precedence of the relational operators
• For example:

x == y > z      equivalent to     x == (y > z)

• Avoid using the “not equal to” operator ( != ) in an if statement containing an else, use “equal to” ( == ) for clarity.

• For example:

if(x != 5)

statement1;

else

statement2;

• So, better written as:

if(x == 5)

statement2;

else

statement1;

#### 3.8    Logical Operators

• C / C++ logical operators enable the programmer to combine 2 or more relational expressions into a single expression that evaluate as either TRUE (1) or FALSE (0).

 Operator Symbol Example AND && expression1 && expression2 OR || expression1 || expression2 NOT ! !expression1 Table 3.7:  Logical operators

 Expression Evaluates As (expression1  &&   expression2) True (1) only if both expression1 and expression2 are true; false (0) otherwise. (expression1 || expression2) True (1) if either expression1 or expression2 is true; false (0) only if both are FALSE. (! expression1) False (0) if expression1 is true; true (1) if expression1 is true. Table 3.8: Evaluation of the logical expressions
• These expressions use the logical operators to evaluate as either TRUE or FALSE depending on the TRUE/FALSE value of their operands.

• For example:

 Expressions Evaluates As (5 == 5)  && (6  !=  2) True (1) because both operands are true (5 > 1) || (6 < 1) True (1) because one operand is true (2 == 1)  &&  (5 == 5) False (0) because one operand is false ! (5 == 4) True (1) because the operand is false NOT (FALSE)  = TRUE Table 3.9: Examples of logical expressions
• For AND and  OR operator are summarized in the following Tables:

 Operand1 Operand2 Output 0 0 0 ( F ) 0 1 0 ( F ) 1 0 0 ( F ) 1 1 1 ( T ) Table 3.10:  Logical AND Operation

 Operand1 Operand2 Output 0 0 0 ( F ) 0 1 1 ( T ) 1 0 1 ( T ) 1 1 1 ( T ) Table 3.11:  Logical OR Operation

#### 3.8.1    TRUE And FALSE Values

• For relational expression, 0 is FALSE, 1 is TRUE

• Any numeric value is interpreted as either TRUE or FALSE when it is used in a C / C++ expression or statement that is expecting a logical (true or false) value.

• The rules:

A value of 0, represents FALSE.

Any non zero (including negative numbers) value represents TRUE.

• For example:

x  =  125;

if(x)

printf("%d", x)

#### 3.8.2    Precedence of Logical Operators

• C / C++ logical operators also have a precedence order.

• ! is same level with unary mathematical operators ++ and -- and it has higher precedence than all relational operators and all binary mathematical operators.

• && and || operators lower than all mathematical and relational operators.

• Parentheses also can be used to modify evaluation order when using the logical operators.

• When the parentheses are absent, the results are determined by operator precedence then the result may not be desired.

• When parentheses are present, the order in which the expressions are evaluated changes.

• Try the following program example and study the output and the source code.

#include <stdio.h>

int main()

{

// initialize variables and note that c is not less than d, which is one of the conditions to test for

// therefore the entire expression should be evaluated as false

int  a = 5, b = 6, c = 5, d = 1;

int  x;

// evaluate the expression without parentheses

x = a < b || a < c && c < d;      // Form 1

printf("Given expression:\n");

printf("x = a < b || a < c && c < d\n");

printf("Without parentheses the expression evaluates as %d", x);

// evaluate the expression with parentheses

x = (a < b || a < c) && (c < d);  // Form 2

printf("\n\nWith parentheses:\n");

printf("x = (a < b || a < c) && (c < d)\n");

printf("With parentheses the expression evaluates as %d\n", x);

return 0;

}

Output:

• From the above example, we are given 3 conditions:

1. Is a less than b?  ,               a < b    // Condition 1

2. Is a less than c?  ,               a < c    // Condition 2

3. Is c less than d?  ,               c < d    // Condition 3

• Condition 1 logical expression that evaluate as true if condition 3 is true and if either condition 1 or condition 2 is true.  But this do not fulfill the specification because the && operator has higher precedence than ||, the expression is equivalent to a < b || (a < c && c < d) and evaluates as true if (a < b) is true, regardless of whether the relationships (a < c) and (c < d) are true.

#### 3.9    Compound Assignment Operators

• For combining a binary mathematical operation with an assignment operation.

• There is shorthand method.

• For example:

x  =  x  +  5;

x  += 5;

• The general notation is:

expression1 = expression1 operator expression2

• The shorthand method is:

expression1 operator  =  expression2

• The examples:

 Expression Equivalent x *=  y x  =  x  *  y y -= z + 1 y  =  y – (z + 1) a  /  =  b a  =  a  /  b x  +=  y / 8 x = x  +  (y / 8) y  %=  3 y  =  y  %  3 Table 3.12: Examples of compound assignment operator
• Another example:

If             x = 12;

Then,

z = x += 2;

z =  x = x + 2

=   12 + 2

=   14

• Program example:

#include <stdio.h>

int main()

{

int a = 3, b = 4;

printf("Initially: a = 3, b = 4\n");

printf("\na += b ---> a = a + b = %d\n", a+=b);

printf("a last value = %d\n", a);

printf("\na *= b ---> a = a * b = %d\n", a*=b);

printf("a last value = %d\n", a);

printf("\na -= b ---> a = a - b = %d\n", a-=b);

printf("a last value = %d\n", a);

printf("\na/=b ---> a = a / b = %d\n", a/=b);

printf("a last value = %d\n", a);

printf("\na-=(b+1)---> a = a - (b + 1) = %d\n", a-=(b+1));

printf("a last value = %d\n", a);

return 0;

}

#### 3.10    The Conditional Operators

• The C / C++ only ternary operator, it takes 3 operands.

• The syntax:

Expression1  ?  expression2  :  expression3;

• If expression1 evaluates as true (non zero), the entire expression evaluated to the value of expression2.  If expression1 evaluates as false (zero), the entire expression evaluated to the value of expression3.

• For example:

x  =  y  ?  1  :  100;

Assign value 1 to x if y is true.

Assign value 100 to x if y is false.

• It also can be used in places an if statement cannot be used, such as inside a single printf() statement. For example:

z = (x > y)? x : y;

• Can be written as:

if(x > y)

z  =  x;

else

z  =  y;

• A program example.

#include <stdio.h>

int main()

{

int a, b = 4, c= 50;

// here b is less than c, so the statement

// (b>c) is false, then 200 should be assigned

// to a, reflected through the output

a = (b>c) ? 100 : 200;

printf("Given: b = 4, c= 50\n");

printf("The statement:a = (b>c) ? 100 : 200\n");

printf("will be evaluated to a = %d\n", a);

return 0;

}

#### Output:

• Change the (b>c) to (b<c), then recompile and rerun.  Notice the output difference.

Related C and C++ reading and digging:

1. Check the best selling C/C++ books at Amazon.com.

2. The source code for this Module is: . and the related worksheet for your practice is: C lab worksheets.