# Lesson 3:Operators,Conditions,Loops

C# Operators,Conditions and Loops

C# provides a variety of operators to work within your program. The operators mostly used are

<=, >=, binary +, binary -, ^, &, |,==, !=,<, >, ~, ++, –, sizeof (), typeof() etc

Here is a list of operators categories which I have taken from msdn site:

Primary

x.y

f(x)

a[x]

x++

x–

new

typeof

checked

unchecked

default(T)

delegate

sizeof

->

Unary

+x

-x

!x

~x

++x

–x

(T)x

await

&x

*x

Multiplicative

x * y

x / y

x % y

x + y

x – y

Shift

x << y x >> y

Relational and type testing

x < y x > y

x <= y x >= y

is

as

Equality

x == y

x != y

Logical AND

x & y

Logical XOR

x ^ y

Logical OR

x | y

Conditional AND

x && y

Conditional OR

x || y

Null-coalescing

x ?? y

Conditional

?:

Assignment and lambda expression

x = y

x += y

x -= y

x *= y

x /= y

x %= y

x &= y

x |= y

x ^= y

x <<= y x >>= y

=>

DivideByZeroException

If you divide any number by zero, you will get a DivideByZeroException

E.g. 1/0,2.1/0 etc

These are often termed as Integer Arithmetic Overflow,Floating-Point Arithmetic Overflow and Decimal Overflow exceptions .

Examples of Operators in action

Unary Operators

Perform action on a single operand.Such as ++a.Here ++ is the operator and a is the operand

Increment Operator:

Example
class MyClass
{
static void Main()
{
double x;
x = 1.5;
Console.WriteLine(++x);
x = 1.5;
Console.WriteLine(x++);
Console.WriteLine(x);
}
}

/*
Output
2.5
1.5
2.5
*/

Note: Taken from http://msdn.microsoft.com/en-us/library/vstudio/36x43w8w.aspx as a reference

The ++x is a prefix increment operator.It actually first increments the values and then show the incremented result.Where as x++ is a postfix increment operator which first shows the value contained in x and then the incremented value.

Decrement Operators –x,x– have the same logic if we want to decrement the values instead of incrementing.

[Another interesting point is that,if we have a statement like this : x=x+1: we can also write it as x+=1]

(Statements are set of instructions used in a C# program.They are terminated by a semi-colon.For example x=x+1; is a statement)

Binary Operators

They are used in between two or more operands

E.g (+, -, *, /, %, &, |, ^, <<, >>, ==, !=, >, <, >=, or <=) etc Here is a chart of statements in C# on Microsoft official site http://msdn.microsoft.com/en-us/library/xt4z8b0f(v=vs.110).aspx

Ternary Operator ?:

The easiest example  with definition and code is present  on the following link. Sometimes I have to refer to the link due to the fact that we have to cover whole lots of things later. If you have any difficulty…. Ask me on Comments section

http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.100).aspx

Conditions in C#

if and else condition

The if condition is used to execute a certain block of code,when the condition is valid in the if block.

The else condition is the next resort when the if condition is not valid.

Examples

Example 1

int i=1;

if(i==1) // note ‘==’ is used in if;not ‘=’

{

Console.Write(“Hello”);

}

else { Console.Write(“Bye”);

}

Output

Hello

Example 2

Operators applied to if

if(a!=b) // if ‘a’ is not equal to ‘b’

if(a==b && c==d) // if ‘a’ is equal to ‘b’ and ‘c’ equals to ‘d’

if(y==true) // if the value in ‘y’ is true

if(i>=j II k<=l)// if ‘i’ is less than or equal to j or ‘k’ is less than or equal to l

etc

The else if trick

When coding in C#, there often comes a situation when we have to deal with a state of a variable in order to execute a specific block of code. In such a situation else if is to watch for.

Example

using System;

namespace mynamespace

{

class Program

{

static void Main()

{

int i = 2;

if (i == 1)

{

Console.WriteLine(“n i=1”);
}

else if(i > 1)

{

Console.WriteLine(“n i={0}”, i);

}

}

}

}

Output

i=2

Note {0} is used to refer to the first value in the argument. For two values, we can use

Console.WriteLine(“i={0},j={1)”,i,j);

Switch statement

Examples

Example1

int MyVal = 1;
switch (MyVal)
{
case 1: Console.WriteLine(“MyVal=1”);
break;
case 2: Console.WriteLine(“MyVal=2”);
break;
default: Console.WriteLine(“MyVal=1”);
break;
}

The switch statement checks each statement for the condition to get verified. If so, the break keyword terminates further checks. If no condition is satisfied, the default condition is obvious. if statement leads over the switch when we are checking against something undetermined yet. Above example is used for the value contain in integer. We can easily use switch with other data types as well

Example2

using System;

class Program
{
static void Main()
{

char a = ‘a’;

switch (a)
{

case ‘b’: Console.WriteLine(“n Value is :{0}”,a);
break;

case ‘c’:
Console.WriteLine(“n Value is :{0}”,a);
break;

case ‘d’:
Console.WriteLine(“n Value is :{0}”,a);
break;

default:

Console.WriteLine(“n Value is unchanged i.e :{0}”,a);
break;

}

}

}

Output

The value is unchanged i.e.: a

Loops in C#:

Loops are used to perform several operations for  a number of times which is also known as loop iteration. Following are the loops available in C#

For Loop

For Loop is used to loop for a specific number of times. It has initialization point, condition and then increment

Examples

for (int i = 0; i < 20; i++)
{
Console.WriteLine(i);
}

Output

1

2

3

4

.

.

.

.

19

While Loop

While Loop is used in those situations, when we are unaware of the condition at which the loop has to be terminated

Example

static void Main()

{

int i =1;

//increment ‘i’ by ‘1’ each time until i is lesser than ‘5’

while (i < 5)

{

Console.WriteLine(i);

i++;

}

Output

1

2

3

4

We can also use While(true),While(dr.Read()) etc.

Break Keyword

Example

using System;

class Program
{
static void Main()
{

int i = 1;

while (i < 5)

{

Console.WriteLine(i);

i++;

if (i == 4)

{

// terminate the loop iteration if the value in i becomes 4

break;

}

}
}

}

Output

1

2

3

[ The break keyword is used to terminate the execution of the loop.Here,if i reaches the value 4,then immediately terminate the loop.so the value 4 is not shown]

Do While Loop

do {

// Body

}

while (condition);

In Do While, the body of the loop is always executed at least once.Whereas in While Loop,body executes only if the condition is satisfied

Example

using System;

class Program
{
static void Main()
{

int a = 5;
do
{
Console.WriteLine(a);
a–;
}
while (a >0);
}

}

Output

5

4

3

2

1

For Each Loop

This kind of loop is used to iterate through collections.Collections will be discussed later

Example

using System;

class Program

{

static void Main()

{

int[] array = { 1, 3, 5, 7, 9 }; //array collection of integers

foreach (int value in array)

{

Console.WriteLine(value);

if (value == 7)

{

break;

}

}

}

}

Output

1

3

5

7

Continue Keyword

This keyword is often used to give the control back to the iterating loop rather than terminating the loop so that the loop proceeds to the next iteration and continue executing

Example

using System;

class Program
{
static void Main()

{
/* integer array consisting the members in {} brackets
and separated by commas.
arrays will be discussed later */
int[] array = { 1, 3, 5, 7, 9 };

foreach (int value in array)

{

if (value < 9)

{

Console.WriteLine(value);

continue;

}

else

{

Console.WriteLine(“n Value:{0} is reached.After it no other value is present”, value);

break;

}

}
}

}

Output

1
3
5
7

Value:9 is reached.After it no other value is present

Goto Statement.It is just like jumping from one statement to another different statement.It should be used with caution.

Yield

We will discuss it later in Collections

Lesson 3 completed……

Analyst, Programmer, Educationist and Blogger at Technofranchise
Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.