Chapter 3: Writing C# Expressions

Size: px
Start display at page:

Download "Chapter 3: Writing C# Expressions"

Transcription

1 Page 1 of 19 Chapter 3: Writing C# Expressions In This Chapter Unary Operators Binary Operators The Ternary Operator Other Operators Enumeration Expressions Array Expressions Statements Blocks Labels Declarations Operator Precedence and Associativity C# provides a complete set of language elements for writing expressions. An expression is a set of language elements combined to perform a meaningful computation. This chapter provides guidance in building C# expressions. This chapter demonstrates expressions created with each of C# s built-in operators. All aspects of operators are covered in order to provide an understanding of their effects. There are four types of operators unary, binary, ternary, and a few others that don't fit into a category. Unary operators affect a single expression. Binary operators require two expressions to produce a result. The ternary operator has three expressions. The others can only be explained by reading each of their descriptions. For C++ and Java Programmers C# operators and their precedence are the same. No surprises here at all. If desired, you could skip this section without missing anything. Unary Operators As previously stated, unary operators affect a single expression. In many instances, the unary operators enable operations with simpler syntax than a comparable binary operation. The unary operators include + (plus), - (minus), ++ (increment), -- (decrement),! (logical negation), and ~ (bitwise complement). Note Mathematical operations on floating-point types are performed according to IEEE 754 arithmetic.

2 Page 2 of 19 The Plus Operator The plus operator (+) has no effect on the expression it s used with. Why would a language have an operator that has no effect? For consistency. Most C# operators have a logical complement. Since there is a minus operator, its logical complement is the plus operator. The + operator is available to explicitly document code. Here are a couple examples: int negative = -1; int positive = 1; int result; result = +negative; // result = -1 result = +positive; // result = 1 The Minus Operator The minus operator (-) allows negation of a variable s value. In integer and decimal types, the result is the number subtracted from ero. For floating-point types, the - operator inverts the sign of the number. When a value is NaN (not a number), the result is still NaN. Here are some examples: int negint = -1; decimal posdec = 1; float negflt = -1.1f; double nandbl = Double.NaN; int resint; decimal resdec; float resflt; double resdbl; resint = -negint; // resint = 1 resdec = -posdec; // resdec = -1 resflt = -negflt; // resflt = 1.1 resdbl = -nandbl; // resdbl = NaN The Increment Operator The increment operator (++) allows incrementing the value of a variable by 1. The timing of the effect of this operator depends upon which side of the expression it s on. Here s a post-increment example: int count; int index = 6; count = index++; // count = 6, index = 7 In this example, the ++ operator comes after the expression index. That s why it s called a postincrement operator. The assignment takes place and then index is incremented. Since the assignment occurs first, the value of index is placed into count, making it equal 6. Then index is incremented to become 7.

3 Page 3 of 19 Here s an example of a pre-increment operator: int count; int index = 6; count = ++index; // count = 7, index = 7 This time the ++ operator comes before the expression index. This is why it s called the pre-increment operator. Index is incremented before the assignment occurs. Since index is incremented first, its value becomes 7. Next, the assignment occurs to make the value of count equal 7. The Decrement Operator The decrement operator (--) allows decrementing the value of a variable. The timing of the effect of this operator again depends upon which side of the expression it is on. Here s a post-decrement example: int count; int index = 6; count = index--; // count = 6, index = 5 In this example, the -- operator comes after the expression index, and that s why it s called a postdecrement operator. The assignment takes place and then index is decremented. Since the assignment occurs first, the value of index is placed into count, making it equal 6. Then index is decremented to become 5. Here s an example of a pre-decrement operator: int count; int index = 6; count = --index; // count = 5, index = 5 This time the -- operator comes before the expression index, which is why it s called the pre-decrement operator. Index is decremented before the assignment occurs. Since index is decremented first, its value becomes 5, and then the assignment occurs to make the value of count equal 5. The Logical Complement Operator A logical complement operator (!) serves to invert the result of a Boolean expression. The Boolean expression evaluating to true will be false. Likewise, the Boolean expression evaluating to false will be true. Here are a couple examples: bool bexpr = true; bool bresult =!bexpr; // bresult = false bresult =!bresult; // bresult = true The Bitwise Complement Operator A bitwise complement operator (~) inverts the binary representation of an expression. All 1 bits are turned to 0. Likewise, all 0 bits are turned to 1. Here s an example:

4 Page 4 of 19 byte bitcomp = 15; // bitcomp = 15 = b byte bresult = (byte) ~bitcomp; // bresult = 240 = b Binary Operators Binary operators are those operators that work with two operands. For example, a common binary expression would be a + b the addition operator (+) surrounded by two operands. The binary operators are further subdivided into arithmetic, relational, logical, and assignment operators. Arithmetic Operators This is the first group of binary operators, those supporting arithmetic expressions. Arithmetic expressions are composed of two expressions with an arithmetic operator between them. This includes all the typical mathematical operators as expected in algebra. The Multiplication Operator The multiplication operator (*) evaluates two expressions and returns their product. Here's an example: int expr1 = 3; int expr2 = 7; int product; product = expr1 * expr2; // product = 21 The Division Operator The division operator (/), as its name indicates, performs mathematical division. It takes a dividend expression and divides it by a divisor expression to produce a quotient. Here's an example: int dividend = 45; int divisor = 5; int quotient; quotient = dividend / divisor; // quotient = 9 Notice the use of integers in this expression. Had the result been a fractional number, it would have been truncated to produce the integer result. The Remainder Operator The remainder operator (%) returns the remainder of a division operation between a dividend and divisor. A common use of this operator is to create equations that produce a remainder that falls within a specified range. Here's an example: int dividend = 33; int divisor = 10; int remainder; remainder = dividend % divisor; // remainder = 3 No matter what, as long as the divisor stays at 10, the remainder will always be between 0 and 9.

5 Page 5 of 19 The Addition Operator The addition operator (+) performs standard mathematical addition by adding one number to another. Here s an example: int one = 1; int two; two = one + one; // two = 2 The Subtraction Operator The subtraction operator (-) performs standard mathematical subtraction by subtracting the value of one expression from another. Here s an example: decimal debt = m; decimal payment = m; decimal balance; balance = debt - payment; // balance = The Left Shift Operator To shift the bits of a number to the left, use the left shift operator (<<). The effect of this operation is that all bits move to the left a specified number of times. High-order bits are lost. Lower order bits are ero filled. This operator may be used on the int, uint, long, and ulong data types. Here s an example. uint intmax = ; // b uint bytemask; bytemask = intmax << 8; // b The Right Shift Operator The right shift operator (>>) shifts the bits of a number to the right. By providing a number to operate on and the number of digits, every bit shifts to the right by the number of digits specified. Only use the right shift operator on int, uint, long, and ulong data types. The uint, ulong, positive int, and positive long types shift eros from the left. The negative int and negative long types keep a 1 in the sign bit position and fill the next position to the right with a 0. Here are some examples: uint intmax = ; // b uint shortmask; shortmask = intmax >> 16; // b int intmax = -1; // b int shortmask; shortmask = intmax >> 16; // b For Java Programmers C# doesn t have a right shift with ero extension operator (>>>).

6 Page 6 of 19 Relational Operators Relational operators are used to make a comparison between two expressions. The primary difference between relational operators and arithmetic operators is that relational operators return a bool type rather than a number. Another difference is that arithmetic operators are applicable to certain C# types whereas relational operators can be used on every possible C# type, whether built-in or not. Floating-point types are evaluated according to IEEE 754. The results of a relational expression are either true or false. The Equal Operator To see if two expressions are the same, use the equal operator (==). The equal operator works the same for integral, floating-point, decimal, and enum types. It simply compares the two expressions and returns a bool result. Here s an example: bool bresult; decimal debit = m; decimal credit = m; bresult = debit == credit; // bresult = false When comparing floating-point types, +0.0 and 0.0 are considered equal. If either floating-point number is NaN (not a number), equal returns false. The Not Equal Operator The not equal operator (!=) is the opposite of the equal operator for all types, with a slight variation for floating-point types only. If one of the floating-point numbers is NAN (not a number), not equal returns true. There are two forms of not equal applicable to expressions. The first is the normal not equal operator (! =). The other is a negation of the equal operator!(a==b). Normally, these two forms always evaluate to the same value. The exception occurs when evaluating floating-point expressions where one or both expressions evaluate to NaN and the relational operator in the negation of an expression is <, >, <=, or >=. The a > b form evaluates to false, but the!(a<=b) evaluates to true. Here are some examples: bool bresult; decimal debit = m; decimal credit = m; bresult = debit!= credit; // bresult = true bresult =!(debit == credit); // bresult = true The Less Than Operator If it s necessary to find out if one value is smaller than another, use the less than operator (<). The expression on the left is being evaluated and the expression on the right is the basis of comparison. When the expression on the left is a lower value than the expression on the right, the result is true. Otherwise, the result is false. Here s an example:

7 Page 7 of 19 short redbeads = 2; short whitebeads = 23; bool bresult; bresult = redbeads < whitebeads; // bresult=true, work harder The Greater Than Operator If it s necessary to know that a certain value is larger than another, use the greater than operator (>). It compares the expression on the left to the basis expression on the right. When the expression on the left is a higher value than the expression on the right, the result is true. Otherwise, the result is false. Here s an example: short redbeads = 13; short whitebeads = 12; bool bresult; bresult = redbeads > whitebeads; // bresult=true, good job! The Less Than or Equal Operator Sometimes it s necessary to know if a number is either lower than or equal to another number. That s what the less than or equal operator (<=) is for. The expression on the left is compared to the expression on the right. When the expression on the left is either the same value as or less than the one on the right, less than or equal returns true. This operator is the opposite of the greater than operator, which means that!(a>b) would produce the same results. The exception is when there s a floating-point expression evaluating to NaN, in which case the result is always true. Here s an example of the less than or equal operator: float limit = 4.0f; float currvalue = f; bool Bresult; bresult = currvalue <= limit; // bresult = true The Greater Than or Equal Operator As its name implies, the greater than or equal operator (>=) checks a value to see if it s greater than or equal to another. When the expression to the left of the operator is the same as or more than the expression on the right, greater than or equal returns true. The greater than or equal operator is the opposite of the less than operator. Here s an example: double rightangle = 90.0d; double myangle = 96.0d; bool isabtuse; isabtuse = myangle >= rightangle; // Yes, myangle is abtuse Logical Operators Logical operators perform Boolean logic on two expressions. There are three types of logical operators in C#: bitwise, Boolean, and conditional.

8 Page 8 of 19 The bitwise logical operators perform Boolean logic on corresponding bits of two integral expressions. Valid integral types are the signed and unsigned int and long types. They return a compatible integral result with each bit conforming to the Boolean evaluation. Boolean logical operators perform Boolean logic upon two Boolean expressions. The expression on the left is evaluated, and then the expression on the right is evaluated. Finally, the two expressions are evaluated together in the context of the Boolean logical operator between them. They return a bool result corresponding to the type of operator used. The conditional logical operators operate much the same way as the Boolean logical operators with one exception in behavior: Once the first expression is evaluated and found to satisfy the results of the entire expression, the second expression is not evaluated. This is efficient because it doesn t make sense to continue evaluating an expression when the result is already known. The Bitwise AND Operator The bitwise AND operator (&) compares corresponding bits of two integrals and returns a result with corresponding bits set to 1 when both integrals have 1 bits. When either or both integrals have a 0 bit, the corresponding result bit is 0. Here s an example: byte oddmask = 1; // b byte somebyte = 85; // b bool iseven; iseven = (oddmask & somebyte) == 0; //(oddmask & somebyte) = 1 The Bitwise Inclusive OR Operator The bitwise inclusive OR operator ( ) compares corresponding bits of two integrals and returns a result with corresponding bits set to 1 if either of the integrals have 1 bits in that position. When both integrals have a 0 in corresponding positions, the result is ero in that position. Here s an example: byte option1 = 1; // b byte option2 = 2; // b byte totaloptions; totaloptions = (byte) (option1 option2); // b The Bitwise Exclusive OR Operator The bitwise exclusive OR operator (^) compares corresponding bits of two integrals and returns a result with corresponding bits set to 1 if only one of the integrals has a 1 bit and the other integral has a 0 bit in that position. When both integral bits are 1 or when both are 0, the result s corresponding bit is 0. Here s an example: byte invertmask = 255; // b byte somebyte = 240; // b byte inverse; inverse = (byte)(somebyte ^ invertmask); //inversion= b The Boolean AND Operator

9 Page 9 of 19 The Boolean AND operator (&) evaluates two Boolean expressions and returns true when both expressions evaluate to true. Otherwise, the result is false. The result of each expression evaluated must return a bool result. Here s an example: bool instock = false; decimal price = 18.95m; bool buy; buy = instock & (price < 20.00m); // buy = false The Boolean Inclusive OR Operator The Boolean inclusive OR operator ( ) evaluates the results of two Boolean expressions and returns true if either of the expressions returns true. When both expressions are false, the result of the Boolean inclusive OR evaluation is false. Both expressions evaluated must return a bool type value. Here s an example: int mileage = 2305; int months = 4; bool changeoil; changeoil = mileage > 3000 months > 3; // changeoil = true The Boolean Exclusive OR Operator The Boolean exclusive OR operator (^) evaluates the results of two Boolean expressions and returns true if only one of the expressions returns true. When both expressions are true or both expressions are false, the result of the Boolean exclusive OR expression is false. In other words, the expressions must be different. Here s an example: bool availflag = false; bool toggle = true; bool available; available = availflag ^ toggle; // available = true The Conditional AND Operator The conditional AND operator (&&) is similar to the Boolean AND operator in that it evaluates two expressions and returns true when both expressions are true. It is different when the first expression evaluates to false. Since both expressions must be true, it s automatically assumed that if the first expression evaluates to false, the entire expression is false. Therefore, the conditional AND operator returns false and does not evaluate the second expression. When the first expression is true, the conditional AND operator goes ahead and evaluates the second expression. Here s an example: bool instock = false; decimal price = 18.95m; bool buy; buy = instock && (price < 20.00m); // buy = false Notice that price < 20 will never be evaluated.

10 Page 10 of 19 The Conditional OR Operator The conditional OR operator ( ) is similar to the Boolean inclusive OR operator ( ) in that it evaluates two expressions and returns true when either expression is true. The difference is when the first expression evaluates to true. Since either expression can be true to prove that the overall expression is true, the operator automatically assumes that the entire expression is true when it finds the first expression is true. Therefore, the conditional OR operator returns true without evaluating the second expression. When the first expression is false, the conditional OR operator goes ahead and evaluates the second expression. Here s an example: int mileage = 4305; int months = 4; bool changeoil; changeoil = mileage > 3000 months > 3; // changeoil = true Notice that because mileage > 3000 is true, months > 3 will never be evaluated. Side Effects Watch out for side effects with conditional Boolean operations. Side effects occur when your program depends on the expression on the right of the conditional logical operator being evaluated. If the expression on the right is not evaluated, this could cause a hard-to-find bug. The conditional logical operators are also called short circuit operators. Take a look at this example: decimal totalspending = m; decimal avgspending; bool onbudget = totalspending > m && totalspending < calcavg(); Notice that the second half of the expression was not evaluated. If calcavg() was supposed to change the value of a class field for later processing, there would be an error. Warning When using conditional AND and conditional OR operators, make sure a program does not depend upon evaluation of the right-hand side of the expression, because it may not be evaluated. Such side effects are likely to cause bugs. Assignment Operators This chapter has already demonstrated plenty of examples of the simple assignment operator in action. This section explains the compound operators and what can be expected from them. Basically, the concept is simple. A compound operator is a combination of the assignment operator and an arithmetic operator, bitwise logical operator, or Boolean logical operator. Here s an example:

11 Page 11 of 19 int total = 7; total += 3; // total = 10 This is the same as saying: total = total + 3. Table 3.1 shows a list of the available compound assignment operators. Table 3.1 Compound Assignment Operators Operator Function *= Multiplication /= Division %= Remainder += Addition -= Subtraction <<= Left Shift >>= Right Shift &= AND ^= Exclusive OR = Inclusive OR The Ternary Operator The ternary operator contains three expressions, thus the name ternary. The first expression must be a Boolean expression. When the first expression evaluates to true, the value of the second expression is returned. When the first expression evaluates to false, the value of the third expression is returned. This is a concise and short method of making a decision and returning a choice based upon the result of the decision. The ternary operator is often called the conditional operator. Here s an example: long democratvotes = ; long republicanvotes = ; string headline = democratvotes!= republicanvotes? "We Finally Have a Winner!" : recount(); Other Operators C# has some operators that can t be categoried as easily as the other types. These include the is, as, sieof(), typeof(), checked(), and unchecked() operators. The following sections explain each operator. The is Operator The is operator checks a variable to see if it s a given type. If so, it returns true. Otherwise, it returns false. Here s an example.

12 Page 12 of 19 int i = 0; bool istest = i is int; // istest = true The as Operator The as operator attempts to perform a conversion on a reference type. The following example tries to convert the integer i into a string. If the conversion were successful, the object variable obj would hold a reference to a string object. When the conversion from an as operator fails, it assigns null to the receiving reference. That s the case in this example where obj becomes null because i is an integer, not a string: int i = 0; object obj = i as string; Console.WriteLine("i {0} a string.", obj == null? "is not" : "is" ); // i is not a string. The sieof() Operator C# provides a facility to perform low-level functions through a construct known as unsafe code. The sieof() operator works only in unsafe code. The operator takes a type and returns the type s sie in bytes. Here s an example: unsafe { int intsie = sieof(int); // intsie = 4 } The typeof() Operator The typeof() operator returns a Type object. The Type class holds type information about a value or reference type. The typeof() operator is used in various places in C# to discover information about reference and value types. The following example gets type information on the int type: Type mytype = typeof(int); Console.WriteLine( "The int type: {0}", mytype ); // The int type: Int32 The checked() Operator The checked() operator detects overflow conditions in certain operations. The following example causes a system error by attempting to assign a value to a short variable that it can t hold: short val1 = 20000, val2 = 20000; short myshort = checked((short)(val1 + val2)); // error The unchecked() Operator If it is necessary to ignore this error and accept the results regardless of overflow conditions, use the unchecked() operator as in this example: short val1 = 20000, val2 = 20000;

13 Page 13 of 19 short myshort = unchecked((short)(val1 + val2)); // error ignored Tip Use the /checked[+ -] command line option when the majority of program code should be checked (/checked+) or unchecked (/checked-). Then all that needs to be done inside the code is to annotate the exceptions with the checked() and unchecked() operators. Enumeration Expressions The elements of enumeration expressions evaluate the same as their underlying types. In addition to using normal operators, there are additional methods that can be performed with an enum type. An Enum class is used to obtain the majority of functionality shown in this section. Where the Enum class is being used, the capitalied Enum class name prefixes the method call. The examples in this section refer to the following enum: enum Weekday { Mon = 1, Tue, Wed, Thu, Fri, Sat = 10, Sun }; For C++ Programmers C# enums have much more functionality than C++ enums. As a typed value, the enum must be assigned to a variable of its type. For example, the underlying representation of a Weekday enum may default to an integral value, but it s still a Weekday type. The following line shows the declaration and initialiation of an enum variable: Weekday w = Weekday.Mon; During a Console.WriteLine() method call, enum values are printed with their names rather than their underlying integral values. Here s an example: Console.WriteLine("WeekDay: {0}", w); // WeekDay: Mon The Format() method returns the string representation of an enum value, as shown here: Console.WriteLine("Format: {0}", w.format()); // Format: Mon To go in the opposite direction and convert a string to an enum, use the FromString() method. The arguments it accepts are the enum type, the string representation of the value to be converted, and a Boolean condition to verify case. The following example uses the typeof() operator to get the enum type. The string to be converted is Tue, and the method is case-sensitive.

14 Page 14 of 19 Console.WriteLine("FromString: {0}", Enum.FromString(typeof(EnumTest.Weekday), "Tue", true)); // FromString: Tue To get the name of an enum variable, use the GetName() method. The following example shows the GetName() method accepting the enum type and an instance of that enum type and returning its name as a string. w = EnumTest.Weekday.Wed; Console.WriteLine("GetName: {0}", Enum.GetName(typeof(EnumTest.Weekday), w)); // GetName: Wed If there is a need to get the string representations of all the members of an enum, use the GetNames() method plural of the previous method. The following example shows an array being filled with the names. The method call only needs the enum type. string[] weekdays = new string[7]; weekdays = Enum.GetNames(typeof(EnumTest.Weekday)); Console.WriteLine("Day 1: {0}", weekdays[0]); // Day 1: Mon Console.WriteLine("Day 2: {0}", weekdays[1]); // Day 2: Tue Console.WriteLine("Day 3: {0}", weekdays[2]); // Day 3: Wed Console.WriteLine("Day 4: {0}", weekdays[3]); // Day 4: Thu Console.WriteLine("Day 5: {0}", weekdays[4]); // Day 5: Fri Console.WriteLine("Day 6: {0}", weekdays[5]); // Day 6: Sat Console.WriteLine("Day 7: {0}", weekdays[6]); // Day 7: Sun A corresponding method to get the values of an enum is the GetValues() method. The following example shows the GetValues() method accepting an enum type and returning an array of objects. Notice that the array is of type objects. In C#, all types are also object types. Therefore, any type can be assigned to the object type. object[] weekdayvals = new object[7]; weekdayvals = Enum.GetValues(typeof(EnumTest.Weekday)); Console.WriteLine("Day 1: {0}", weekdayvals[0]); // Day 1: Mon Console.WriteLine("Day 2: {0}", weekdayvals[1]); // Day 2: Tue Console.WriteLine("Day 3: {0}", weekdayvals[2]); // Day 3: Wed Console.WriteLine("Day 4: {0}", weekdayvals[3]); // Day 4: Thu Console.WriteLine("Day 5: {0}", weekdayvals[4]); // Day 5: Fri Console.WriteLine("Day 6: {0}", weekdayvals[5]); // Day 6: Sat Console.WriteLine("Day 7: {0}", weekdayvals[6]); // Day 7: Sun To find out the underlying type of an enum, use the GetUnderlyingType() method. It accepts an enum type argument, and the return value is the integral type of the enum's underlying type. Here's an example: Console.WriteLine("Underlying Type: {0}", Enum.GetUnderlyingType( typeof(enumtest.weekday))); // Underlying Type: Int32 When it's necessary to determine if an enum value is defined, use the IsDefined() method. It accepts an enum type and an enum value and returns a Boolean true if the value is defined in the enum. Otherwise, it returns false. Here's an example:

15 Page 15 of 19 w = EnumTest.Weekday.Thu; Console.WriteLine("Thu is Defined: {0}", Enum.IsDefined(typeof(EnumTest.Weekday), w)); // Thu is Defined: True To obtain an enum type that is set to a specific value, use the ToObject() method. The following example shows the method accepting an enum type and an integer, and returning an enum of the requested type with the value corresponding to the integer. Console.WriteLine("Get Friday: {0}", Enum.ToObject(typeof(EnumTest.Weekday), 5)); // Get Friday: Fri Array Expressions Besides being an efficient storage construct, arrays have additional functionality that helps make programs more expressive and powerful. The following example shows one such capability: string[] weekdays = new string[7]; Console.WriteLine("Number of Days: {0}", weekdays.length); // Number of Days: 7 For C++ Programmers From the perspective of traditional built-into-the-language arrays, C++ arrays are simply a pointer to a block of memory. This refers to the C++ arrays derived from its C language ancestry. C# arrays have much more functionality. The C++ STL array class is similar to the C# ArrayList collection class. Both are library classes. The previous example showed the array s Length property. The array type has many more methods and properties, as shown in Table 3.2. Table 3.2 C# Array Members Method/Property AsList BinarySearch Clear Copy Description Returns an Ilist representation of the array Finds a value in a one-dimensional array using a binary search Cleans out a range of array values by setting them to 0 or null Copies a range of array elements to another array

16 Page 16 of 19 CreateInstance IndexOf LastIndexOf Reverse Sort IsReadOnly IsSynchronied Length Rank SyncRoot Clone CopyTo Equals GetEnumerator GetHashCode GetLength GetLowerBound GetType GetUpperBound GetValue Initialie SetValue ToString Creates a new instance of an array Finds the first occurrence of a value and returns its index Finds the last occurrence of a value and returns its index Reverses the elements of a one-dimensional array Sorts a one-dimensional array Returns true if read-only Returns true if synchronied Returns the number of elements in all dimensions Returns the number of dimensions Returns array synchroniation object Performs a shallow copy Copies from one array to another Compares array references for equality Returns an IEnumerator of a onedimensional array Returns a unique identifier Returns the number of elements in specified dimension Returns the lower bound of a dimension Returns the Type object Returns the upper bound of a dimension Returns values from specified elements Calls the default constructor of each element Sets values of specified elements Returns a string representation Statements Statements in C# are single entities that cause a change in the program s current state. They re commonly associated with some type of assignment statement, changing the value of a variable. A statement ends with a semicolon (;). Leave one out and the compiler will issue a prompt notification. Statements may span multiple lines, which could help make your code more readable, as the following example shows: decimal closingcosts = loanorigination + appraisal + titlesearch

17 Page 17 of 19 + insuranceadvance + taxadvance + points + realtorcommission + whateverelsetheycanripyouofffor; Had the statement been placed on one line, it would have either continued off the right side of the page or wrapped around in an inconvenient location. This way, each item is visible, lined up nicely, and easier to understand. Blocks Setting off code in blocks clearly delimits the beginning and ending of a unit of work and establishes scope. Begin a block of code with a left-hand brace ({), and end it with a right-hand brace (}). Blocks are required to specify the boundaries of many language elements such as classes, interfaces, structures, properties, indexers, events, and methods. Labels Labels are program elements that simply identify a location in a program. Their only practical use is to support the goto statement. The goto statement allows program control to jump to the place where a label is defined. A label is any valid identifier followed by a colon (not a semicolon). Here are two examples: loop: // a label named "loop" jumphere: // a label named "jumphere" Declarations Declarations enable definition and announcement of the existence and nature of program data. There are two forms of declaration in C#: simple declaration and declaration with initialiation. A simple declaration takes the following form: <type> <identifier>; The type may be any C# or user-defined type. The identifier is any valid identifier as defined in Chapter 2, "Getting Started with C#." A declaration with initialiation looks like this: <type> <identifier> = <expression>; The type and identifier are the same as the previous example. The equal sign takes the evaluated expression on its right and loads it into the variable declared on the left. The expression can be any valid C# statement evaluating to the type of variable specified by type. The declaration is a statement followed by a semicolon. Operator Precedence and Associativity

18 Page 18 of 19 When evaluating C# expressions, there are certain rules to ensure the outcome of the evaluation. These rules are governed by precedence and associativity and preserve the semantics of all C# expressions. Precedence refers to the order in which operations should be evaluated. Sub-expressions with higher operator precedence are evaluated first. There are two types of associativity: left and right. Operators with left associativity are evaluated from left to right. When an operator has right associativity, its expression is evaluated from right to left. For example, the assignment operator is right associative. Therefore, the expression to its right is evaluated before the assignment operation is invoked. Table 3.3 shows the C# operators, their precedence, and associativity. Certain operators have precedence over others to guarantee the certainty and integrity of computations. One effective rule of thumb when using most operators is to remember their algebraic precedence. Here s an example: int result; result = * 9; // result = 32 This computes 3 * 9 = = 32. To alter the order of operations use parentheses, which have a higher precedence: result = (5 + 3) * 9; // result = 72 This time, 5 and 3 were added to get 8 and then multiplied by 9 to get 72. See Table 3.3 for a listing of operator precedence and associativity. Operators in top rows have precedence over operators in lower rows. Operators on the left in each row have higher precedence over operators to the right in the same row. Table 3.3 Operator Precedence and Associativity Operators (x), x.y, f(x), a[x], x++, x- -, new, typeof, sieof, checked, unchecked + (unary), (unary), ~, ++x, - -x, (T)x Associativity Left Left *, / % Left + (arithmetic), (arithmetic) Left <<, >> Left <, >, <=, >=, is, as Left ==,!= Left & Left ^ Left Left

19 Page 19 of 19 && Left Left?: Right =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, = Right Summary This chapter covered the various C# operators unary, arithmetic, relational operators, and other operators and provided examples of how to use them. The unary operators include plus, minus, increment, decrement, logical complement, and bitwise complement operators. Binary operators include the arithmetic, logical, relational and assignment operators. There is a single ternary operator that produces conditional results. C# has a few other operators that don't fit into the any of those categories; they include the is, as, typeof, sieof, checked, and unchecked operators. The enum and array types have additional functions that make programs more expressive and powerful. I included several examples of enums and a table of array methods and properties. This chapter also described statements, blocks, labels, and declarations, and included a section about operator precedence and associativity. Having mastered the material in this chapter, it's simple to move into logical manipulation of program flow. Copyright Pearson Education. All rights reserved.

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Chapter 2: Elements of Java

Chapter 2: Elements of Java Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

More information

Example of a Java program

Example of a Java program Example of a Java program class SomeNumbers static int square (int x) return x*x; public static void main (String[] args) int n=20; if (args.length > 0) // change default n = Integer.parseInt(args[0]);

More information

JavaScript: Control Statements I

JavaScript: Control Statements I 1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1 7.2 Algorithms 3 Any computable problem can

More information

AP Computer Science Java Subset

AP Computer Science Java Subset APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

More information

Chapter 3 Operators and Control Flow

Chapter 3 Operators and Control Flow Chapter 3 Operators and Control Flow I n this chapter, you will learn about operators, control flow statements, and the C# preprocessor. Operators provide syntax for performing different calculations or

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void 1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of

More information

6.087 Lecture 2 January 12, 2010

6.087 Lecture 2 January 12, 2010 6.087 Lecture 2 January 12, 2010 Review Variables and data types Operators Epilogue 1 Review: C Programming language C is a fast, small,general-purpose,platform independent programming language. C is used

More information

Introduction to Python

Introduction to Python Caltech/LEAD Summer 2012 Computer Science Lecture 2: July 10, 2012 Introduction to Python The Python shell Outline Python as a calculator Arithmetic expressions Operator precedence Variables and assignment

More information

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything

More information

Selection Statements

Selection Statements Chapter 5 Selection Statements 1 Statements So far, we ve used return statements and expression ess statements. e ts. Most of C s remaining statements fall into three categories: Selection statements:

More information

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system. http://www.tutorialspoint.com/java/java_quick_guide.htm JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural- neutral

More information

Computer Science 281 Binary and Hexadecimal Review

Computer Science 281 Binary and Hexadecimal Review Computer Science 281 Binary and Hexadecimal Review 1 The Binary Number System Computers store everything, both instructions and data, by using many, many transistors, each of which can be in one of two

More information

Statements and Control Flow

Statements and Control Flow Contents 1. Introduction 2. Types and Variables 3. Statements and Control Flow 4. Reading Input 5. Classes and Objects 6. Arrays 7. Methods 8. Scope and Lifetime 9. Utility classes 10. Introduction to

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

VB.NET Programming Fundamentals

VB.NET Programming Fundamentals Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements

More information

JavaScript: Introduction to Scripting. 2008 Pearson Education, Inc. All rights reserved.

JavaScript: Introduction to Scripting. 2008 Pearson Education, Inc. All rights reserved. 1 6 JavaScript: Introduction to Scripting 2 Comment is free, but facts are sacred. C. P. Scott The creditor hath a better memory than the debtor. James Howell When faced with a decision, I always ask,

More information

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved.

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved. 1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays

More information

PL / SQL Basics. Chapter 3

PL / SQL Basics. Chapter 3 PL / SQL Basics Chapter 3 PL / SQL Basics PL / SQL block Lexical units Variable declarations PL / SQL types Expressions and operators PL / SQL control structures PL / SQL style guide 2 PL / SQL Block Basic

More information

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example Operator Overloading Lecture 8 Operator Overloading C++ feature that allows implementer-defined classes to specify class-specific function for operators Benefits allows classes to provide natural semantics

More information

C++ Language Tutorial

C++ Language Tutorial cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain

More information

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority) Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

More information

The C Programming Language course syllabus associate level

The C Programming Language course syllabus associate level TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

More information

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions Phys4051: C Lecture 2 & 3 Functions (Review) Comment Statements Variables & Operators Branching Instructions Comment Statements! Method 1: /* */! Method 2: // /* Single Line */ //Single Line /* This comment

More information

The programming language C. sws1 1

The programming language C. sws1 1 The programming language C sws1 1 The programming language C invented by Dennis Ritchie in early 1970s who used it to write the first Hello World program C was used to write UNIX Standardised as K&C (Kernighan

More information

Numeral Systems. The number twenty-five can be represented in many ways: Decimal system (base 10): 25 Roman numerals:

Numeral Systems. The number twenty-five can be represented in many ways: Decimal system (base 10): 25 Roman numerals: Numeral Systems Which number is larger? 25 8 We need to distinguish between numbers and the symbols that represent them, called numerals. The number 25 is larger than 8, but the numeral 8 above is larger

More information

CS 111 Classes I 1. Software Organization View to this point:

CS 111 Classes I 1. Software Organization View to this point: CS 111 Classes I 1 Software Organization View to this point: Data Objects and primitive types Primitive types operators (+, /,,*, %). int, float, double, char, boolean Memory location holds the data Objects

More information

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca

More information

Binary Division. Decimal Division. Hardware for Binary Division. Simple 16-bit Divider Circuit

Binary Division. Decimal Division. Hardware for Binary Division. Simple 16-bit Divider Circuit Decimal Division Remember 4th grade long division? 43 // quotient 12 521 // divisor dividend -480 41-36 5 // remainder Shift divisor left (multiply by 10) until MSB lines up with dividend s Repeat until

More information

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand: Introduction to Programming and Algorithms Module 2 CS 146 Sam Houston State University Dr. Tim McGuire Introduction To Computers And Java Chapter Objectives To understand: the meaning and placement of

More information

PHP Tutorial From beginner to master

PHP Tutorial From beginner to master PHP Tutorial From beginner to master PHP is a powerful tool for making dynamic and interactive Web pages. PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.

More information

DNA Data and Program Representation. Alexandre David 1.2.05 adavid@cs.aau.dk

DNA Data and Program Representation. Alexandre David 1.2.05 adavid@cs.aau.dk DNA Data and Program Representation Alexandre David 1.2.05 adavid@cs.aau.dk Introduction Very important to understand how data is represented. operations limits precision Digital logic built on 2-valued

More information

2010/9/19. Binary number system. Binary numbers. Outline. Binary to decimal

2010/9/19. Binary number system. Binary numbers. Outline. Binary to decimal 2/9/9 Binary number system Computer (electronic) systems prefer binary numbers Binary number: represent a number in base-2 Binary numbers 2 3 + 7 + 5 Some terminology Bit: a binary digit ( or ) Hexadecimal

More information

Objective-C Tutorial

Objective-C Tutorial Objective-C Tutorial OBJECTIVE-C TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i ABOUT THE TUTORIAL Objective-c tutorial Objective-C is a general-purpose, object-oriented programming

More information

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures The C++ Language Loops Loops! Recall that a loop is another of the four basic programming language structures Repeat statements until some condition is false. Condition False True Statement1 2 1 Loops

More information

6. Control Structures

6. Control Structures - 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,

More information

EE 261 Introduction to Logic Circuits. Module #2 Number Systems

EE 261 Introduction to Logic Circuits. Module #2 Number Systems EE 261 Introduction to Logic Circuits Module #2 Number Systems Topics A. Number System Formation B. Base Conversions C. Binary Arithmetic D. Signed Numbers E. Signed Arithmetic F. Binary Codes Textbook

More information

Sources: On the Web: Slides will be available on:

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

More information

Oct: 50 8 = 6 (r = 2) 6 8 = 0 (r = 6) Writing the remainders in reverse order we get: (50) 10 = (62) 8

Oct: 50 8 = 6 (r = 2) 6 8 = 0 (r = 6) Writing the remainders in reverse order we get: (50) 10 = (62) 8 ECE Department Summer LECTURE #5: Number Systems EEL : Digital Logic and Computer Systems Based on lecture notes by Dr. Eric M. Schwartz Decimal Number System: -Our standard number system is base, also

More information

Programming languages C

Programming languages C INTERNATIONAL STANDARD ISO/IEC 9899:1999 TECHNICAL CORRIGENDUM 2 Published 2004-11-15 INTERNATIONAL ORGANIZATION FOR STANDARDIZATION МЕЖДУНАРОДНАЯ ОРГАНИЗАЦИЯ ПО СТАНДАРТИЗАЦИИ ORGANISATION INTERNATIONALE

More information

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language Simple C++ Programs Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input and Output Basic Functions from

More information

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science updated 03/08/2012 Unit 1: JKarel 8 weeks http://www.fcps.edu/is/pos/documents/hs/compsci.htm

More information

The Clean programming language. Group 25, Jingui Li, Daren Tuzi

The Clean programming language. Group 25, Jingui Li, Daren Tuzi The Clean programming language Group 25, Jingui Li, Daren Tuzi The Clean programming language Overview The Clean programming language first appeared in 1987 and is still being further developed. It was

More information

Lecture 8: Binary Multiplication & Division

Lecture 8: Binary Multiplication & Division Lecture 8: Binary Multiplication & Division Today s topics: Addition/Subtraction Multiplication Division Reminder: get started early on assignment 3 1 2 s Complement Signed Numbers two = 0 ten 0001 two

More information

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 The Java Type System By now, you have seen a fair amount of Java. Time to study in more depth the foundations of the language,

More information

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer About The Tutorial C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system.

More information

Number Representation

Number Representation Number Representation CS10001: Programming & Data Structures Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Topics to be Discussed How are numeric data

More information

Click on the links below to jump directly to the relevant section

Click on the links below to jump directly to the relevant section Click on the links below to jump directly to the relevant section What is algebra? Operations with algebraic terms Mathematical properties of real numbers Order of operations What is Algebra? Algebra is

More information

Numbering Systems. InThisAppendix...

Numbering Systems. InThisAppendix... G InThisAppendix... Introduction Binary Numbering System Hexadecimal Numbering System Octal Numbering System Binary Coded Decimal (BCD) Numbering System Real (Floating Point) Numbering System BCD/Binary/Decimal/Hex/Octal

More information

1 Introduction. 2 An Interpreter. 2.1 Handling Source Code

1 Introduction. 2 An Interpreter. 2.1 Handling Source Code 1 Introduction The purpose of this assignment is to write an interpreter for a small subset of the Lisp programming language. The interpreter should be able to perform simple arithmetic and comparisons

More information

Divide: Paper & Pencil. Computer Architecture ALU Design : Division and Floating Point. Divide algorithm. DIVIDE HARDWARE Version 1

Divide: Paper & Pencil. Computer Architecture ALU Design : Division and Floating Point. Divide algorithm. DIVIDE HARDWARE Version 1 Divide: Paper & Pencil Computer Architecture ALU Design : Division and Floating Point 1001 Quotient Divisor 1000 1001010 Dividend 1000 10 101 1010 1000 10 (or Modulo result) See how big a number can be

More information

Chapter 7D The Java Virtual Machine

Chapter 7D The Java Virtual Machine This sub chapter discusses another architecture, that of the JVM (Java Virtual Machine). In general, a VM (Virtual Machine) is a hypothetical machine (implemented in either hardware or software) that directly

More information

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share. LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.

More information

if and if-else: Part 1

if and if-else: Part 1 if and if-else: Part 1 Objectives Write if statements (including blocks) Write if-else statements (including blocks) Write nested if-else statements We will now talk about writing statements that make

More information

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

3.GETTING STARTED WITH ORACLE8i

3.GETTING STARTED WITH ORACLE8i Oracle For Beginners Page : 1 3.GETTING STARTED WITH ORACLE8i Creating a table Datatypes Displaying table definition using DESCRIBE Inserting rows into a table Selecting rows from a table Editing SQL buffer

More information

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be... What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control

More information

COMPUTER SCIENCE 1999 (Delhi Board)

COMPUTER SCIENCE 1999 (Delhi Board) COMPUTER SCIENCE 1999 (Delhi Board) Time allowed: 3 hours Max. Marks: 70 Instructions: (i) All the questions are compulsory. (ii) Programming Language: C++ QUESTION l. (a) Why main function is special?

More information

Java (12 Weeks) Introduction to Java Programming Language

Java (12 Weeks) Introduction to Java Programming Language Java (12 Weeks) Topic Lecture No. Introduction to Java Programming Language 1 An Introduction to Java o Java as a Programming Platform, The Java "White Paper" Buzzwords, Java and the Internet, A Short

More information

Data Storage: Each time you create a variable in memory, a certain amount of memory is allocated for that variable based on its data type (or class).

Data Storage: Each time you create a variable in memory, a certain amount of memory is allocated for that variable based on its data type (or class). Data Storage: Computers are made of many small parts, including transistors, capacitors, resistors, magnetic materials, etc. Somehow they have to store information in these materials both temporarily (RAM,

More information

Pemrograman Dasar. Basic Elements Of Java

Pemrograman Dasar. Basic Elements Of Java Pemrograman Dasar Basic Elements Of Java Compiling and Running a Java Application 2 Portable Java Application 3 Java Platform Platform: hardware or software environment in which a program runs. Oracle

More information

Microsoft Access 3: Understanding and Creating Queries

Microsoft Access 3: Understanding and Creating Queries Microsoft Access 3: Understanding and Creating Queries In Access Level 2, we learned how to perform basic data retrievals by using Search & Replace functions and Sort & Filter functions. For more complex

More information

Lecture 2 Notes: Flow of Control

Lecture 2 Notes: Flow of Control 6.096 Introduction to C++ January, 2011 Massachusetts Institute of Technology John Marrero Lecture 2 Notes: Flow of Control 1 Motivation Normally, a program executes statements from first to last. The

More information

I PUC - Computer Science. Practical s Syllabus. Contents

I PUC - Computer Science. Practical s Syllabus. Contents I PUC - Computer Science Practical s Syllabus Contents Topics 1 Overview Of a Computer 1.1 Introduction 1.2 Functional Components of a computer (Working of each unit) 1.3 Evolution Of Computers 1.4 Generations

More information

Basic Programming and PC Skills: Basic Programming and PC Skills:

Basic Programming and PC Skills: Basic Programming and PC Skills: Texas University Interscholastic League Contest Event: Computer Science The contest challenges high school students to gain an understanding of the significance of computation as well as the details of

More information

Binary storage of graphs and related data

Binary storage of graphs and related data EÖTVÖS LORÁND UNIVERSITY Faculty of Informatics Department of Algorithms and their Applications Binary storage of graphs and related data BSc thesis Author: Frantisek Csajka full-time student Informatics

More information

Java Basics: Data Types, Variables, and Loops

Java Basics: Data Types, Variables, and Loops Java Basics: Data Types, Variables, and Loops If debugging is the process of removing software bugs, then programming must be the process of putting them in. - Edsger Dijkstra Plan for the Day Variables

More information

CHAPTER 2. Logic. 1. Logic Definitions. Notation: Variables are used to represent propositions. The most common variables used are p, q, and r.

CHAPTER 2. Logic. 1. Logic Definitions. Notation: Variables are used to represent propositions. The most common variables used are p, q, and r. CHAPTER 2 Logic 1. Logic Definitions 1.1. Propositions. Definition 1.1.1. A proposition is a declarative sentence that is either true (denoted either T or 1) or false (denoted either F or 0). Notation:

More information

Base Conversion written by Cathy Saxton

Base Conversion written by Cathy Saxton Base Conversion written by Cathy Saxton 1. Base 10 In base 10, the digits, from right to left, specify the 1 s, 10 s, 100 s, 1000 s, etc. These are powers of 10 (10 x ): 10 0 = 1, 10 1 = 10, 10 2 = 100,

More information

Useful Number Systems

Useful Number Systems Useful Number Systems Decimal Base = 10 Digit Set = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} Binary Base = 2 Digit Set = {0, 1} Octal Base = 8 = 2 3 Digit Set = {0, 1, 2, 3, 4, 5, 6, 7} Hexadecimal Base = 16 = 2

More information

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser) High-Level Programming Languages Nell Dale & John Lewis (adaptation by Michael Goldwasser) Low-Level Languages What are disadvantages of low-level languages? (e.g., machine code or assembly code) Programming

More information

Certified PHP Developer VS-1054

Certified PHP Developer VS-1054 Certified PHP Developer VS-1054 Certification Code VS-1054 Certified PHP Developer Vskills certification for PHP Developers assesses the candidate for developing PHP based applications. The certification

More information

Chapter One Introduction to Programming

Chapter One Introduction to Programming Chapter One Introduction to Programming 1-1 Algorithm and Flowchart Algorithm is a step-by-step procedure for calculation. More precisely, algorithm is an effective method expressed as a finite list of

More information

Lecture 1 Introduction to Java

Lecture 1 Introduction to Java Programming Languages: Java Lecture 1 Introduction to Java Instructor: Omer Boyaci 1 2 Course Information History of Java Introduction First Program in Java: Printing a Line of Text Modifying Our First

More information

Introduction to Visual C++.NET Programming. Using.NET Environment

Introduction to Visual C++.NET Programming. Using.NET Environment ECE 114-2 Introduction to Visual C++.NET Programming Dr. Z. Aliyazicioglu Cal Poly Pomona Electrical & Computer Engineering Cal Poly Pomona Electrical & Computer Engineering 1 Using.NET Environment Start

More information

Chapter 5. Selection 5-1

Chapter 5. Selection 5-1 Chapter 5 Selection 5-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow

More information

3.2 The Factor Theorem and The Remainder Theorem

3.2 The Factor Theorem and The Remainder Theorem 3. The Factor Theorem and The Remainder Theorem 57 3. The Factor Theorem and The Remainder Theorem Suppose we wish to find the zeros of f(x) = x 3 + 4x 5x 4. Setting f(x) = 0 results in the polynomial

More information

Ed. v1.0 PROGRAMMING LANGUAGES WORKING PAPER DRAFT PROGRAMMING LANGUAGES. Ed. v1.0

Ed. v1.0 PROGRAMMING LANGUAGES WORKING PAPER DRAFT PROGRAMMING LANGUAGES. Ed. v1.0 i PROGRAMMING LANGUAGES ii Copyright 2011 Juhász István iii COLLABORATORS TITLE : PROGRAMMING LANGUAGES ACTION NAME DATE SIGNATURE WRITTEN BY István Juhász 2012. március 26. Reviewed by Ágnes Korotij 2012.

More information

6.170 Tutorial 3 - Ruby Basics

6.170 Tutorial 3 - Ruby Basics 6.170 Tutorial 3 - Ruby Basics Prerequisites 1. Have Ruby installed on your computer a. If you use Mac/Linux, Ruby should already be preinstalled on your machine. b. If you have a Windows Machine, you

More information

plc numbers - 13.1 Encoded values; BCD and ASCII Error detection; parity, gray code and checksums

plc numbers - 13.1 Encoded values; BCD and ASCII Error detection; parity, gray code and checksums plc numbers - 3. Topics: Number bases; binary, octal, decimal, hexadecimal Binary calculations; s compliments, addition, subtraction and Boolean operations Encoded values; BCD and ASCII Error detection;

More information

Semantic Analysis: Types and Type Checking

Semantic Analysis: Types and Type Checking Semantic Analysis Semantic Analysis: Types and Type Checking CS 471 October 10, 2007 Source code Lexical Analysis tokens Syntactic Analysis AST Semantic Analysis AST Intermediate Code Gen lexical errors

More information

Computer Programming C++ Classes and Objects 15 th Lecture

Computer Programming C++ Classes and Objects 15 th Lecture Computer Programming C++ Classes and Objects 15 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2013 Eom, Hyeonsang All Rights Reserved Outline

More information

Exercise 4 Learning Python language fundamentals

Exercise 4 Learning Python language fundamentals Exercise 4 Learning Python language fundamentals Work with numbers Python can be used as a powerful calculator. Practicing math calculations in Python will help you not only perform these tasks, but also

More information

Levent EREN levent.eren@ieu.edu.tr A-306 Office Phone:488-9882 INTRODUCTION TO DIGITAL LOGIC

Levent EREN levent.eren@ieu.edu.tr A-306 Office Phone:488-9882 INTRODUCTION TO DIGITAL LOGIC Levent EREN levent.eren@ieu.edu.tr A-306 Office Phone:488-9882 1 Number Systems Representation Positive radix, positional number systems A number with radix r is represented by a string of digits: A n

More information

High-Precision C++ Arithmetic

High-Precision C++ Arithmetic Base One International Corporation 44 East 12th Street New York, NY 10003 212-673-2544 info@boic.com www.boic.com High-Precision C++ Arithmetic - Base One s Number Class fixes the loopholes in C++ high-precision

More information

IV-1Working with Commands

IV-1Working with Commands Chapter IV-1 IV-1Working with Commands Overview... 2 Multiple Commands... 2 Comments... 2 Maximum Length of a Command... 2 Parameters... 2 Liberal Object Names... 2 Data Folders... 3 Types of Commands...

More information

Limitation of Liability

Limitation of Liability Limitation of Liability Information in this document is subject to change without notice. THE TRADING SIGNALS, INDICATORS, SHOWME STUDIES, PAINTBAR STUDIES, PROBABILITYMAP STUDIES, ACTIVITYBAR STUDIES,

More information

Maple Introductory Programming Guide

Maple Introductory Programming Guide Maple Introductory Programming Guide M. B. Monagan K. O. Geddes K. M. Heal G. Labahn S. M. Vorkoetter J. McCarron P. DeMarco Maplesoft, a division of Waterloo Maple Inc. 1996-2008. ii Maplesoft, Maple,

More information

Solution for Homework 2

Solution for Homework 2 Solution for Homework 2 Problem 1 a. What is the minimum number of bits that are required to uniquely represent the characters of English alphabet? (Consider upper case characters alone) The number of

More information

Math Review. for the Quantitative Reasoning Measure of the GRE revised General Test

Math Review. for the Quantitative Reasoning Measure of the GRE revised General Test Math Review for the Quantitative Reasoning Measure of the GRE revised General Test www.ets.org Overview This Math Review will familiarize you with the mathematical skills and concepts that are important

More information

J a v a Quiz (Unit 3, Test 0 Practice)

J a v a Quiz (Unit 3, Test 0 Practice) Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points

More information

General Software Development Standards and Guidelines Version 3.5

General Software Development Standards and Guidelines Version 3.5 NATIONAL WEATHER SERVICE OFFICE of HYDROLOGIC DEVELOPMENT Science Infusion Software Engineering Process Group (SISEPG) General Software Development Standards and Guidelines 7/30/2007 Revision History Date

More information