Tải bản đầy đủ (.pdf) (30 trang)

Operators and Programming Constructs pot

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (876.32 KB, 30 trang )

Operators and
Programming
Constructs
Chapter 3
Operators are used to compute results and compare
the data values of a program. A program often
involves
decision-making and iterative tasks. To accomplish
these tasks, programmers use various operators in
the conditional and looping constructs.
This chapter discusses the types of operators used in
C# language. In addition, the conditional constructs
and the looping constructs are also discussed.
In this chapter, you will learn to:
 Use various operators:
z Arithmetic
z Arithmetic assignment
z Unary
z Comparison
z Logical
 Use conditional constructs
 Use looping constructs
Objectives

¤NIIT Operators and Programming Constructs 3.3
Applications use operators to process the data entered by a user. Operators like + and - are
used to process variables and return a value. An operator is a set of one or more characters
that is used for computations or comparisons. Operators can transform one or more data
values, called operands, into a new data value.
Consider the following expression:
X+Y


The preceding expression uses two operands and an operator to add the values stored in
the variables.
Operators in C# can be classified as follows:
 Arithmetic operators
 Arithmetic assignment operators
 Unary operators
 Comparison operators
 Logical operators
These operators are the symbols that are used to perform arithmetic operations on
variables. The following table describes the commonly used 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.
Using Operators

A
rithmetic Operators
3.4 Operators and Programming Constructs ¤NIIT
Operator Description Example
/
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 Operators
These operators are used to perform arithmetic operations to assign a value to an operand.
The simplest of these is the “=”. Its general form is, var = expression. The following table
lists the usage and describes the commonly used 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
A
rithmetic Assignment Operators
¤NIIT Operators and Programming Constructs 3.5
These 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.
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
operator)
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
3.6 Operators and Programming Constructs ¤NIIT
These operators are used to compare two values and perform an action on the basis of the

result of that comparison. Whenever you use comparison operator, the expression results
a boolean value ‘true’ or ‘false’. The following table explains the usage of commonly
used 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.
==
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
Comparison Operators
¤NIIT Operators and Programming Constructs 3.7
Logical operators are used to evaluate expressions and return a Boolean value. The
following table explains the usage of 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 Result

int x;
x = 20;
Result = (!( x == 10))
Console.WriteLine(“x is not equal to
10”);
The message “x is not equal to 10” is
displayed because the expression used in
the if statement is true.
Logical Operators
3.8 Operators and Programming Constructs ¤NIIT
Operator Usage Description Example
||
expression1 ||
expression2
Returns true if
either
expression1 or
expression2 or
both of them are
true.
bool Result;
string str1, str2;
str1 = "Korea";
str2 = "France";
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
¤NIIT Operators and Programming Constructs 3.9
The ability to take decisions is fundamental to human beings. Decision-making can be
incorporated into programs as well. This will result in determining the sequence in which
a program will execute instructions. You can control the flow of a program by using
conditional constructs. Conditional constructs allow the selective execution of statements,

depending on the value of the expressions 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
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 following code is an example of if else construct:
using System;
class LeapYear
{
static void Main(string[] args)
{
int Year;
Console.WriteLine("Enter the year: ");
Year = Convert.ToInt32(Console.ReadLine());
if ((Year % 4 == 0) && (Year % 100 != 0 || Year % 400 ==
0))
{

Console.WriteLine("The Year you have entered is a
Leap Year {0}", Year);
}
else
{
Using Conditional Constructs
The if…else Construct
3.10 Operators and Programming Constructs ¤NIIT
Console.WriteLine("The Year you have entered is not
a Leap Year {0}", Year);
}
Console.ReadLine();
}
}
The preceding code checks whether the year entered by the user is a Leap year. If the
condition specified in the
if statement is true, the statments in the if block are executed.
And if the condition specified in the
if statement is false, the statments in the else block
are executed.
The output of the preceding code is shown in the following figure.
Output of the Leap Year
The else part in the if else construct is optional and can be omitted, as shown in the
following code:
int var = 5;
if (var>0)
Console.WriteLine(“var is a positive number.”);
The if else constructs can be nested inside each other. When nested together, the
construct is known as cascading
if else constructs. The following code is an example

of the cascading
if else construct:
int Number1, Number2, Number3;
Number1 = 10;
Number2 = 20;
Number3 = 30;
if (Number1 > Number2)
¤NIIT Operators and Programming Constructs 3.11
N
ote
if (Number1 > Number3)
Console.WriteLine(“Number1 is the greatest.”);
else
Console.WriteLine(“Number3 is the greatest.”);
else
if (Number2 > Number3)
Console.WriteLine(“Number2 is the greatest.”);
else
Console.WriteLine(“Number3 is the greatest.”);
The preceding code displays the greatest of three numbers.
The cascading
if else construct can also be used with logical operators. The
following code is an example of converting the cascading
if else construct to an
if else construct by using logical operators:
int Number1, Number2, Number3;
Number1 = 10;
Number2 = 20;
Number3 = 30;
if ((Number1 > Number2) && (Number1 > Number3))

Console.WriteLine(“Number1 is the greatest”);
In the preceding code, the && operator is used to find the logical AND of two conditions.
The statement
Console.WriteLine(“Number1 is the greatest”) is executed only if
both the conditions evaluate to true.
In case of a logical OR operator (||), if the first condition evaluates to true, the second
condition is not evaluated.
Another conditional construct available in C# is the
switch case construct. It is used
when there are multiple values for a variable. The following code is the syntax of the
switch case construct:
switch (VariableName)
{
case ConstantExpression_1:
statements;
break;
case ConstantExpression_2:
statements;
break;

The switch…case Construct
3.12 Operators and Programming Constructs ¤NIIT
case ConstantExpression_n:
statements;
break;
default:
statements;
break;
}
When the switch statement is executed, the variable given in the switch statement is

evaluated and compared with each case constant. If one of the case constants is equal to
the value of the variable given in the
switch statement, control is passed to the statement
following the matched case label. A
break statement is used to exit the switch statement.
This prevents the execution of the remaining case structures by ending the execution of
the switch case construct. Each break statement terminates the enclosing switch
statement and the flow of control. If none of the cases match, the default case is
invoked.
The keyword switch is followed by the variable in parentheses:
switch(var)
Each case keyword is followed by a case constant:
case 1:
The data type of the case constant should match the data type of the switch variable.
Before entering the switch construct, a value should be assigned to the switch variable
You can substitute a complex
if else construct with the switch case construct.
The following code is an example of the complex if else construct:
int var;
var = 500;
if (var == 100)
Console.WriteLine("Century");
else if (var == 200)
Console.WriteLine("Double Century");
else if (var == 300)
Console.WriteLine("Triple Century");
else
Console.WriteLine("Invalid value");
The preceding code of the if else construct can be replaced by a switch case
construct, as shown in the following example:

int var;
var = 500;
switch(var)
{
case 100:
Console.WriteLine("Century");
¤NIIT Operators and Programming Constructs 3.13
N
ote
break;
case 200:
Console.WriteLine("Double Century");
break;
case 300:
Console.WriteLine("Triple Century");
break;
default:
Console.WriteLine("Invalid value");
break;

}
The switch case construct evaluates an expression only once at the top of the
structure, where as the
if else construct evaluates the expression for each if
statement.
The if else structure can be substituted with a switch case structure only if
each
else if statement in the if else construct evaluates the same
expression.
3.14 Operators and Programming Constructs ¤NIIT

Problem Statement
Write a program that emulates a calculator. The calculator should be able to perform the
following mathematical operations:
 Addition
 Subtraction
 Multiplication
 Division
Solution
To develop the required program, perform the following steps:
1. Select StartÆAll ProgramsÆAccessoriesÆNotepad.
2. Write the following program code in Notepad:
using System;
namespace Calculation
{
class CalculateNumber
{
int Number1, Number2;
char option;
int Result;
public void Number()
{
Console.WriteLine("Enter the First number");
Number1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second number");
Number2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Main Menu");
Console.WriteLine("1.Addition");
Console.WriteLine("2.Subtraction");
Console.WriteLine("3.Multiplication");
Console.WriteLine("4.Division");

Console.WriteLine("Enter the Operation you want to
perform");
option = Convert.ToChar(Console.ReadLine());
switch (option)
{
Activity: Calculator Using Conditional Constructs
¤NIIT Operators and Programming Constructs 3.15
case '1':
Result = Number1 + Number2;
Console.WriteLine("The result of
addition is:{0}", Result);
break;
case '2':
Result = Number1 - Number2;
Console.WriteLine("The result of
subtraction is:{0}", Result);
break;
case '3':
Result = Number1 * Number2;
Console.WriteLine("The result of
multiplication is:{0}", Result);
break;
case '4':
Result = Number1 / Number2;
Console.WriteLine("The result of
division is:{0}", Result);
break;
default:
Console.WriteLine("Invalid Option");
break;

}
Console.ReadLine();
}
}
class ClassMain
{
static void Main(string[] args)
{
CalculateNumber obj = new CalculateNumber();
obj.Number();
}
}
}
3. Select FileÆSave to save the program file. The Save As dialog box opens.
4. Enter “Calculator.cs” in the File name text box.
3.16 Operators and Programming Constructs ¤NIIT
N
ote
The filename is saved with .cs extension, signifying that it is a C# program.
5. Click the Save button in the Save As dialog box.
6. Select StartÆAll ProgramsÆMicrosoft Visual Studio 2005ÆVisual Studio
ToolsÆVisual Studio 2005 Command Prompt to open the Visual Studio 2005
Command Prompt window.
7. In the Visual Studio 2005 Command Prompt window, move to the location where
the program file is saved.
8. Compile the program file by using the following command:
csc Calculator.cs
9. Execute the compiled program as:
Calculator.exe
10. Verify the output of the executed program.

The following screen verifies the output of the executed program.
Output of the Executed Calculator Program
¤NIIT Operators and Programming Constructs 3.17
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
The
while loop construct is used to execute a block of statements for a definite number of
times, depending on a condition. The
while statement always checks the condition before
executing the statements within the loop. When the execution reaches the last statement in
the while loop, the control is passed back to the beginning of the loop. If the condition
still holds true, the statements within the loop are executed again. The execution of the
statements within the loop continues until the condition evaluates to false.
The following code is the syntax of the
while loop construct:
while (expression)
{
statements;
}
The following code is an example of the while loop construct:
using System;
class Variable
{
static void Main(string[]args)
{
int var;
var = 100;

while (var < 200)
{
Console.WriteLine ("Value of variable is: {0}", var);
var = var + 10;
Console.ReadLine();
}
}
}
The preceding code creates an integer variable var and assigns the value 100 to it. The
while statement checks whether the value of var is lower than 200. If the condition
evaluates to
true, the statements within the while loop are executed. This process
continues until the value of
var becomes greater than or equal to 200.
The while Loop
Using Loop Constructs
3.18 Operators and Programming Constructs ¤NIIT
The output of the preceding code when executed is as follows.
Output of the while Loop Program
You can use the break statement to exit the while loop structure. The following code is
an example of the
break statement:
int var;
var = 100;
while (true)
{
Console.WriteLine (“Value of var: ” + var);
var = var + 10;
if (var >= 200)
break;

}
In the preceding code, the while statement while (true) will always evaluate to true
and the while block will run an indefinite number of times. In such a case, the break
statement is used to exit the while loop block on the basis of the condition given within
the
while block. In the preceding example, the control moves out of the while loop when
the value of
var becomes greater than or equal to 200.
The
do while loop construct is similar to the while loop construct. Both iterate until
the specified loop condition becomes false. However, in the
do while loop, the body of
the loop is executed at least once and the condition is evaluated for subsequent iterations.
The do…while Loop
¤NIIT Operators and Programming Constructs 3.19
The following code is the syntax of the do while loop construct:
do
{
statements;
}while(expression);
Consider the following example of the do while loop construct:
int var;
var = 100;
do
{
Console.WriteLine (“Value of var: ” + var);
var = var + 10;
}
while (var < 200);
In the preceding code, the condition is checked after the statements in the do while

loop structure is executed. Therefore, the statements within the do while loop are
executed at least once, regardless of whether the condition evaluates to
true or false.
3.20 Operators and Programming Constructs ¤NIIT
while
This difference between the do while and while loop constructs is shown in the
following figure.
Difference in Execution of the do while and while Loops
The
for loop structure is used to execute a block of statements for a specific number of
times. The following code is the syntax of the
for loop construct:
for (initialization; termination; increment/decrement)
{
statements
}
The initialization expression initializes the for loop construct. It is executed once at the
beginning of the loop. The termination expression determines when to terminate the loop.
At the beginning of the loop, this expression is evaluated for each iteration. When the
expression evaluates to false, the loop terminates. Then, through the loop, the increment
or decrement expression gets invoked after each iteration. All these components are
optional.
The for Loop
False
do while
False
True
Execute body
of Loop
Evaluate

Condition
True
Execute body
of Loop
Evaluate
Condition
¤NIIT Operators and Programming Constructs 3.21
You can create an infinite loop by omitting all the three expressions, as shown in the
following code:
for ( ; ; )
{

}
The sequence of execution of a complete for loop construct is shown in the following
figure.
Sequence of Execution of the for Loop
False
True
Initialization
Evaluate
Condition
Body of the
for Loop
Exit the for
Loop
Increment/Decrement
3.22 Operators and Programming Constructs ¤NIIT
The following is an example of the for loop structure that displays integers between 10
and 20:
using System;

class Variable
{
static void Main(string[] args)
{
int var;
for (var=10; var <=20; var++)
{
Console.WriteLine ("Value of variable is:{0} ", var);
Console.ReadLine();
}
}
}
The output of the preceding code is as follows.
Output of the for Loop Program
¤NIIT Operators and Programming Constructs 3.23
Problem Statement
Write a program that generates the Fibonacci series up to 200.
Solution
To create the required program, perform the following steps:
1. Select StartÆAll ProgramsÆAccessoriesÆNotepad.
2. Write the following program code in Notepad:
using System;
class Fibonacci
{
static void Main(string[] args)
{
int number1;
int number2;
number1=number2=1;
Console.WriteLine("{0}", number1);

while (number2 < 200)
{
Console.WriteLine(number2);
number2 += number1;
number1 = number2-number1;
}
Console.ReadLine();
}
}
3. Select FileÆSave to save the program file. The Save As dialog box is displayed.
4. Enter “Fibonacci.cs” in the File name text box.
5. Click the Save button in the Save As dialog box.
6. Select StartÆAll ProgramsÆMicrosoft Visual Studio 2005ÆVisual Studio
ToolsÆVisual Studio 2005 Command Prompt to open the Visual Studio 2005
Command Prompt window.
7. In the Visual Studio 2005 Command Prompt window, move to the location where
the program file is saved.
8. Compile the program file by using the following command:
csc Fibonacci.cs
9. Execute the compiled program as:
Fibonacci.exe
10. Verify the output of the executed program.
Activity: Fibonacci Series Using Loop Constructs
3.24 Operators and Programming Constructs ¤NIIT
The following screen verifies the output of the executed program.
Output of the Fibonacci Series
At times, there is a need to exit a loop before the loop condition is re-evaluated after
iteration. As with a
while loop, you can use the break statement to exit for loop. The
continue statement is used to skip all the subsequent instructions and take the control

back to the loop.
The following code accepts five numbers and prints the sum of all the positive numbers:
using System;
class BreakContinue
{
static void Main(string[] args)
{
int incr, SumNum, number;
for (SumNum = number = incr = 0; incr < 5; incr += 1)
{
Console.WriteLine("Enter a positive number");
number = Convert.ToInt32(Console.ReadLine());
if (number <= 0) // Non-positive numbers
continue; // Continue to inctr+=1 in the forloop
SumNum = SumNum + number;
}
Console.WriteLine("The sum of positive numbers entered is
{0}", SumNum);
The break and continue Statements
¤NIIT Operators and Programming Constructs 3.25
Console.ReadLine();
}
}
The output of the preceding code is as follows.
Output of the break and continue Program

×