The following is the syntax of the if...else construct: Console.WriteLine"The Year you have entered is a } else { Using Conditional Constructs The if…else Construct... Output of
Trang 1Operators 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:
Use conditional constructs
Use looping constructs
Objectives
Trang 3Applications 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:
These operators are the symbols that are used to perform arithmetic operations on
variables The following table describes the commonly used arithmetic operators
Trang 4Operator Description Example
Operator Usage Description
= X = 5; Stores the value 5 in the variable X
Arithmetic Assignment Operators
Arithmetic Assignment Operators
Trang 5These 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
++ ++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
Trang 6These 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
Trang 7Logical 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
! ! 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
Trang 8Operator Usage Description Example
|| expression1 ||
expression2
Returns true if either expression1 or expression2 or both of them are true
^ 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
Logical Operators
Trang 9The 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:
Theif else construct
Theswitch 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:
Console.WriteLine("The Year you have entered is a
}
else
{
Using Conditional Constructs
The if…else Construct
Trang 10Console.WriteLine("The Year you have entered is not
a Leap Year {0}", Year);
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)
Trang 11Console.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:
Trang 12The following code is an example of the complexif elseconstruct:
Trang 13Theswitch caseconstruct evaluates an expression only once at the top of the
structure, where as theif elseconstruct 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
Trang 14To develop the required program, perform the following steps:
1 Select StartÆAll ProgramsÆAccessoriesÆNotepad.
2 Write the following program code in Notepad:
Trang 153 Select FileÆSave to save the program file The Save As dialog box opens
4 Enter “Calculator.cs” in the File name text box
Trang 16Note
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
Trang 17Loop structures are used to execute one or more lines of code repetitively The following loop constructs are supported by C#:
Thewhile loop
Thedo while loop
Thefor 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:
continues until the value of var becomes greater than or equal to 200
The while Loop
Using Loop Constructs
Trang 18The 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:
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
Trang 19The following code is the syntax of the do while loop construct:
Trang 20This difference between the do while and whileloop 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)
True
Execute body
of Loop
Evaluate Condition
Trang 21You can create an infinite loop by omitting all the three expressions, as shown in the following code:
Body of the for Loop
Exit the for Loop
Increment/Decrement
Trang 22The following is an example of the for loop structure that displays integers between 10and 20:
The output of the preceding code is as follows
Output of the for Loop Program
Trang 23Problem 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:
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
Trang 24The 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 continuestatement 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;
Trang 25Console.ReadLine();
}
}
The output of the preceding code is as follows
Output of the break and continue Program
Trang 26Note
1 Consider the following code:
static void Main(string[] args)
The Convert.ToChar() converts a value to the char datatype
What will be the output if the input of the preceding code is x?
Trang 273 Which of the following operators can be used to evaluate an expression to true only
if both the conditions are true?
a &&
b ||
c >=
d !=
4 State whether the following statement is true or false:
The continue statement if used in the while and do while loop causes the program control to pass to the top of the loop avoiding the other statements in the loop
5 State whether the following statement is true or false:
A termination expression is evaluated at each iteration of the for loop
Trang 28In this chapter, 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
Conditional constructs are used to allow the selective execution of statements The conditional constructs in C# are: