Date post: | 17-Jan-2016 |
Category: |
Documents |
Upload: | tanvi-sharma |
View: | 231 times |
Download: | 0 times |
In this session, you will learn to:Use various operators:
Arithmetic Arithmetic Assignment Unary Comparison Logical
Use conditional constructsUse looping constructsUsing Arrays
ObjectivesObjectives
Applications use operators to process the data entered by a user.
Operators in C# can be classified as follows:Arithmetic operatorsArithmetic Assignment operatorsUnary operatorsComparison operatorsLogical operators
Using Operators Using Operators
Arithmetic operators are the symbols that are used to perform arithmetic operations on variables.
The following table describes the commonly used arithmetic operators.
Arithmetic Operators Arithmetic Operators
Operator Description Example
+ Used to add two numbers
X=Y+Z;If Y is equal to 20 and Z is equal to 2, X will have the value 22.
- Used to subtract two numbers
X=Y-Z;If Y is equal to 20 and Z is equal to 2, X will have the value 18.
* Used to multiply two numbers
X=Y*Z;If Y is equal to 20 and Z is equal to 2, X will have the value 40.
/ Used to divide one number by another
X=Y/Z;If Y is equal to 21 and Z is equal to 2, X will have the value 10.But, if Y is equal to 21.0 and Z is equal to 2, X will have the value 10.5.
% Used to divide two numbers and return the remainder
X=Y%Z;If Y is equal to 21 and Z is equal to 2, X will contain the value 1.
Arithmetic assignment operators are used to perform arithmetic operations to assign a value to an operand.
The following table lists the usage and describes the commonly used assignment operators.
Arithmetic Assignment Operators
Operator Usage Description
= X = 5; Stores the value 5 in the variable X.
+= X+=Y; Same as:X = X + Y;
-= X-=Y; Same as:X = X - Y;
*= X*=Y; Same as:X = X * Y;
/= X/=Y; Same as:X = X / Y;
%= X%=Y; Same as:X = X % Y;
Arithmetic Assignment Operators Arithmetic Assignment Operators
Unary operators are used to increment or decrement the value of an operand by 1.
The following table explains the usage of the increment and decrement operators.
Unary Operators
Operator Usage Description Example
++ ++Operand;(Preincrement operator)Or,Operand++; (Postincrement operator)
Used to increment the value of an operand by 1
Y = ++X;If the initial value of X is 5, after the execution of the preceding statement, values of both X and Y will be 6.Y = X++;If the initial value of X is 5, after the execution of the preceding statement, value of X will be 6 and the value of Y will be 5.
-- --Operand;(Predecrement operator)Or,Operand--; (Postdecrement)
Used to decrement the value of an operand by 1
Y = --X;If the initial value of X is 5, after the execution of the preceding statement, values of X and Y will be 4.Y = X--;If the initial value of X is 5, after the execution of the preceding statement, value of X will be 4 and the value of Y will be 5.
Unary Operators Unary Operators
Comparison operators are used to compare two values and perform an action on the basis of the result of that comparison.
The following table explains the usage of commonly used comparison operators.
Comparison Operators
Operator Usage Description Example (In the following examples, the value of X is assumed to be 20 and the value of Y is assumed to be 25)
< expression1 < expression2
Used to check whether expression1 is less than expression2
bool Result;Result = X < Y;Result will have the value true.
> expression1 > expression2
Used to check whether expression1 is greater than expression2
bool Result;Result = X > Y;Result will have the value false.
<= expression1 <= expression2
Used to check whether expression1 is less than or equal to expression2
bool Result;Result = X <= Y;Result will have the value true.
>= expression1 >= expression2
Used to check whether expression1 is greater than or equal to expression2
bool Result;Result = X >= Y;Result will have the value false.
Comparison Operators Comparison Operators
Comparison Operators (Contd.)
Operator Usage Description Example (In the following examples, the value of X is assumed to be 20 and the value of Y is assumed to be 25)
== expression1 == expression2
Used to check whether expression1 is equal to expression2
bool Result;Result = X == Y;Result will have the value false.
!= expression1 != expression2
Used to check whether expression1 is not equal to expression2
bool Result;Result = X != Y;Result will have the value true.
Comparison Operators (contd..) Comparison Operators (contd..)
Logical operators are used to evaluate expressions and return a Boolean value.
The following table explains the usage of logical operators.
Logical Operators
Operator Usage Description Example
&& expression1 && expression2
Returns true if both expression1 and expression2 are true.
bool Result;string str1, str2; str1 = “Korea”;str2 = “France”;Result= ((str1==“Korea”) && (str2==“France”))
Console.WriteLine (Result .ToString());
The message displays True because str1 has the value “Korea” and str2 has the value “France”.
! ! expression Returns true if the expression is false.
bool Resultint x; x = 20; Result=(!( x == 10)) Console.WriteLine(Result.ToString());The message displays True because the expression used returns true.
Logical Operators Logical Operators
Logical Operators (Contd.)
Operator Usage Description Example
|| expression1 || expression2
Returns true if either expression1 or expression2 or both of them are true.
bool Resultstring str1, str2; str1 = “Korea”;str2 = “England”;Result= ((str1==“Korea”) || (str2== “France”))
Console.WriteLine (Result .ToString());
The message displays True if either str1 has the value “Korea” or str2 has the value “France”.
^ expression1 ^ expression2
Returns true if either expression1 or expression2 is true. It returns false if both expression1 and expression2 are true or if both expression1 and expression2 are false.
bool Result;string str1, str2;str1 = “Korea”;str2= “France”;Result = (str1== “Korea”) ^ (str2== “France”);Console.WriteLine (Result .ToString());The message False is displayed because both the expressions are true.
Logical Operators (contd..) Logical Operators (contd..)
Using Conditional Constructs
Conditional constructs allow the selective execution of statements, depending on the value of expression associated with them.
The comparison operators are required for evaluating the conditions.
The various conditional constructs are:The if…else construct
The switch…case construct
Using Conditional ConstructsUsing Conditional Constructs
The if…else conditional construct is followed by a logical expression where data is compared and a decision is made on the basis of the result of the comparison.
The following is the syntax of the if…else construct:if (expression)
{statements;
}
else
{statements;
}
The if…else Construct The if…else constructThe if…else construct
The if…else constructs can be nested inside each other.
When if…else construct is nested together, the construct is known as cascading if…else constructs.
The if…else Construct (Contd.) The if…else construct (contd..)The if…else construct (contd..)
The switch…case construct is used when there are multiple values for a variable.
The following is the syntax of the switch…case construct:switch (VariableName)
{
case ConstantExpression_1:
statements;
break;
case ConstantExpression_2:
statements;
break;
The switch…case Construct The switch…case constructThe switch…case construct
…
case ConstantExpression_n:
statements;
break;
default:
statements;
break;
}
The switch…case Construct (Contd.) The switch…case construct (contd..)The switch…case construct (contd..)
Problem Statement:Write a program that emulates a calculator. The calculator should be able to perform the following mathematical operations:
Addition
Subtraction
Multiplication
Division
Demo: Calculator Using Conditional Constructs Conditional Constructs Calculator using conditional constructsCalculator using conditional constructs
Using Loop Constructs
Loop structures are used to execute one or more lines of code repetitively.
The following loop constructs are supported by C#:The while loop
The do…while loop
The for loop
Using Loop constructsUsing Loop constructs
The while Loop
The while loop construct is used to execute a block of statements for a definite number of times, depending on a condition.
The following is the syntax of the while loop construct:while (expression)
{statements;
}
The while loopThe while loop
The do…while Loop
The do…while loop construct is similar to the while loop construct.
Both iterate until the specified loop condition becomes false.
The following is the syntax of the do…while loop construct:do
{
statements;
}while(expression);
The do…while loopThe do…while loop
The do…while Loop (Contd.)
The following figure shows the difference between the do…while and while loop construct.
False
do while
False
True
Execute body of Loop
EvaluateCondition
True
Execute body of Loop
EvaluateCondition
while
The do…while loop (contd..)The do…while loop (contd..)
The for Loop
The for loop structure is used to execute a block of statements for a specific number of times.
The following is the syntax of the for loop construct: for (initialization; termination;
increment/decrement)
{
statements
}
The for loopThe for loop
The for Loop (Contd.)
The following figure shows the sequence of execution of a complete for loop construct.
True
False
Initialization
EvaluateCondition
Body of the for Loop
Exit the for Loop
Increment/ Decrement
The for loop(contd..)The for loop(contd..)
Demo: Fibonacci Series Using Loop Constructs
Problem Statement:Write a program that generates the Fibonacci series up to 200.
Fibonacci series using Loop constructsFibonacci series using Loop constructs
The break and continue Statements
The break statement is used to exit from the loop and prevents the execution of the remaining loop.
The continue statement is used to skip all the subsequent instructions and take the control back to the loop.
The break and continue statementThe break and continue statement
Implementing Arrays
An array is a collection of values of the same data type.
The following figure shows the array structure in the system’s memory.
Index
Value 0
Index
Value 6
Implementing ArraysImplementing Arrays
Declaring an Array
An array needs to be declared before it can be used in a program.
You can declare an array by using the following statement:datatype[] Arrayname;
Let us understand the explanation of the various elements of the array declaration through an example.
Declaring an arrayDeclaring an array
Declaring an Array (Contd.)
int[ ] Score; Datatype
Is used to specify the data type for the elements
Declaring an array (contd..)Declaring an array (contd..)
Declaring an Array (Contd.)
int[ ] Score; [ ]
Is used to specify the rank of the array
Declaring an array (contd..)Declaring an array (contd..)
Declaring an Array (Contd.)
int[ ] Score; Arrayname
Is used to specify the name of the array using which the elements of the array will be initialized and manipulated
Declaring an array (contd..)Declaring an array (contd..)
In C#, you can initialize the array variable and can assign values to the array elements. In addition, you can copy the array variable to another variable.
During initialization, you need to use the new keyword to create an instance of the array. In addition, the size of the array is also specified while it is initialized.
The following is an example of array initialization:int[] Score; // Array declaration
Score = new int[10]; //Array Instance
Initializing and Assigning Values to Array Initializing and Assigning values to ArrayInitializing and Assigning values to Array
You can assign values to each element of the array by using the index number, which is called the array subscript of the element.The following is an example of assigning values to the array:int[] Score = new int[3];Score[0]=10;
Orint[] Score={5,10,15};
When you copy the array variable, both the source and target variable refer to the same array instance in the memory. The following is an example of copying the array variables:int[] Source = new int[10] {0, 1, 2, 3, 4};int[] Target= Source;
Initializing and Assigning Values to Array (Contd.) Initializing and Assigning values to Array (contd..)Initializing and Assigning values to Array (contd..)
When an array is initialized, you can access the element values and manipulate them.
The foreach loop is specially used for manipulating arrays.
The following is the syntax of the foreach loop:foreach (type identifier in expression)
{
//statements
}
Manipulating Array Elements Manipulating Array elementsManipulating Array elements
The following is the example of foreach loop:int[] Numbers = { 4, 3, 2, 1, 0, -1, -2, 9, 5 };
Console.WriteLine("The Contents of an Array is:");
foreach (int K in Numbers)
{
Console.WriteLine("{0} \t",K);
}
Manipulating Array Elements (Contd.) Manipulating Array elements (contd..)Manipulating Array elements (contd..)
Multidimensional Arrays
The rank value of the array is also known as the dimension of the array.
The array can be single dimensional or multidimensional.
Single dimensional array stores data in a row.
Multidimensional array stores data using different dimensions.
The following figure is a graphical representation of values stored in a single dimensional array and a multidimensional array.
int [] Num; int[,] Num; 0
0 1 2 3 4 1
0 1 2 3 4
Multidimensional ArraysMultidimensional Arrays
You can create a two dimensional array like as shown below:
int[ , ] myArray;
myArray=new int[3,4];
or
int [ , ] myArray=new int[3,4];
this creates as array having 3 rows and four columns.
You can also initialize two dimensional array by following their declaration with a list of initial values enclosed in braces:
int[ , ] myArray={ {0,0,0},{1,1,1}};
Multidimensional Array(Contd.) Multidimensional Arrays (contd..)Multidimensional Arrays (contd..)
In this session, you learned that:Operators are used to compute and compare values and test multiple conditions.
You use arithmetic operators to perform arithmetic operations on variables like addition, subtraction, multiplication, and division.
You can use arithmetic assignment operators to perform arithmetic operations and assign the result to a variable.
The unary operators, such as the increment and decrement operators, operate on one operand.
Comparison operators are used to compare two values and perform an action on the basis of the result of the comparison.
Logical operators are used to evaluate expressions and return a Boolean value.
Summary SummarySummary
Conditional constructs are used to allow the selective execution of statements. The conditional constructs in C# are:
if…else
switch…case
Looping constructs are used when you want a section of a program to be repeated a certain number of times. C# offers the following looping constructs:
while
do…while
for
The break and continue statements are used to control the program flow within a loop.
Summary (Contd.) Summary (contd..)Summary (contd..)