Operators and Programming Constructs pot

30 127 0
Operators and Programming Constructs pot

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

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) [...]... preceding code is x? a The character is X b The character is not X c Error message d X 2 To which category of operators do the ++ belong? a Arithmetic operators b Arithmetic assignment operators c Unary operators d Comparison operators 3.26 Operators and Programming Constructs NIIT 3 Which of the following operators can be used to evaluate an expression to true only if both the conditions are true? a && b ||... 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... forloop SumNum = SumNum + number; } Console.WriteLine("The sum of positive numbers entered is {0}", SumNum); 3.24 Operators and Programming Constructs NIIT } } Console.ReadLine(); The output of the preceding code is as follows Output of the break and continue Program NIIT Operators and Programming Constructs 3.25 Practice Questions 1 Consider the following code: static void Main(string[] args) { char character;... 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 NIIT Operators and Programming Constructs 3.27 Summary In this chapter, you learned that: Operators are used to compute and compare values and test... Visual Studio 2005 Command Prompt to open the Visual Studio 2005 Command Prompt window In the Visual Studio 2005 Command Prompt window, move to the location where the program file is saved 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 NIIT Operators and Programming Constructs 3.23 The... whether the condition evaluates to true or false NIIT Operators and Programming Constructs 3.19 This difference between the do while and while loop constructs is shown in the following figure do while while Execute body of Loop Evaluate Condition False True Evaluate Condition False Execute body of Loop True Difference in Execution of the do while and while Loops The for Loop The for loop structure is... File name text box Operators and Programming Constructs 3.15 Note The filename is saved with cs extension, signifying that it is a C# program 5 6 8 Click the Save button in the Save As dialog box 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 In the Visual Studio 2005 Command Prompt window,... following command: 9 Execute the compiled program as: 7 csc Calculator.cs 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 3.16 Operators and Programming Constructs NIIT Using Loop Constructs Loop structures are used to execute one or more lines of code repetitively The following loop constructs. .. 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: 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... 3.28 Operators and Programming Constructs NIIT Exercises Exercise 1 Write a program to identify whether a character entered by a user is a vowel or a consonant Exercise 2 Write a program to identify whether the number entered by a user is even or odd Exercise 3 Write a program to accept a number from the user and display all the prime numbers from zero up to the number entered by user NIIT Operators and . 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. 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. 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

Ngày đăng: 01/08/2014, 09:21

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan