Home » C# Basics » 03 - C# Programming - Part 1
3

Operators and Expressions

Explains what operators and expressions are and how it functions in a C# program

Operators are used for processing the data. Expressions are created by combining the operators with variables and constants:

int number1, number2, sum;
number1=10;
number2=20;
sum=number1 + number2;

In the last statement, two variables using the + symbol are added. The `+' symbol is the operator.

C# has various operators. Mathematical operators are used for mathematical calculations-

Operator

Use

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Remainder of a division

Some other frequently used operators are the logical operators. They compare two values and give result in `true' or `false'. They are mostly used with the decision-making statements:

==

Equal

!=

Not equal

>

Greater than

<

Less than

>=

Greater than or equal to

<=

Less than or equal to

&&

Checks multiple conditions. If all the conditions are true, the result is `true'. If any one condition is false, the result is `false'.

||

Checks multiple conditions. If any one of the conditions is true, the result is `true'. If all the condition are false, the result is `false'.

Consider the following -

int x,y,z;
x=10;
y=25;
z=10;

Now, let us check the following statements:

if(x==y) 

// this will result in false since x and y are not equal

if(x==z) 

// this will result in true since x and z are equal

if(x>=z) 

// result is true

if(y<z) 

// result is false

if( (x<y) && (y>z) ) 

// since x is less than y and y is greater than z, both conditions

are true. Hence, the result is true.

if( (x<y) && (y<z) ) 

// since x is less than y but y is not less than z, one condition

is false. Hence, the result is false.

if( (x<y) || (y<z) ) 

// here, though y is not less than z, since x is less than y, one

condition is true. Hence, the result is true.

if( (x>y) || (y<z) ) 

// here, neither y is less than z nor x is greater than y. Both

conditions are false. Hence, the result is false.