A condition is an expression that can be either true or false. This section introduces a simple version of C#'s if statement that allows an application to make a decision based on the value of a condition. For example, the condition "grade is greater than or equal to 60" determines whether a student passed a test. If the condition in an if statement is true, the body of the if statement executes. If the condition is false, the body does not execute. We will see an example shortly.
Conditions in if statements can be formed by using the equality operators (==, and !=) and relational operators (>, <, >= and <=) summarized in Fig. 3.25. The two equality operators (== and !=) each have the same level of precedence, the relational operators (>, <, >= and <=) each have the same level of precedence, and the equality operators have lower precedence than the relational operators. They all associate from left to right.
Standard algebraic equality and relational operators |
C# equality or relational operator |
Sample C# condition |
Meaning of C# condition |
---|---|---|---|
Equality operators |
|||
= |
== |
x == y |
x is equal to y |
!= |
x != y |
x is not equal to y |
|
Relational operators |
|||
> |
> |
x > y |
x is greater than y |
< |
< |
x < y |
x is less than y |
>= |
x >= y |
x is greater than or equal to y |
|
<= |
x <= y |
x is less than or equal to y |
The application of Fig. 3.26 uses six if statements to compare two integers entered by the user. If the condition in any of these if statements is true, the assignment statement associated with that if statement executes. The application uses the Console class to prompt for and read two lines of text from the user, extracts the integers from that text with the ToInt32 method of class Convert, and stores them in variables number1 and number2. Then the application compares the numbers and displays the results of the comparisons that are true.
Figure 3.26. Comparing integers using if statements, equality operators and relational operators.
(This item is displayed on pages 103 - 104 in the print version)
1 // Fig. 3.26: Comparison.cs 2 // Comparing integers using if statements, equality operators, 3 // and relational operators. 4 using System; 5 6 public class Comparison 7 { 8 // Main method begins execution of C# application 9 public static void Main( string[] args ) 10 { 11 int number1; // declare first number to compare 12 int number2; // declare second number to compare 13 14 //prompt user and read first number 15 Console.Write( "Enter first integer: " ); 16 number1 = Convert.ToInt32( Console.ReadLine() ); 17 18 //prompt user and read second number 19 Console.Write( "Enter second integer: " ); 20 number2 = Convert.ToInt32( Console.ReadLine() ); 21 22 if ( number1 == number2 ) 23 Console.WriteLine( "{0} == {1}", number1, number2 ); 24 25 if ( number1 != number2 ) 26 Console.WriteLine( "{0} != {1}", number1, number2 ); 27 28 if ( number1 < number2 ) 29 Console.WriteLine( "{0} < {1}", number1, number2 );30 31 if ( number1 > number2 ) 32 Console.WriteLine( "{0} > {1}", number1, number2 ); 33 34 if ( number1 <= number2 ) 35 Console.WriteLine( "{0} <= {1}", number1, number2 ); 36 37 if ( number1 >= number2 ) 38 Console.WriteLine( "{0} >= {1}", number1, number2 ); 39 } // end method Main 40 } // end class Comparison
|
The declaration of class Comparison begins at line 6
public class Comparison
The class's Main method (lines 939) begins the execution of the application.
Lines 1112
int number1; // declare first number to compare int number2; // declare second number to compare
declare the int variables used to store the values entered by the user.
Lines 1416
// prompt user and read first number Console.Write( "Enter first integer: " ); number1 = Convert.ToInt32( Console.ReadLine() );
prompt the user to enter the first integer and input the value. The input value is stored in variable number1.
Lines 18-20
// prompt user and read second number Console.Write( "Enter second integer: " ); number2 = Convert.ToInt32( Console.ReadLine() );
perform the same task, except that the input value is stored in variable number2.
Lines 2223
if ( number1 == number2 ) Console.WriteLine( "{0} == {1}", number1, number2 );
compare the values of the variables number1 and number2 to determine whether they are equal. An if statement always begins with keyword if, followed by a condition in parentheses. An if statement expects one statement in its body. The indentation of the body statement shown here is not required, but it improves the code's readability by emphasizing that the statement in line 23 is part of the if statement that begins in line 22. Line 23 executes only if the numbers stored in variables number1 and number2 are equal (i.e., the condition is true). The if statements in lines 2526, 2829, 3132, 3435 and 3738 compare number1 and number2 with the operators !=, <, >, <= and >=, respectively. If the condition in any of the if statements is true, the corresponding body statement executes.
|
|
|
|
Note that there is no semicolon (;) at the end of the first line of each if statement. Such a semicolon would result in a logic error at execution time. For example,
if ( number1 == number2 ); // logic error Console.WriteLine( "{0} == {1}", number1, number2 );
would actually be interpreted by C# as
if ( number1 == number2 ) ; // empty statement Console.WriteLine( "{0} == {1}", number1, number2 );
where the semicolon in the line by itselfcalled the empty statementis the statement to execute if the condition in the if statement is true. When the empty statement executes, no task is performed in the application. The application then continues with the output statement, which always executes, regardless of whether the condition is true or false, because the output statement is not part of the if statement.
|
Note the use of whitespace in Fig. 3.26. Recall that whitespace characters, such as tabs, newlines and spaces, are normally ignored by the compiler. So statements may be split over several lines and may be spaced according to your preferences without affecting the meaning of an application. It is incorrect to split identifiers, strings, and multicharacter operators (like >=). Ideally, statements should be kept small, but this is not always possible.
|
|
Figure 3.27 shows the precedence of the operators introduced in this chapter. The operators are shown from top to bottom in decreasing order of precedence. All these operators, with the exception of the assignment operator, =, associate from left to right. Addition is left associative, so an expression like x + y + z is evaluated as if it had been written as ( x + y ) + z. The assignment operator, =, associates from right to left, so an expression like x = y = 0 is evaluated as if it had been written as x = ( y = 0 ), which, as you will soon see, first assigns the value 0 to variable y and then assigns the result of that assignment, 0, to x.
Operators |
Associativity |
Type |
|||
---|---|---|---|---|---|
* |
/ |
% |
left to right |
multiplicative |
|
+ |
- |
left to right |
additive |
||
< |
<= |
> |
>= |
left to right |
relational |
== |
!= |
left to right |
equality |
||
= |
right to left |
assignment |
|
Preface
Index
Introduction to Computers, the Internet and Visual C#
Introduction to the Visual C# 2005 Express Edition IDE
Introduction to C# Applications
Introduction to Classes and Objects
Control Statements: Part 1
Control Statements: Part 2
Methods: A Deeper Look
Arrays
Classes and Objects: A Deeper Look
Object-Oriented Programming: Inheritance
Polymorphism, Interfaces & Operator Overloading
Exception Handling
Graphical User Interface Concepts: Part 1
Graphical User Interface Concepts: Part 2
Multithreading
Strings, Characters and Regular Expressions
Graphics and Multimedia
Files and Streams
Extensible Markup Language (XML)
Database, SQL and ADO.NET
ASP.NET 2.0, Web Forms and Web Controls
Web Services
Networking: Streams-Based Sockets and Datagrams
Searching and Sorting
Data Structures
Generics
Collections
Appendix A. Operator Precedence Chart
Appendix B. Number Systems
Appendix C. Using the Visual Studio 2005 Debugger
Appendix D. ASCII Character Set
Appendix E. Unicode®
Appendix F. Introduction to XHTML: Part 1
Appendix G. Introduction to XHTML: Part 2
Appendix H. HTML/XHTML Special Characters
Appendix I. HTML/XHTML Colors
Appendix J. ATM Case Study Code
Appendix K. UML 2: Additional Diagram Types
Appendix L. Simple Types
Index