Lecture 2 Intake 30, 2009
The Expression and Operators
Operators
There are several operators in C language. It may be unary operator which has one
operand or binary operator which has two operands. The operator may be classified as:
The Mathematical operator:
+ sign add the two operands
- sign subtract the second operands from the first operands
* sign multiply the two operands
/...sign divided the first operand by the second
%.sign modulus operator (it give the reminder of the division)
% can’t be used with real numbers (floating point numbers).
When you apply / to an integer or character, any remainder will be truncated, e.g 5/2
gives 2.
Example:
# include <stdio.h>
int main()
{
int i,x,y;
x=3;
y=7;
i=y%x;
printf(“%d”,i);
return 0;
}
the value of i will be 1
In the division, if we divide int by int the result will be integer. To divide two integer and
to have the value float we must make one of the operands as float. This is done by using
type casting:
In type casting: You force an expression to be of a specific type during a certain
statement only. It has the form:
(new type) expression
so we can use it to have a decimal value when dividing two integer
Example:
# include <stdio.h>
int main()
{
int x,y;
float i;
x=3; y=7;
i=(float)y/x;
printf(“%f”,i);
return 0;
}
1
Lecture 2 Intake 30, 2009
The value of i will be 2.3333333
The Relational operator
It allows the programmer to compare two value and return non zero value if the
comparison is right or zero if the comparison is not true. Usually used for conditional
statements.
> greater than
< lower than
>= greater than or equal
<= lower than or equal
== equal
!= not equal
The Logical operator
The logical operator works with logical values (true or false)
&& and
|| or
! not
The Increment/Decrement operator
++ increment by 1
-- decrement by 1
The pre-increment: ++x
The post-increment: x++
The difference between pre-increment and post-increment can be seen in the following
examples
#include <stdio.h> #include <stdio.h>
int main() int main()
{ {
int x,y; int x,y;
x=10; x=10;
y=++x; y=x++;
printf(“%d \n”,x); printf(“%d \n”,x);
printf(“%d \n”,y); printf(“%d \n”,y);
return 0; return 0;
} }
the value of x=11 the value of x=11
the value of y=11 the value of y=10
x=x+1; y=x;
y=x; x=x+1;
increment then assigning assign then increment
2
Lecture 2 Intake 30, 2009
The assignment operator
= equal x = 5;
+= x += 5; equivalent to x = x+5;
-= x -= 5; equivalent to x = x-5;
*= x *= 5; equivalent to x = x*5;
/= x /= 5; equivalent to x = x/5;
%= x %= 5; equivalent to x = x%5;
LHS takes the value evaluated by expression of RHS.
Expressions
Operators, constants, functions, and variables are the constituents of expressions. An
expression in C is any valid combination of these elements.
Order of Evaluation
C does not specify the order in which the subexpressions of an expression are evaluated.
This leaves the compiler free to rearrange an expression to produce more optimal code.
However, it also means that your code should never rely upon the order in which
subexpressions are evaluated.
Precedence of C Operators
Highest ( ) [ ] –>.
! ~ ++ – – – (type) * & sizeof
*/%
+–
<< >>
< <= > >=
== !=
&
^
|
&&
||
?
Lowest = += –= *= /= etc.
For example, the expression
x = f1() + f2();
does not ensure that f1( ) will be called before f2( ).
Type Casting
You can force an expression to be of a specific type by using a cast. The general form of a
cast is
(type) expression
where type is a valid data type. For example, to cause the expression x/2 to evaluate to type
float, write (float) x/2
Casts are technically operators. As an operator, a cast is unary and has the same
precedence as any other unary operator. Casts can be very useful.
3
Lecture 2 Intake 30, 2009
You can add tabs and spaces to expressions to make them easier to read. For example,
the following two expressions are the same:
x=10/y~(127/x);
x = 10 / y ~(127/x);
Redundant or additional parentheses do not cause errors or slow down the execution of
an expression. You should use parentheses to clarify the exact order of evaluation, both for
yourself and for others. For example, which of the following two expressions is easier to
read?
x = y/3-34*temp+127;
x = (y/3) - (34*temp) + 127;
Statements
1. Selection (conditional) statements
There are two type of selection statements and operator:
The if statements:
if (condition)
{
statements;
}
The statement between { } will be executed if the condition is true other wise it will be
escaped and continue the program. The if statement is used when some extra instruction
will be done if the condition is valid then continue the program and if the condition is not
valid, it continue the program: i.e. The following diagram.
Example:
Write a program to read a number. If it is odd (multiply the number*2) then print it, if it is
even print it.
#include <stdio.h>
int main()
{
int x,y;
scanf(“%d”,&x);
y = x %2;
if (y!=0)
{
x *= 2;
}
printf(“The number = %d \n”,x);
4
Lecture 2 Intake 30, 2009
return 0;
}
This program can be written as follow:
int main()
{
int x;
scanf(“%d”, &x);
if((x%2)!=0) OR if(x%2)
{ {
x *= 2; x *= 2;
} }
printf(“The number = %d \n”,x);
return 0;
}
The individual statements in the if statement end with semicolons, but not the if. The
if...else spans several lines, so you don’t put semicolons after the first line of an if statement.
if (condition)
{
statements;
}
else
{
statements;
}
The if-else statement is used when we have one condition and two different solutions
Example:
Write a program to have the student grade and print if it is passed or failed, knowing that
passing is from 60
#include <stdio.h>
int main()
{
int grade;
printf(“Enter the student grade ”);
scanf(“%d”,&grade);
if(grade>=60)
{
printf(“\n Pass”);
}
else
5
Lecture 2 Intake 30, 2009
{
printf(“\n Failed”);
}
printf (“\n End program”);
return 0;
}
Nested if
A nested if is the target of another if or else. An else statement must always refer s to
the nearest if statement that is within the same block and that is not already associated with
an else. The Ansi C standard specifies that atleast 15 levels of nesting must be supported.
Example :
Write a program that read the grade and print if it is grade A, B, C, or Failed. Knowing
that:
A if the grade greater than 90
B if the grade greater than 80
C if the grade greater than 60
# include <stdio.h>
int main()
{
int grade;
printf(“Enter the grade”);
scanf(“%d”,grade);
if(grade>=90)
{
printf(“\n Grade A”);
}
else
{
if(grade>=80)
{
printf(“\n Grade B”);
}
else
{
if(grade>=60)
{
printf(“\n Grade C”);
}
else
{
printf(“\n Failed”);
}
}
}
return 0;
}
N.B.
6
Lecture 2 Intake 30, 2009
1) when writing the condition, be sure that you use the relational operator NOT the
assignment operator (i.e. if you check for equality check that you use == not =)
2) be sure that you haven’t put ; after the condition of the if statement
The switch case:
It is a multiple branch selection, it has the form:
switch (expression)
{
case constant1:
{
statement;
break;
}
case constant2:
{
statement;
break;
}
default:
{
statement;
}
}
The switch can only test for equality. No two case constant in the same switch. The
switch expression works on the following data type: int, long, char
Example:
Write a program to enter 1, 2, or 3 then the program write one, two or three otherwise
write Out of range
#include <stdio.h>
int main()
{
int n;
printf(“Enter a no.: ”);
scanf(“%d”,&n);
switch (n)
{
case 1:
{
printf(“\n One”);
break;
}
case 2:
{
printf(“\n Two”);
break;
}
case 3:
7
Lecture 2 Intake 30, 2009
{
printf(“\n Three”);
break;
}
default:
{
printf(“\nOut of range”);
}
}
return 0;
}
Example:
Write a program that read two number and print the message as the following table:
First number Second number Message
1 1 One One
1 2 One Two
1 Any other number One the second out of range
2 1 Value of second * first
2 2 Value of second * first
2 Any other number Two the second out of range
3 1 Value of second %first
3 2 Value of second %first
2 Any other number Three the second out of range
Any other value Any value The first number is out of range
#include <stdio.h>
int main()
{
int x, y;
printf(“Enter the first number: ”);
scanf(“%d”, &x);
printf(“Enter the second number: “);
scanf(“%d”, &y);
switch(x)
{
case 1:
{
switch(y)
{
case 1:
{
printf(“One One\n”);
break;
}
case 2:
{
printf(“One Two\n”);
break;
}
default:
8
Lecture 2 Intake 30, 2009
{
printf(“Out Of Range\n”);
}
}
break;
}
case 2:
{
switch(y)
{
case 1:
{
printf(“%d\n”, x*y);
break;
}
case 2:
{
printf(“%d\n”, x*y);
break;
}
default:
{
printf(“Out Of Range\n”);
}
}
break;
}
case 3:
{
switch(y)
{
case 1:
{
printf(“%d\n”, y%x);
break;
}
case 2:
{
printf(“%d\n”, y%x);
break;
}
default:
{
printf(“Out Of Range\n”);
}
}
break;
}
default:
9
Lecture 2 Intake 30, 2009
{
printf(“First number Out Of Range\n”);
}
}
return 0;
}
The ? operator
This is an operator that can replace certain statment of the if-else form. The “?” is a
ternary operator (take three operand) has the general form :
Exp1 ? Exp2 : Exp3 where Exp1, Exp2, and Exp3 are expressions.
The “?” operator works like this:
Exp1 is evaluated (true) evaluate Exp2
(false) evaluate Exp3
example:
max = num1 > num2 ? num1 : num2;
example:
write a program that compare between 2 numbers S1 and S2 and print :
1 if S1 > S2
2 if S1 = S2
3 if S1 < S2
num = (S1 > S2 ? 1 : (S1 == S2 ? 2 : 3) );
Example:
Get 2 numbers and print the max.
int main()
{
int x,y,max;
scanf(“%d”,&x);
scanf(“%d”,&y);
max=(x>y?x:y);
printf(“max is %d”,max);
return 0;
}
10