Operator precedence and associativity

Size: px
Start display at page:

Download "Operator precedence and associativity"

Transcription

1 Operator precedence and associativity In mathematics, an operation is a mathematical calculation involving zero or more input values (called operands) that produces an output value. Common operations (such as addition) use special symbols (such as +) that denote the operation. These symbols are called operators. Operators in programming work the same way except the names may not always be a symbol. Operators work analogously to functions that take input parameters and return a value, except they are more concise. For example, + * is much easier to read than add(, mult(, ))! In order to properly evaluate an expression such as + *, we must understand both what the operators do, and the correct order to apply them. The order in which operators are evaluated in a compound expression is called operator precedence. Using normal mathematical precedence rules (which state that multiplication is resolved before addition), we know that the above expression should evaluate as + ( * ) to produce the value 0. In C++, when the compiler encounters an expression, it must similarly analyze the expression and determine how it should be evaluated. To assist with this, all operators are assigned a level of precedence. Those with the highest precedence are evaluated first. You can see in the table below that multiplication and division (precedence level ) have a higher precedence than addition and subtraction (precedence level ). The compiler uses these levels to determine how to evaluate expressions it encounters. Thus, + * evaluates as + ( * ) because multiplication has a higher level of precedence than addition. If two operators with the same precedence level are adjacent to each other in an expression, the operator associativity rules tell the compiler whether to evaluate the operators from left to right or from right to left. For example, in the expression * /, the multiplication and division operators are both precedence level. Level has an associativity of left to right, so the expression is resolved from left to right: ( * ) / =.

2 Table of operators Notes: Precedence level is the highest precedence level, and level is the lowest. Operators with a higher precedence level get evaluated first. L->R means left to right associativity. R->L means right to left associativity. Lvalue (locator value), rvalue Prec/ Ass None :: :: L->R R->L ! ~ Operator Description Pattern () () () } type() type} []. -> ++ typeid const_cast dynamic_ca st reinterpret_ cast static_cast Global scope (unary) Class scope (binary) Parentheses Function call Initialization Uniform initialization (C+ +) Functional cast Functional cast (C++) Array subscript Member access from object Member access from object ptr Post-increment Post-decrement Run-time type information Cast away const Run-time type-checked cast Cast one type to another Compile-time typechecked cast Unary plus Unary minus Pre-increment Pre-decrement Logical NOT Bitwise NOT ::name class_name::member_name (expression) function_name(parameters) type name(expression) type nameexpression} new_type(expression) new_typeexpression} pointer[expression] object.member_name object_pointer- >member_name lvalue++ lvalue typeid(type) or typeid(expression) const_cast<type>(expression ) dynamic_cast<type>(express ion) reinterpret_cast<type>(expre ssion) static_cast<type>(expression ) +expression -expression ++lvalue lvalue!expression ~expression

3 L->R ->*.* L->R L->R + - (type) sizeof & * new new[] delete delete[] * / % L->R << >> 8 L->R < <= > >= 9 L->R ==!= 0 L- >R L- >R L- >R L- >R L- >R C-style cast Size in bytes Address of Dereference Dynamic memory allocation Dynamic array allocation Dynamic memory deletion Dynamic array deletion Member pointer selector Member object selector Multiplication Division Modulus Addition Subtraction Bitwise shift left Bitwise shift right Comparison less than Comparison less than or equals Comparison greater than Comparison greater than or equals Equality Inequality (new_type)expression sizeof(type) or sizeof(expression) &lvalue *expression new type new type[expression] delete pointer delete[] pointer object_pointer- >*pointer_to_member object.*pointer_to_member expression * expression expression / expression expression % expression expression + expression expression - expression expression << expression expression >> expression expression < expression expression <= expression expression > expression expression >= expression expression == expression expression!= expression & Bitwise AND expression & expression ^ Bitwise XOR expression ^ expression Bitwise OR expression expression && Logical AND expression && expression Logical OR expression expression R-?: Conditional (see note expression? expression :

4 >L R- >L = *= /= %= += -= <<= >>= &= = ^= below) Assignment Multiplication assignment Division assignment Modulus assignment Addition assignment Subtraction assignment Bitwise shift left assignment Bitwise shift right assignment Bitwise AND assignment Bitwise OR assignment Bitwise XOR assignment expression lvalue = expression lvalue *= expression lvalue /= expression lvalue %= expression lvalue += expression lvalue -= expression lvalue <<= expression lvalue >>= expression lvalue &= expression lvalue = expression lvalue ^= expression throw Throw expression throw expression L-, Comma operator expression, expression >R Note: The expression in the middle of the conditional operator?: is evaluated as if it were parenthesized. A few operators you should already recognize: +, -, *, /, (), =, <, >, <=, and >=. These arithmetic and relational operators have the same meaning in C++ as they do in every-day usage. However, unless you have experience with another programming language, it s likely the majority of the operators in this table will be incomprehensible to you right now. That s expected at this point. We ll cover many of them in this chapter, and the rest will be introduced as there is a need for them. The above table is primarily meant to be a reference chart that you can refer back to in the future to resolve any precedence or associativity questions you have. That said, if you have an expression that uses operators of different types, it is a best practice to use parenthesis to explicitly disambiguate the order of evaluation. Rule: If your expression uses different operators, use parenthesis to make it clear how the expression should evaluate, even if they are technically

5 unnecessary. How do I do exponents? You ll note that the ^ operator (commonly used to denote exponentiation in standard mathematical nomenclature) is a Bitwise XOR operation in C++. C++ does not include an exponent operator. To do exponents in C++, #include the <cmath> header, and use the pow() function: #include <cmath> double x = pow(.0,.0); // to the th power Note that the parameters and return value of pow are of type double. Note that due to rounding errors in floating point numbers, the results of pow() may not be precise (slightly smaller or larger than what you d expect). If you want to do integer exponents, you re best off just using your own function to do so, like this one (that uses the exponentiation by squaring algorithm for efficiency): // note: exp must be non-negative int pow(int base, int exp) int result = ; while (exp) if (exp & ) result *= base; exp >>= ; base *= base; } return result; }

6 Don t worry if you don t understand all of the parts of this function yet. Just beware of overflowing your integer result, which can happen very quickly if either argument is large. Arithmetic operators Unary arithmetic operators There are two unary arithmetic operators, plus (+), and minus (-). If you remember, unary operators are operators that only take one operand. Operator Symb ol Unary plus For m Operation + +x Value of x Unary Negation - -x minus of x The unary plus operator returns the value of the operand. In other words, + =, and +x = x. Generally you won t need to use this operator since it s redundant. It was added largely to provide symmetry with the unary minus operator. The unary minus operator returns the operand multiplied by -. In other words, if x =, -x = -. For best effect, both of these operators should be placed immediately preceding the operand (eg. -x, not - x). Do not confuse the unary minus operator with the binary subtraction operator, which uses the same symbol. For example, in the expression x = - -;, the first minus is the subtraction operator, and the second is the unary minus operator. Binary arithmetic operators There are binary arithmetic operators. Binary operators are operators that take a left and right operand.

7 Operator Addition + Symb ol For m x + y x plus y Subtraction - x - y x minus y Multiplication * x * y Operation x multiplied by y Division / x / y x divided by y Modulus x % The remainder of x % (Remainder) y divided by y The addition, subtraction, and multiplication operators work just like they do in real life, with no caveats. Division and modulus (remainder) need some additional explanation. Integer and floating point division It is easiest to think of the division operator as having two different modes. If both of the operands are integers, the division operator performs integer division. Integer division drops any fractions and returns an integer value. For example, / = because the fraction is dropped. Note that integer division does not round. If either or both of the operands are floating point values, the division operator performs floating point division. Floating point division returns a floating point value, and the fraction is kept. For example,.0 / =., /.0 =., and.0 /.0 =.. Note that trying to divide by 0 (or 0.0) will generally cause your program to crash, as the results are undefined! Using static_cast<> to do floating point division with integers We can similarly use static_cast<> to convert an integer to a floating point number so that we can do floating point division instead of integer division. Consider the following code: #include <iostream> int main()

8 8 9 0 int x = ; int y = ; std::cout << "int / int = " << x / y << "\n"; std::cout << "double / int = " << static_cast<double>(x) / y << "\n"; std::cout << "int / double = " << x / static_cast<double>(y) << "\n"; std::cout << "double / double = " << static_cast<double>(x) / static_cast<double>(y) << "\n"; } return 0; This produces the result: int / int = double / int =. int / double =. double / double =. Modulus (remainder) The modulus operator is also informally known as the remainder operator. The modulus operator only works on integer operands, and it returns the remainder after doing integer division. For example, / = remainder, thus % =. As another example, / = remainder, thus % =. Modulus is very useful for testing whether a number is evenly divisible by another number: if x % y == 0, then we know that y divides evenly into x. For example, say we wanted to write a program that printed every number from to 00 with 0 numbers per line. We could use the modulus operator to determine where to do the line breaks. Even though you haven t seen a while statement yet, the following program should be pretty comprehensible: #include <iostream> int main() // count holds the current number to print

9 int count = ; // start at // Loop continually until we pass number 00 while (count <= 00) std::cout << count << " "; // print the current number // if count is evenly divisible by 0, print a new line if (count % 0 == 0) std::cout << "\n"; count = count + ; // go to next number } // end of while return 0; } // end of main() This results in: We ll discuss while statements in a future lesson. A warning about integer division and modulus with negative numbers

10 prior to C++ Prior to C++, if either of the operands of integer division are negative, the compiler is free to round up or down! For example, - / can evaluate to either - or -, depending on which way the compiler rounds. However, most modern compilers truncate towards 0 (so - / would equal -). The C++ specification changed this to explicitly define that integer division should always truncate towards 0 (or put more simply, the fractional component is dropped). Also prior to C++, if either operand of the modulus operator is negative, the results of the modulus can be either negative or positive! For example, - % can evaluate to either or -. The C++ specification tightens this up so that a % b always resolves to the sign of a. Arithmetic assignment operators Operator Symb ol Form Operation Assignment = x = y Assign value y to x Addition assignment += Subtraction assignment Multiplication assignment -= *= Division assignment /= x += y x -= y x *= y Add y to x Subtract y from x Multiply x by y x /= y Divide x by y x %= Put the remainder of x / Modulus assignment %= y y in x Up to this point, when you ve needed to add to a variable, you ve likely done the following: x = x + ; This works, but it s a little clunky, and takes two operators to execute. Because writing statements such as x = x + is so common, C++ provides arithmetic assignment operators for convenience. Instead of writing x = x +, you can write x +=. Instead of x = x * y, you can write x *= y.

11 Where s the exponent operator? Astute readers will note that there is no exponent operator. Instead, you have to use the pow() function that lives in the cmath library. pow(base, exponent) is the equivalent of base exponent. It s worth noting that the parameters to pow() are doubles, so it can handle non-integer exponents #include <cmath> // needed for pow() #include <iostream> int main() std::cout << "Enter the base: "; double base; std::cin >> base; } std::cout << "Enter the exponent: "; double exp; std::cin >> exp; std::cout << base << "^" << exp << " = " << pow(base, exp) << "\n"; return 0; Increment/decrement operators, and side effects Incrementing (adding to) and decrementing (subtracting from) a variable are

12 so common that they have their own operators in C. There are actually two versions of each operator -- a prefix version and a postfix version. Operator Prefix increment (preincrement) Prefix decrement (predecrement) Postfix increment (postincrement) Symb ol For m ++ ++x x ++ x++ Operation Increment x, then evaluate x Decrement x, then evaluate x Evaluate x, then increment x Postfix decrement (postdecrement) decrement x Evaluate x, then - - x- - The prefix increment/decrement operators are very straightforward. The value of x is incremented or decremented, and then x is evaluated. For example: int x = ; int y = ++x; // x is now equal to, and is assigned to y The postfix increment/decrement operators are a little more tricky. The compiler makes a temporary copy of x, increments or decrements the original x (not the copy), and then evaluates the temporary copy of x. The temporary copy of x is then discarded. int x = ; int y = x++; // is assigned to y, and x is now equal to Let s examine how this last line works in more detail. First, the compiler makes a temporary copy of x that starts with the same value as x (). Then it increments the original x from to. Then the compiler evaluates the temporary copy, which evaluates to, and assigns that value to y. Then the temporary copy is discarded. Consequently, y ends up with the value of, and x ends up with the value. Here is another example showing the difference between the prefix and postfix versions: int x =, y = ; cout << x << " " << y << endl; cout << ++x << " " << --y << endl; // prefix

13 cout << x << " " << y << endl; cout << x++ << " " << y-- << endl; // postfix cout << x << " " << y << endl; This produces the output: On the third line, x and y are incremented/decremented before they are evaluated, so their new values are printed by cout. On the fifth line, a temporary copy of the original values (x=, y=) is sent to cout, and then the original x and y are incremented. That is why the changes from the postfix operators don t show up until the next line. Rule: Favor pre-increment and pre-decrement over post-increment and postdecrement. The prefix versions are not only more performant, you re less likely to run into strange issues with them. Side effects A function or expression is said to have a side effect if it modifies some state (e.g. any stored information in memory), does input or output, or calls other functions that have side effects. Most of the time, side effects are useful: x = ; ++x; std::cout << x; The assignment operator in the above example has the side effect of changing the value of x permanently. Even after the statement has finished executing, x will have the value. Operator++ has the side effect of incrementing x. The outputting of x has the side effect of modifying the console. However, side effects can also lead to unexpected results: int add(int x, int y)

14 8 9 0 return x + y; } int main() int x = ; int value = add(x, ++x); // is this +, or +? It depends on what order your compiler evaluates the function arguments in std::cout << value; // value could be or, depending on how the above line evaluates! return 0; } C++ does not define the order in which function arguments are evaluated. If the left argument is evaluated first, this becomes a call to add(, ), which equals. If the right argument is evaluated first, this becomes a call to add(, ), which equals! Note that this is only a problem because one of the argument to function add() has a side effect. Here s another popular example: 8 int main() int x = ; x = x++; std::cout << x; return 0; } What value does this program print? The answer is: it s undefined. If the ++ is applied to x before the assignment, the answer will be (postfix operator++ increments x from to, but it evaluates to, so the expression becomes x = ). If the ++ is applied to x after the assignment, the answer will be (this evaluates as x = x, then postfix operator++ is applied, incrementing x from to ).

15 There are other cases where C++ does not specify the order in which certain things are evaluated, so different compilers will make different assumptions. Even when C++ does make it clear how things should be evaluated, some compilers implement behaviors involving variables with side-effects incorrectly. These problems can generally all be avoided by ensuring that any variable that has a side-effect applied is used no more than once in a given statement. Rule: Don t use a variable that has a side effect applied to it more than once in a given statement. If you do, the result may be undefined. Please don t ask why your programs that violate the above rule produce results that don t seem to make sense. That s what happens when you write programs that have undefined behavior. Sizeof, comma, and conditional operators Sizeof operator Operator Symbol Form Operation Sizeof sizeof sizeof(type) sizeof(variable) Returns size of type or variable in bytes Note that sizeof can also be used on a variable, and will return the size of that variable: #include <iostream> int main() double d =.0; std::cout << sizeof(d); // will print the size of variable d in bytes } Comma operator Operator Symbol Comma, Operation Evaluate x then y, returns value of y

16 The comma operator allows you to evaluate multiple expressions wherever a single expression is allowed. The comma operator evaluates to its rightmost operand. For example: int x = 0; int y = ; int z = (++x, ++y); // increment x and y z would be assigned the result of evaluating ++y, which equals. In almost every case, a statement written using a comma would be better written as separate statements. For example, the above code should be written as: int x = 0; int y = ; ++x; ++y; int z = y; Note that comma has the lowest precedence of all the operators, even lower than assignment. Because of this, the following two lines of code do different things: z = (a, b); // evaluate (a, b) first to get result of b, then assign that value to variable z. z = a, b; // evaluates as "(z = a), b", so z gets assigned the value of a, and b is discarded. Most programmers do not use the comma operator at all, with the single exception of inside for loops, where its use is fairly common. We discuss for loops in a future lesson. Note that although a comma is used to separate the parameters in a function call, this is not using the comma operator. int sum = add(x, y); // this comma is not the comma operator Similarly, when declaring multiple variables on a single line, the comma there is just a normal separator, not the comma operator

17 int x(), y(); // this comma is not the comma operator either Rule: Avoid using the comma operator, except within for loops. Conditional operator Operator Symbol Form Operation If c is nonzero (true) then evaluate x, Conditional?: c? x : y otherwise evaluate y The conditional operator (?:) (also known as the arithmetic if operator) is C+ + s only ternary operator (it takes operands). Because of this, it s also sometimes referred to as the ternary operator (we suggest you avoid calling it this in case C++ adds another ternary operator in the future). The?: operator provides a shorthand method for doing a particular type of if/else statement. If/else statements in the following form: if (condition) expression; else other_expression; can be rewritten as: (condition)? expression : other_expression; Note that the operands of the conditional operator must be expressions themselves (not statements). For example, an if/else statement that looks like this: if (condition) x = some_value else x = some_other_value can be rewritten as: x = (condition)? some_value : some_other_value; Many people find this more compact form easier to read.

18 As another example, to put the larger of values x and y in variable larger, we could write this: if (x > y) larger = x; else larger = y; Or this: larger = (x > y)? x : y; It is common to put the conditional part of the expression inside of parenthesis, both to make it easier to read, and also to make sure the precedence is correct. It is also worth noting that the expression between the? and : is evaluated as if it were parenthesized. Keep in mind that the?: operator has a very low precedence. If doing anything other than assigning the result to a variable, the?: statement needs to be wrapped in parenthesis. For example to print the larger of values x and y to the screen, we could do this: if (x > y) std::cout << x; else std::cout << y; Or we could do this: std::cout << ((x > y)? x : y); Because the << operator has higher precedence than the?: operator, the statement: std::cout << (x > y)? x : y; would evaluate as: (std::cout << (x > y))? x : y; That would print (true) if x > y, or 0 (false) otherwise! The conditional operator gives us a convenient way to simplify simple if/else

19 statements, particularly when assigning the result to a variable or returning the result as part of a function return. It should not be used for complex if/else statements, as it quickly becomes both unreadable and error prone. Rule: Only use the conditional operator for simple conditionals where it enhances readability. The conditional operator evaluates as an expression It s worth noting that the conditional operator evaluates as an expression, whereas if/else evaluates as statements. This means the conditional operator can be used in some places where if/else can not. For example, when initializing a const variable: bool inbigclassroom = false; const int classsize = inbigclassroom? 0 : 0; There s no satisfactory if/else statement for this, since const variables must be initialized when defined, and the initializer can t be a statement. Relational operators (comparisons) There are relational operators: Operator Symb ol For m Operation Greater than > x > y true if x is greater than y, false otherwise Less than < x < y true if x is less than y, false otherwise Greater than or equals Less than or equals >= <= Equality == x >= y x <= y x == y true if x is greater than or equal to y, false otherwise true if x is less than or equal to y, false otherwise true if x equals y, false otherwise Inequality!= x!= true if x does not equal y, false otherwise

20 y You have already seen how all of these work, and they are pretty intuitive. Each of these operators evaluates to the boolean value true (), or false (0). Here s some sample code using these operators with integers: #include <iostream> int main() std::cout << "Enter an integer: "; int x; std::cin >> x; std::cout << "Enter another integer: "; int y; std::cin >> y; if (x == y) std::cout << x << " equals " << y << "\n"; if (x!= y) std::cout << x << " does not equal " << y << "\n"; if (x > y) std::cout << x << " is greater than " << y << "\n"; if (x < y) std::cout << x << " is less than " << y << "\n"; if (x >= y) std::cout << x << " is greater than or equal to " << y << "\n"; if (x <= y) std::cout << x << " is less than or equal to " << y << "\n"; return 0; } And the results from a sample run: Enter an integer: Enter another integer: does not equal is less than is less than or equal to These operators are extremely straightforward to use when comparing integers.

21 Comparison of floating point values Directly comparing floating point values using any of these operators is dangerous. This is because small rounding errors in the floating point operands may cause unexpected results. Here s an example of rounding errors causing unexpected results: #include <iostream> int main() double d( ); // should equal 0.0 double d(0-9.99); // should equal 0.0 } if (d == d) std::cout << "d == d" << "\n"; else if (d > d) std::cout << "d > d" << "\n"; else if (d < d) std::cout << "d < d" << "\n"; return 0; This program prints an unexpected result: d > d In the above program, d = and d = Both numbers are close to 0.0, but d is greater than, and d is less than. And neither are equal. Sometimes the need to do floating point comparisons is unavoidable. In this case, the less than and greater than operators (>, >=, <, and <=) are often used with floating point values as normal. The operators will produce the correct result most of the time, only potentially failing when the two operands are close. Due to the way these operators tend to be used, a wrong result often only has slight consequences. The equality operator is much more troublesome since even the smallest of rounding errors makes it completely inaccurate. Consequently, using operator== or operator!= on floating point numbers is not

22 advised. The most common method of doing floating point equality involves using a function that calculates how close the two values are to each other. If the two numbers are "close enough", then we call them equal. The value used to represent "close enough" is traditionally called epsilon. Epsilon is generally defined as a small number (e.g ). New developers often try to write their own close enough function like this: #include <cmath> // for fabs() bool isalmostequal(double a, double b, double epsilon) // if the distance between a and b is less than epsilon, then a and b are "close enough" return fabs(a - b) <= epsilon; } fabs() is a function in the <cmath> library that returns the absolute value of its parameter. fabs(a - b) returns the distance between a and b as a positive number. This function checks if the distance between a and b is less than whatever epsilon value representing close enough was passed in. If a and b are close enough, the function returns true. While this works, it s not great. An epsilon of is good for inputs around.0, too big for numbers around , and too small for numbers like 0,000. This means every time we call this function, we have to pick an epsilon that s appropriate for our inputs. If we know we re going to have to scale epsilon in proportion to our inputs, we might as well modify the function to do that for us. Donald Knuth, a famous computer scientist, suggested the following method in his book The Art of Computer Programming, Volume II: Seminumerical Algorithms (Addison-Wesley, 99) : #include <cmath> // return true if the difference between a and b is within epsilon percent of the larger of a and b bool approximatelyequal(double a, double b, double epsilon) return fabs(a - b) <= ( (fabs(a) < fabs(b)? fabs(b) : fabs(a)) * epsilon); }

23 In this case, instead of using epsilon as an absolute number, we re using epsilon as a multiplier, so its effect is relative to our inputs. Let s examine in more detail how the approximatelyequal() function works. On the left side of the <= operator, the absolute value of a - b tells us the distance between a and b as a positive number. On the right side of the <= operator, we need to calculate the largest value of "close enough" we're willing to accept. To do this, the algorithm chooses the larger of a and b (as a rough indicator of the overall magnitude of the numbers), and then multiplies it by epsilon. In this function, epsilon represents a percentage. For example, if we want to say "close enough" means a and b are within % of the larger of a and b, we pass in an epsilon of % (% = /00 = 0.0). The value for epsilon can be adjusted to whatever is most appropriate for the circumstances (e.g. 0.0% = an epsilon of 0.000). To do inequality (!=) instead of equality, simply call this function and use the logical NOT operator (!) to flip the result: if (!approximatelyequal(a, b, 0.00)) std::cout << a << " is not equal to " << b << "\n"; Note that while the approximatelyequal() function will work for many cases, it is not perfect, especially as the numbers approach zero: #include <iostream> int main() // a is really close to.0, but has rounding errors, so it's slightly smaller than.0 double a = ; // First, let's compare a (almost.0) to.0. std::cout << approximatelyequal(a,.0, e-8) << "\n"; // Second, let's compare a-.0 (almost 0.0) to 0.0 std::cout << approximatelyequal(a-.0, 0.0, e-8) << "\n"; } Perhaps surprisingly, this returns: 0

24 The second call didn t perform as expected. The math simply breaks down close to zero. One way to avoid this is to use both an absolute epsilon (as we did in the first approach) and a relative epsilon (as we did in Knuth s approach): // return true if the difference between a and b is less than absepsilon, or within relepsilon percent of the larger of a and b bool approximatelyequalabsrel(double a, double b, double absepsilon, double relepsilon) // Check if the numbers are really close -- needed when comparing numbers near zero. double diff = fabs(a - b); if (diff <= absepsilon) return true; // Otherwise fall back to Knuth's algorithm return diff <= ( (fabs(a) < fabs(b)? fabs(b) : fabs(a)) * relepsilon); } In this algorithm, we ve added a new parameter: absepsilon. First, we check to see if the distance between a and b is less than our absepsilon, which should be set at something very small (e.g. e-). This handles the case where a and b are both close to zero. If that fails, then we fall back to Knuth s algorithm. Here s our previous code testing both algorithms: #include <iostream> int main() // a is really close to.0, but has rounding errors double a = ; std::cout << approximatelyequal(a,.0, e-8) << "\n"; // compare "almost.0" to.0 std::cout << approximatelyequal(a-.0, 0.0, e-8) << "\n"; // compare "almost 0.0" to 0.0 std::cout << approximatelyequalabsrel(a-.0, 0.0, e-, e-8) << "\n"; // compare "almost 0.0" to 0.0 }

25 You can see that with an appropriately picked absepsilon, approximatelyequalabsrel() handles the small inputs correctly. Comparison of floating point numbers is a difficult topic, and there s no one size fits all algorithm that works for every case. However, the approximatelyequalabsrel() should be good enough to handle most cases you ll encounter. Logical operators While relational (comparison) operators can be used to test whether a particular condition is true or false, they can only test one condition at a time. Often we need to know whether multiple conditions are true at once. For example, to check whether we ve won the lottery, we have to compare whether all of the multiple numbers we picked match the winning numbers. In a lottery with numbers, this would involve comparisons, all of which have to be true. Other times, we need to know whether any one of multiple conditions is true. For example, we may decide to skip work today if we re sick, or if we re too tired, or if won the lottery in our previous example. This would involve checking whether any of comparisons is true. Logical operators provide us with this capability to test multiple conditions. C++ provides us with logical operators: Operator Symb ol Logical NOT Logical AND Form Operation!!x true if x is false, or false if x is true && x && y Logical x y OR Logical NOT true if both x and y are true, false otherwise true if either x or y are true, false otherwise We can summarize the effects of logical NOT like so:

26 true Logical NOT (operator!) Right operand false Result false true If logical NOT s operand evaluates to true, logical NOT evaluates to false. If logical NOT s operand evaluates to false, logical NOT evaluates to true. In other words, logical NOT flips a boolean value from true to false, and viceversa. Logical NOT is often used in conditionals: bool btoolarge = (x > 00); // btoolarge is true if x > 00 if (!btoolarge) // do something with x else // print an error One thing to be wary of is that logical NOT has a very high level of precedence. New programmers often make the following mistake: int x = ; int y = ; if (! x == y) cout << "x does not equal y"; else cout << "x equals y"; This program prints x equals y! But x does not equal y, so how is this possible? The answer is that because the logical NOT operator has higher precedence than the equality operator, the expression! x == y actually evaluates as (!x) == y. Since x is,!x evaluates to 0, and 0 == y is false, so the else statement executes! Reminder: any non-zero integer value evaluates to true when used in a boolean context. Since x is, x evaluates to true, and!x evaluates to false (0). Mixing integer and boolean operations like this can be very confusing, and should be avoided!

27 The correct way to write the above snippet is: int x = ; int y = ; if (!(x == y)) cout << "x does not equal y"; else cout << "x equals y"; This way, x == y will be evaluated first, and then logical NOT will flip the boolean result. Rule: If logical NOT is intended to operate on the result of other operators, the other operators and their operands need to be enclosed in parenthesis. Rule: It s a good idea to always use parenthesis to make your intent clear -- that way, you don t even have to remember the precedence rules. Simple uses of logical NOT, such as if (!bvalue) do not need parenthesis because precedence does not come into play. Logical OR The logical OR operator is used to test whether either of two conditions is true. If the left operand evaluates to true, or the right operand evaluates to true, the logical OR operator returns true. If both operands are true, then logical OR will return true as well. Left operand Logical OR (operator ) Right operand false false false false true true true false true Result true true true For example, consider the following program: #include <iostream> int main()

28 8 9 0 } std::cout << "Enter a number: "; int value; std::cin >> value; if (value== 0 value== ) std::cout << "You picked 0 or " << std::endl; else std::cout << "You did not pick 0 or " << std::endl; return 0; In this case, we use the logical OR operator to test whether either the left condition (value == 0) or the right condition (value == ) is true. If either (or both) are true, the logical OR operator evaluates to true, which means the if statement executes. If neither are true, the logical OR operator evaluates to false, which means the else statement executes. You can string together many logical OR statements: if (value == 0 value == value == value == ) std::cout << "You picked 0,,, or " << std::endl; New programmers sometimes confuse the logical OR operator ( ) with the bitwise OR operator ( ). Even though they both have OR in the name, they perform different functions. Mixing them up will probably lead to incorrect results. Logical AND The logical AND operator is used to test whether both conditions are true. If both conditions are true, logical AND returns true. Otherwise, it returns false. Logical AND (operator &&) Left operand Right operand Result false false false false true false

29 true false false true true true For example, we might want to know if the value of variable x is between 0 and 0. This is actually two conditions: we need to know if x is greater than 0, and also whether x is less than #include <iostream> int main() std::cout << "Enter a number: "; int value; std::cin >> value ; if (value > 0 && value < 0) std::cout << "Your value is between 0 and 0" << std::endl; else std::cout << "Your value is not between 0 and 0" << std::endl; return 0; } In this case, we use the logical AND operator to test whether the left condition (value > 0) AND the right condition (value < 0) are both true. If both are true, the logical AND operator evaluates to true, and the if statement executes. If neither are true, or only one is true, the logical AND operator evaluates to false, and the else statement executes. As with logical OR, you can string together many logical AND statements: if (value > 0 && value < 0 && value!= ) // do something else // do something else If all of these conditions are true, the if statement will execute. If any of these conditions are false, the else statement will execute.

30 Short circuit evaluation In order for logical AND to return true, both operands must evaluate to true. If the first operand evaluates to false, logical AND knows it must return false regardless of whether the second operand evaluates to true or false. In this case, the logical AND operator will go ahead and return false immediately without even evaluating the second operand! This is known as short circuit evaluation, and it is done primarily for optimization purposes. Similarly, if the first operand for logical OR is true, then the entire OR condition has to evaluate to true, and the second operand does not need to be evaluated. Short circuit evaluation presents another opportunity to show why operators that cause side effects should not be used in compound expressions. Consider the following snippet: if (x == && y++ == ) // do something if x does not equal, the conditional must be false, so y++ never gets evaluated! Thus, y will only be incremented if x evaluates to, which is probably not what the programmer intended! As with logical and bitwise OR, new programmers sometimes confuse the logical AND operator (&&) with the bitwise AND operator (&). Mixing ANDs and ORs Mixing logical AND and logical OR operators in the same expression often can not be avoided, but it is an area full of potential dangers. Many programmers assume that logical AND and logical OR have the same precedence (or forget that they don t), just like addition/subtraction and multiplication/division do. However, logical AND has higher precedence than logical OR, thus logical AND operators will be evaluated ahead of logical OR operators (unless they have been parenthesized). As a result of this, new programmers will often write expressions such as value value && value. Because logical AND has higher precedence, this evaluates as value (value && value), not

31 (value value) && value. Hopefully that s what the programmer wanted! If the programmer was assuming left to right evaluation (as happens with addition/subtraction, or multiplication/division), the programmer will get a result he or she was not expecting! When mixing logical AND and logical OR in the same expression, it is a good idea to explicitly parenthesize each operator and its operands. This helps prevent precedence mistakes, makes your code easier to read, and clearly defines how you intended the expression to evaluate. For example, rather than writing value && value value && value, it is better to write (value && value) (value && value). De Morgan s law Many programmers also make the mistake of thinking that!(x && y) is the same thing as!x &&!y. Unfortunately, you can not distribute the logical NOT in that manner. De Morgan s law tells us how the logical NOT should be distributed in these cases:!(x && y) is equivalent to!x!y!(x y) is equivalent to!x &&!y In other words, when you distribute the logical NOT, you also need to flip logical AND to logical OR, and vice-versa! This can sometimes be useful when trying to make up complex expressions easier to read. Where s the logical exclusive or (XOR) operator? Logical XOR is a logical operator provided in some languages that is used to test whether an odd number of conditions is true. Left operand Logical XOR Right operand false false false false true true true false true Result

32 true true false C++ doesn t provide a logical XOR operator. Unlike logical OR or logical AND, XOR cannot be short circuit evaluated. Because of this, making an XOR operator out of logical OR and logical AND operators is challenging. However, you can easily mimic logical XOR using the not equals operator (!=): if (a!= b)... // a XOR b, assuming a and b are booleans This can be extended to multiple operands as follows: if (a!= b!= c!= d)... // a XOR b XOR c XOR d, assuming a, b, c, and d are booleans Note that the above XOR patterns only work if the operands are booleans (not integers). If you want this to work with integers, you can static_cast them to bools. If you need a form of XOR that works with non-boolean operands, you can use this slightly more complicated form: if (static_cast<bool>(a)!= static_cast<bool>(b)!= static_cast<bool>(c)!= static_cast<bool>(d))... // a XOR b XOR c XOR d, for any type that can be converted to bool

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

Information Science 1

Information Science 1 Information Science 1 Simple Calcula,ons Week 09 College of Information Science and Engineering Ritsumeikan University Topics covered l Terms and concepts from Week 8 l Simple calculations Documenting

More information

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators Operators Overview Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators Operands and Operators Mathematical or logical relationships

More information

Unit 3. Operators. School of Science and Technology INTRODUCTION

Unit 3. Operators. School of Science and Technology INTRODUCTION INTRODUCTION Operators Unit 3 In the previous units (unit 1 and 2) you have learned about the basics of computer programming, different data types, constants, keywords and basic structure of a C program.

More information

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands Introduction Operators are the symbols which operates on value or a variable. It tells the compiler to perform certain mathematical or logical manipulations. Can be of following categories: Unary requires

More information

Bits, Words, and Integers

Bits, Words, and Integers Computer Science 52 Bits, Words, and Integers Spring Semester, 2017 In this document, we look at how bits are organized into meaningful data. In particular, we will see the details of how integers are

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Operators in C. Staff Incharge: S.Sasirekha

Operators in C. Staff Incharge: S.Sasirekha Operators in C Staff Incharge: S.Sasirekha Operators An operator is a symbol which helps the user to command the computer to do a certain mathematical or logical manipulations. Operators are used in C

More information

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one. http://www.tutorialspoint.com/go/go_operators.htm GO - OPERATORS Copyright tutorialspoint.com An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.

More information

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5. Week 2: Console I/O and Operators Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.1) CS 1428 Fall 2014 Jill Seaman 1 2.14 Arithmetic Operators An operator is a symbol that tells the computer to perform specific

More information

These are notes for the third lecture; if statements and loops.

These are notes for the third lecture; if statements and loops. These are notes for the third lecture; if statements and loops. 1 Yeah, this is going to be the second slide in a lot of lectures. 2 - Dominant language for desktop application development - Most modern

More information

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

More information

Operators & Expressions

Operators & Expressions Operators & Expressions Operator An operator is a symbol used to indicate a specific operation on variables in a program. Example : symbol + is an add operator that adds two data items called operands.

More information

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g. 1.3a Expressions Expressions An Expression is a sequence of operands and operators that reduces to a single value. An operator is a syntactical token that requires an action be taken An operand is an object

More information

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

More information

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh C++ PROGRAMMING For Industrial And Electrical Engineering Instructor: Ruba A. Salamh CHAPTER TWO: Fundamental Data Types Chapter Goals In this chapter, you will learn how to work with numbers and text,

More information

Expressions and Precedence. Last updated 12/10/18

Expressions and Precedence. Last updated 12/10/18 Expressions and Precedence Last updated 12/10/18 Expression: Sequence of Operators and Operands that reduce to a single value Simple and Complex Expressions Subject to Precedence and Associativity Six

More information

COP 3275: Chapter 04. Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA

COP 3275: Chapter 04. Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA COP 3275: Chapter 04 Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA Operators C emphasizes expressions rather than statements. Expressions are built from variables, constants, and

More information

Lecture 4 CSE July 1992

Lecture 4 CSE July 1992 Lecture 4 CSE 110 6 July 1992 1 More Operators C has many operators. Some of them, like +, are binary, which means that they require two operands, as in 4 + 5. Others are unary, which means they require

More information

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator 1 A Closer Look at the / Operator Used for performing numeric calculations C++ has unary, binary, and ternary s: unary (1 operand) - binary ( operands) 13-7 ternary (3 operands) exp1? exp : exp3 / (division)

More information

1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary

1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary Topic 2 1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary Arithmetic Operators C++ has the same arithmetic operators as a calculator:

More information

Signed umbers. Sign/Magnitude otation

Signed umbers. Sign/Magnitude otation Signed umbers So far we have discussed unsigned number representations. In particular, we have looked at the binary number system and shorthand methods in representing binary codes. With m binary digits,

More information

Divisibility Rules and Their Explanations

Divisibility Rules and Their Explanations Divisibility Rules and Their Explanations Increase Your Number Sense These divisibility rules apply to determining the divisibility of a positive integer (1, 2, 3, ) by another positive integer or 0 (although

More information

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur Operators and Expressions 8/24/2012 Dept of CS&E 2 Arithmetic operators Relational operators Logical operators

More information

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started Handout written by Julie Zelenski, Mehran Sahami, Robert Plummer, and Jerry Cain. After today s lecture, you should run home and read

More information

Section we will not cover section 2.11 feel free to read it on your own

Section we will not cover section 2.11 feel free to read it on your own Operators Class 5 Section 2.11 we will not cover section 2.11 feel free to read it on your own Data Types Data Type A data type is a set of values and a set of operations defined on those values. in class

More information

PART II. Computation

PART II. Computation PART II Computation 72 Chapter 4 Expressions Computation is central to computer programming. We discuss how the usual mathematical operations can be applied to variables and introduce the concepts of precedence

More information

Ch. 12: Operator Overloading

Ch. 12: Operator Overloading Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

Basics of Programming

Basics of Programming Unit 2 Basics of Programming Problem Analysis When we are going to develop any solution to the problem, we must fully understand the nature of the problem and what we want the program to do. Without the

More information

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University Lesson #3 Variables, Operators, and Expressions Variables We already know the three main types of variables in C: int, char, and double. There is also the float type which is similar to double with only

More information

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators JAVA Standard Edition Java - Basic Operators Java provides a rich set of operators to manipulate variables.

More information

Information Science 1

Information Science 1 Topics covered Information Science 1 Terms and concepts from Week 8 Simple calculations Documenting programs Simple Calcula,ons Expressions Arithmetic operators and arithmetic operator precedence Mixed-type

More information

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9 Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Uppercase Alphabets Lowercase Alphabets Character Set A, B, C, Y, Z a, b, c, y, z Digits

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 September 30, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases. Formulating Algorithms with Top-Down, Stepwise Refinement Case Study 2: Sentinel-Controlled Repetition In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability.

More information

Programming in C++ 5. Integral data types

Programming in C++ 5. Integral data types Programming in C++ 5. Integral data types! Introduction! Type int! Integer multiplication & division! Increment & decrement operators! Associativity & precedence of operators! Some common operators! Long

More information

Review of the C Programming Language for Principles of Operating Systems

Review of the C Programming Language for Principles of Operating Systems Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights

More information

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 1 IDL Operators

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 1 IDL Operators ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 1 IDL Operators ARITHMATIC OPERATORS The assignment operator in IDL is the equals sign, =. IDL uses all the familiar arithmetic operators

More information

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Operators. Lecture 3 COP 3014 Spring January 16, 2018 Operators Lecture 3 COP 3014 Spring 2018 January 16, 2018 Operators Special built-in symbols that have functionality, and work on operands operand an input to an operator Arity - how many operands an operator

More information

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz) SOFTWARE DEVELOPMENT 1 Operators 2018W (Institute of Pervasive Computing, JKU Linz) OPERATORS Operators are required to form expressions. Depending on the number of operands they take, they are called:

More information

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

Chapter 4. Operations on Data

Chapter 4. Operations on Data Chapter 4 Operations on Data 1 OBJECTIVES After reading this chapter, the reader should be able to: List the three categories of operations performed on data. Perform unary and binary logic operations

More information

Math 340 Fall 2014, Victor Matveev. Binary system, round-off errors, loss of significance, and double precision accuracy.

Math 340 Fall 2014, Victor Matveev. Binary system, round-off errors, loss of significance, and double precision accuracy. Math 340 Fall 2014, Victor Matveev Binary system, round-off errors, loss of significance, and double precision accuracy. 1. Bits and the binary number system A bit is one digit in a binary representation

More information

SECTION II: LANGUAGE BASICS

SECTION II: LANGUAGE BASICS Chapter 5 SECTION II: LANGUAGE BASICS Operators Chapter 04: Basic Fundamentals demonstrated declaring and initializing variables. This chapter depicts how to do something with them, using operators. Operators

More information

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and The Arithmetic Operators The arithmetic operators refer to the standard mathematical operators: addition, subtraction, multiplication, division and modulus. Op. Use Description + x + y adds x and y x y

More information

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

CprE 288 Introduction to Embedded Systems Exam 1 Review.  1 CprE 288 Introduction to Embedded Systems Exam 1 Review http://class.ece.iastate.edu/cpre288 1 Overview of Today s Lecture Announcements Exam 1 Review http://class.ece.iastate.edu/cpre288 2 Announcements

More information

The Arithmetic Operators

The Arithmetic Operators The Arithmetic Operators The arithmetic operators refer to the standard mathematical operators: addition, subtraction, multiplication, division and modulus. Examples: Op. Use Description + x + y adds x

More information

Computers Programming Course 6. Iulian Năstac

Computers Programming Course 6. Iulian Năstac Computers Programming Course 6 Iulian Năstac Recap from previous course Data types four basic arithmetic type specifiers: char int float double void optional specifiers: signed, unsigned short long 2 Recap

More information

Topic Notes: Bits and Bytes and Numbers

Topic Notes: Bits and Bytes and Numbers Computer Science 220 Assembly Language & Comp Architecture Siena College Fall 2010 Topic Notes: Bits and Bytes and Numbers Binary Basics At least some of this will be review, but we will go over it for

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors First Program Compilation and Execution Simplifying Fractions Loops If Statements Variables Operations Using Functions Errors C++ programs consist of a series of instructions written in using the C++ syntax

More information

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop Announcements Lab Friday, 1-2:30 and 3-4:30 in 26-152 Boot your laptop and start Forte, if you brought your laptop Create an empty file called Lecture4 and create an empty main() method in a class: 1.00

More information

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands Performing Computations C provides operators that can be applied to calculate expressions: tax is 8.5% of the total sale expression: tax = 0.085 * totalsale Need to specify what operations are legal, how

More information

5. Control Statements

5. Control Statements 5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements

More information

Programming Lecture 3

Programming Lecture 3 Programming Lecture 3 Expressions (Chapter 3) Primitive types Aside: Context Free Grammars Constants, variables Identifiers Variable declarations Arithmetic expressions Operator precedence Assignment statements

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

Chapter 2. Data Representation in Computer Systems

Chapter 2. Data Representation in Computer Systems Chapter 2 Data Representation in Computer Systems Chapter 2 Objectives Understand the fundamentals of numerical data representation and manipulation in digital computers. Master the skill of converting

More information

More Programming Constructs -- Introduction

More Programming Constructs -- Introduction More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and

More information

LECTURE 3 C++ Basics Part 2

LECTURE 3 C++ Basics Part 2 LECTURE 3 C++ Basics Part 2 OVERVIEW Operators Type Conversions OPERATORS Operators are special built-in symbols that have functionality, and work on operands. Operators are actually functions that use

More information

2/5/2018. Expressions are Used to Perform Calculations. ECE 220: Computer Systems & Programming. Our Class Focuses on Four Types of Operator in C

2/5/2018. Expressions are Used to Perform Calculations. ECE 220: Computer Systems & Programming. Our Class Focuses on Four Types of Operator in C University of Illinois at Urbana-Champaign Dept. of Electrical and Computer Engineering ECE 220: Computer Systems & Programming Expressions and Operators in C (Partially a Review) Expressions are Used

More information

Topic Notes: Bits and Bytes and Numbers

Topic Notes: Bits and Bytes and Numbers Computer Science 220 Assembly Language & Comp Architecture Siena College Fall 2011 Topic Notes: Bits and Bytes and Numbers Binary Basics At least some of this will be review for most of you, but we start

More information

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */ Overview Language Basics This chapter describes the basic elements of Rexx. It discusses the simple components that make up the language. These include script structure, elements of the language, operators,

More information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

4 Operations On Data 4.1. Foundations of Computer Science Cengage Learning

4 Operations On Data 4.1. Foundations of Computer Science Cengage Learning 4 Operations On Data 4.1 Foundations of Computer Science Cengage Learning Objectives After studying this chapter, the student should be able to: List the three categories of operations performed on data.

More information

The following expression causes a divide by zero error:

The following expression causes a divide by zero error: Chapter 2 - Test Questions These test questions are true-false, fill in the blank, multiple choice, and free form questions that may require code. The multiple choice questions may have more than one correct

More information

Variables and literals

Variables and literals Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of

More information

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators Course Name: Advanced Java Lecture 2 Topics to be covered Variables Operators Variables -Introduction A variables can be considered as a name given to the location in memory where values are stored. One

More information

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement Last Time Let s all Repeat Together 10/3/05 CS150 Introduction to Computer Science 1 1 We covered o Counter and sentinel controlled loops o Formatting output Today we will o Type casting o Top-down, stepwise

More information

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto CS 170 Java Programming 1 Expressions Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 What is an expression? Expression Vocabulary Any combination of operators and operands which, when

More information

Variables and Data Representation

Variables and Data Representation You will recall that a computer program is a set of instructions that tell a computer how to transform a given set of input into a specific output. Any program, procedural, event driven or object oriented

More information

Module 2 Introducing Data Types and Operators

Module 2 Introducing Data Types and Operators Module 2 Introducing Data Types and Operators Table of Contents CRITICAL SKILL 2.1: The C++ Data Types... 2 Project 2-1 Talking to Mars... 10 CRITICAL SKILL 2.2: Literals... 12 CRITICAL SKILL 2.3: A Closer

More information

Logic, Words, and Integers

Logic, Words, and Integers Computer Science 52 Logic, Words, and Integers 1 Words and Data The basic unit of information in a computer is the bit; it is simply a quantity that takes one of two values, 0 or 1. A sequence of k bits

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

Variables and Constants

Variables and Constants HOUR 3 Variables and Constants Programs need a way to store the data they use. Variables and constants offer various ways to work with numbers and other values. In this hour you learn: How to declare and

More information

Review of the C Programming Language

Review of the C Programming Language Review of the C Programming Language Prof. James L. Frankel Harvard University Version of 11:55 AM 22-Apr-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights reserved. Reference Manual for the

More information

JAVA OPERATORS GENERAL

JAVA OPERATORS GENERAL JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Chapter 12 Variables and Operators

Chapter 12 Variables and Operators Chapter 12 Variables and Operators Highlights (1) r. height width operator area = 3.14 * r *r + width * height literal/constant variable expression (assignment) statement 12-2 Highlights (2) r. height

More information

Numbers. John Perry. Spring 2017

Numbers. John Perry. Spring 2017 Basic MAT 685: C++ Numbers University of Southern Msississippi Spring 2017 Outline Basic 1 2 Basic 3 4 Outline Basic 1 2 Basic 3 4 Variable? Basic Name representing data in computer s memory first character?

More information

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5 C++ Data Types Contents 1 Simple C++ Data Types 2 2 Quick Note About Representations 3 3 Numeric Types 4 3.1 Integers (whole numbers)............................................ 4 3.2 Decimal Numbers.................................................

More information

Week 3 More Formatted Input/Output; Arithmetic and Assignment Operators

Week 3 More Formatted Input/Output; Arithmetic and Assignment Operators Week 3 More Formatted Input/Output; Arithmetic and Assignment Operators Formatted Input and Output The printf function The scanf function Arithmetic and Assignment Operators Simple Assignment Side Effect

More information

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

PIC 10A Flow control. Ernest Ryu UCLA Mathematics PIC 10A Flow control Ernest Ryu UCLA Mathematics If statement An if statement conditionally executes a block of code. # include < iostream > using namespace std ; int main () { double d1; cin >> d1; if

More information

Reserved Words and Identifiers

Reserved Words and Identifiers 1 Programming in C Reserved Words and Identifiers Reserved word Word that has a specific meaning in C Ex: int, return Identifier Word used to name and refer to a data element or object manipulated by the

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Arrays array array length fixed array fixed length array fixed size array Array elements and subscripting

Arrays array array length fixed array fixed length array fixed size array Array elements and subscripting Arrays Fortunately, structs are not the only aggregate data type in C++. An array is an aggregate data type that lets us access many variables of the same type through a single identifier. Consider the

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Unit-2 (Operators) ANAND KR.SRIVASTAVA

Unit-2 (Operators) ANAND KR.SRIVASTAVA Unit-2 (Operators) ANAND KR.SRIVASTAVA 1 Operators in C ( use of operators in C ) Operators are the symbol, to perform some operation ( calculation, manipulation). Set of Operations are used in completion

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Language Reference Manual simplicity

Language Reference Manual simplicity Language Reference Manual simplicity Course: COMS S4115 Professor: Dr. Stephen Edwards TA: Graham Gobieski Date: July 20, 2016 Group members Rui Gu rg2970 Adam Hadar anh2130 Zachary Moffitt znm2104 Suzanna

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

More information

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure C Overview Basic C Program Structure C OVERVIEW BASIC C PROGRAM STRUCTURE Goals The function main( )is found in every C program and is where every C program begins speed execution portability C uses braces

More information

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2 Numerical Computing in C and C++ Jamie Griffin Semester A 2017 Lecture 2 Visual Studio in QM PC rooms Microsoft Visual Studio Community 2015. Bancroft Building 1.15a; Queen s W207, EB7; Engineering W128.D.

More information

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013 Expressions and Casting C# Programming Rob Miles Data Manipulation We know that programs use data storage (variables) to hold values and statements to process the data The statements are obeyed in sequence

More information

Operators and Type Conversion. By Avani M. Sakhapara Assistant Professor, IT Dept, KJSCE

Operators and Type Conversion. By Avani M. Sakhapara Assistant Professor, IT Dept, KJSCE Operators and Type Conversion By Avani M. Sakhapara Assistant Professor, IT Dept, KJSCE Introduction An operator is a symbol which represents a particular operation that can be performed on some data.

More information

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3 Programming - 1 Computer Science Department 011COMP-3 لغة البرمجة 1 011 عال- 3 لطالب كلية الحاسب اآللي ونظم المعلومات 1 1.1 Machine Language A computer programming language which has binary instructions

More information

Chapter 7. Expressions and Assignment Statements ISBN

Chapter 7. Expressions and Assignment Statements ISBN Chapter 7 Expressions and Assignment Statements ISBN 0-321-33025-0 Chapter 7 Topics Introduction Arithmetic Expressions Overloaded Operators Type Conversions Relational and Boolean Expressions Short-Circuit

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 6 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Spring 2011 These slides are created using Deitel s slides Sharif University of Technology Outlines

More information