MCS-011 Problem Solving and Programming

Admin | First year, Semester1

Chapters

Newsletter

Relational Operators

Executable C statements either perform actions (such as calculations or input or output of data) or make decision. Using relational operators we can compare two variables in the program. The C relational operators are summarized below, with their meanings. Pay particular attention to the equality operator; it consists of two equal signs, not just one. This section introduces a simple version of C’s if control structure that allows a program to make a decision based on the result of some condition. If the condition is true then the statement in the body of if statement is executed else if the condition is false, the statement is not executed. Whether the body statement is executed or not, after the if structure completes, execution proceeds with the next statement after the if structure. Conditions in the if structure are formed with the relational operators which are summarized in the Table below:

Relational OperatorConditionMeaning
==x == yx is equal to y
!=x != yx is not equal to y
<x < yx is less than y
<=x <= yx is less than or equal to y
>x > yx is greater than y
>=x >= yx is greater than or equal to y


Relational operators usually appear in statements which are inquiring about the truth of some particular relationship between variables. Normally, the relational operators in C are the operators in the expressions that appear between the parentheses. For example,

  1. if (thisNum < minimumSoFar) minimumSoFar = thisNum
  2. if (job == Teacher) salary == minimumWage
  3. if (numberOfLegs != 8) thisBug = insect
  4. if (degreeOfPolynomial < 2) polynomial = linear  

Assignment Statement

In the previous unit, we have seen that variables are basically memory locations and they can hold certain values. But, how to assign values to the variables? C provides an assignment operator for this purpose. The function of this operator is to assign the values or values in variables on right hand side of an expression to variables on the left hand side.

The syntax of the assignment expression is as follows:

Variable = constant / variable/ expression;

The data type of the variable on left hand side should match the data type of constant/variable/expression on right hand side with a few exceptions where automatic type conversions are possible. Some examples of assignment statements are as follows:

b = a ; /* b is assigned the value of a */
b = 5 ; /* b is assigned the value 5*/
b = a+5; /* b is assigned the value of expr a+5 */  

The expression on the right hand side of the assignment statement can be:

  1.   an arithmetic expression;
  2. a relational expression;
  3. a logical expression;
  4. a mixed expression.

The above mentioned expressions are different in terms of the type of operators connecting the variables and constants on the right hand side of the variable. Arithmetic operators, relational operators and logical operators are discussed in the following sections.

For example,

    int a;

    float b, c, avg, t;

    avg = (b + c) / 2;       /* arithmetic expression */

    a = b && c;              /* logical expression */

    a = (b + c) && (b < c);  /* mixed expression */

Arithmetic Operators

The basic arithmetic operators in C are the same as in most other computer languages, and correspond to our usual mathematical/algebraic symbolism. The following arithmetic operators are present in C:

OperatorMeaning
+Addition
-Subtraction
*Multiplication
/Division
%Modular Division

 

Some of the examples of algebraic expressions and their C notation are given below:

ExpressionC Notation
b* g d(b *g) / d
a^3 + cd

(????????)(a*a*a) + (c*d)


The arithmetic operators are all binary operators i.e. all the operators have two operands. The integer division yields the integer result. For example, the expression 10/3 evaluates to 3 and the expression 15/4 evaluates to 3. C provides the modulus operator, %, which yields the reminder after integer division. The modulus operator is an integer operator that can be used only with integer operands. The expression x%y yields the reminder after x is divided by y. Therefore, 10%3 yields 1 and 15%4 yields

3. An attempt to divide by zero is undefined on computer system and generally results in a run- time error. Normally, Arithmetic expressions in C are written in straight-line form. Thus ‘a divided by b’ is written as a/b.

The operands in arithmetic expressions can be of integer, float, double type. In order to effectively develop C programs, it will be necessary for you to understand the rules that are used for implicit conversation of floating point and integer values in C.

They are mentioned below:  

  1. An arithmetic operator between an integer and integer always yields an integer result.
  2. Operator between float and float yields a float result.
  3. Operator between integer and float yields a float result.

If the data type is double instead of float, then we get a result of double data type.

For example,

OperationResult
5/31
5.0/31.3
5/3.01.3
5.0/3.01.3

 

Parentheses can be used in C expression in the same manner as algebraic expression For example,

a * (b + c).

It may so happen that the type of the expression and the type of the variable on the left hand side of the assignment operator may not be same. In such a case the value for the expression is promoted or demoted depending on the type of the variable on left hand side of = (assignment operator). For example, consider the following assignment statements:

int i;
float b;
i = 4.6;
b = 20;

In the first assignment statement, float (4.6) is demoted to int. Hence i gets the value

4. In the second statement int (20) is promoted to float, b gets 20.0. If we have a complex expression like:  

float a, b, c;
int s;
s = a * b / 5.0 * c;

Where some operands are integers and some are float, then int will be promoted or demoted depending on left hand side operator. In this case, demotion will take place since s is an integer.

The rules of arithmetic precedence are as follows:

  1. Parentheses are at the “highest level of precedence”. In case of nested parenthesis, the innermost parentheses are evaluated first.
  2. Multiplication, Division and Modulus operators are evaluated next. If an expression contains several multiplication, division and modulus operators, evaluation proceeds from left to right. These three are at the same level of precedence.
  3. Addition, subtraction are evaluated last. If an expression contains several addition and subtraction operators, evaluation proceeds from left to right. Or the associativity is from left to right.

Apart from these binary arithmetic operators, C also contains two unary operators referred to as increment (++) and decrement (--) operators, which we are going to be discussed below:

The two-unary arithmetic operators provided by C are:

  1. Increment operator (++)
  2. Decrement operator (- -)

The increment operator increments the variable by one and decrement operator decrements the variable by one. These operators can be written in two forms i.e. before a variable or after a variable. If an increment / decrement operator is written before a variable, it is referred to as preincrement / predecrement operators and if it is written after a variable, it is referred to as post increment / postdecrement operator.

For example,

a++ or ++a is equivalent to a = a+1 and
a-- or - -a is equivalent to a = a -1

The importance of pre and post operator occurs while they are used in the expressions. Preincrementing (Predecrementing) a variable causes the variable to be incremented (decremented) by 1, then the new value of the variable is used in the expression in which it appears. Postincrementing (postdecrementing) the variable causes the current value of the variable is used in the expression in which it appears, then the variable value is incremented (decrement) by 1.

The explanation is given in the table below:

ExpressionExplanation
++aIncrement a by 1, then use the new value of a
a++Use the current value of a, then increment a by 1
--bDecrement b by 1, then use the new value of b
b--Use the current value of b, then decrement b by 1

 

Relational Operators

Executable C statements either perform actions (such as calculations or input or output of data) or make decision. Using relational operators we can compare two variables in the program. The C relational operators are summarized below, with their meanings. Pay particular attention to the equality operator; it consists of two equal signs, not just one. This section introduces a simple version of C’s if control structure that allows a program to make a decision based on the result of some condition. If the condition is true then the statement in the body of if statement is executed else if the condition is false, the statement is not executed. Whether the body statement is executed or not, after the if structure completes, execution proceeds with the next statement after the if structure. Conditions in the if structure are formed with the relational operators which are summarized in the Table below:

Relational OperatorConditionMeaning
==x == yx is equal to y
!=x != yx is not equal to y
<x < yx is less than y
<=x <= yx is less than or equal to y
>x > yx is greater than y
>=x >= yx is greater than or equal to y


Relational operators usually appear in statements which are inquiring about the truth of some particular relationship between variables. Normally, the relational operators in C are the operators in the expressions that appear between the parentheses. For example,

  1. if (thisNum < minimumSoFar) minimumSoFar = thisNum
  2. if (job == Teacher) salary == minimumWage
  3. if (numberOfLegs != 8) thisBug = insect
  4. if (degreeOfPolynomial < 2) polynomial = linear  

Logical Operators

Logical operators in C, as with other computer languages, are used to evaluate expressions which may be true or false. Expressions which involve logical operations are evaluated and found to be one of two values: true or false. So far we have studied simple conditions. If we want to test multiple conditions in the process of making a decision, we have to perform simple tests in separate IF statements(will be introduced in detail in the next unit). C provides logical operators that may be used to form more complex conditions by combining simple conditions.

The logical operators are listed below:

OperatorMeaning
&&Logical AND
||Logical OR
!Logical NOT

 

Thus logical operators (AND and OR) combine two conditions and logical NOT is used to negate the condition i.e. if the condition is true, NOT negates it to false and vice versa.

Comma and Conditional Operators

C provides an called as the conditional operator (?:) which is closely related to the if/else structure. The conditional operator is C’s only ternary operator - it takes three operands. The operands together with the conditional operator form a conditional expression. The first operand is a condition, the second operand represents the value of the entire conditional expression it is the condition is true and the third operand is the value for the entire conditional expression if the condition is false.

The syntax is as follows:

(condition)? (expression1): (expression2);

If condition is true, expression1 is evaluated else expression2 is evaluated. Expression1/Expression2 can also be further conditional expression i.e. the case of nested if statement

For eg. 

 x= (y<20) ? 9: 10;
 This means, if (y<20), then x=9 else x=10


Comma Operator 

A comma operator is used to separate a pair of expressions. A pair of expressions separated by a comma is evaluated left to right, and the type and value of the result are the value of the type and value of the right operand. All side effects from the evaluation of the left operand are completed before beginning evaluation of the right operand. The left side of comma operator is always evaluated to void. This means that the expression on the right hand side becomes the value of the total comma-separated expression. For example,

x = (y=2, y - 1);

first assigns y the value 2 and then x the value 1. Parenthesis is necessary since comma operator has lower precedence than assignment operator.  
 

Typecast Operator

We have seen in the previous sections and last unit that when constants and variables of different types are mixed in an expression, they are converted to the same type. That is automatic type conversion takes place. The following type conversion rules are followed:

  1. All chars and short ints are converted to ints. All floats are converted to doubles.
  2. In case of binary operators, if one of the two operands is a long double, the other operand is converted to long double,
    else if one operand is double, the other is converted to double,
     else if one operand is long, the other is converted to long,
     else if one operand is unsigned, the other is converted to unsigned 

C converts all operands “up” to the type of largest operand (largest in terms of memory requirement for e.g. float requires 4 bytes of storage and int requires 2 bytes of storage so if one operand is int and the other is float, int is converted to float).

All the above mentioned conversions are automatic conversions, but what if int is to be converted to float. It is possible to force an expression to be of specific type by using operator called a cast. The syntax is as follows:

(type) expression

where type is the standard C data type. For example, if you want to make sure that the expression a/5 would evaluate to type float you would write it as

( float ) a/5

cast is an unary operator and has the same precedence as any other unary operator.  
 

Size of operator

C provides a compile-time unary operator called sizeof that can be used to compute the size of any object. The expressions such as:

sizeof object                       and                               sizeof(type name) 

result in an unsigned integer value equal to the size of the specified object or type in bytes. Actually the resultant integer is the number of bytes required to store an object of the type of its operand. An object can be a variable or array or structure. An array and structure are data structures provided in C, introduced in latter units. A type name can be the name of any basic type like int or double or a derived type like a structure or a pointer.

For example,
 sizeof(char) = 1bytes
 sizeof(int) = 2 bytes  

C Shorthand

C has a special shorthand that simplifies coding of certain type of assignment statements. For example:

a=a+2;

can be written as:

a += 2

The operator +=tells the compiler that a is assigned the value of a + 2; This shorthand works for all binary operators in C. The general form is:

variable operator = variable / constant / expression

These operators are listed below:

OperatorExampleMeaning
+=a += 2a = a + 2
-=a -= 2a = a - 2
*=a *= 2a = a * 2
/=a /= 2a = a / 2
%=a %= 2a = a % 2
&&=a &&= ca = a && c
||=a ||= ca = a || c

 
 

Priority of Operators

Since all the operators we have studied in this unit can be used together in an expression, C uses a certain hierarchy to solve such kind of mixed expressions. The hierarchy and associatively of the operators discussed so far is summarized in Table 6. The operators written in the same line have the same priority. The higher precedence operators are written first

OperatorsAssociativity
( )Left to right
! ++ -- (type) sizeofRight to left
/ %Left to right
+ -Left to right
< <= > >=Left to right
== !=Left to right
&&Left to right
||Left to right
?:Right to left
= += -= *= /= %= &&= ||=Right to left
,Left to right

About John Doe

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Report an issue

Related Posts

3 Comments

John Doe

5 min ago

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Reply

John Doe

5 min ago

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Reply