Expressions 1 3 1

broken image


< cpp‎ | language

2014, Edward Fry, Timothy Rasinski, High Frequency Word Phrases Level 3-Reading with Expression, Teacher Created Materials (→ISBN), page 43. Primary expressions. The operands of any operator may be other expressions or primary expressions (e.g. In 1 + 2. 3, the operands of operator+ are the subexpression 2. 3 and the primary expression 1). Primary expressions are any of the following: Literals (e.g. 2 or 'Hello, world') Id-expressions, including. NYS COMMON CORE MATHEMATICS CURRICULUM Lesson 1 7.3 Lesson 1: Generating Equivalent Expressions S.3 This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. Find the sum of −3𝑎𝑎+ 2 and 5𝑎𝑎−3.

C++
Compiler support
Freestanding and hosted
Language
Standard library headers
Named requirements
Feature test macros (C++20)
Language support library
Concepts library(C++20)
Diagnostics library
General utilities library
Strings library
Containers library
Iterators library
Ranges library(C++20)
Algorithms library
Numerics library
Localizations library
Input/output library
Filesystem library(C++17)
Regular expressions library(C++11)
Atomic operations library(C++11)
Thread support library(C++11)
Technical specifications
Symbols index
External libraries
C++ language
General topics
Keywords
Escape sequences
Flow control
Conditional execution statements
Iteration statements (loops)
while
do-while
Jump statements
goto - return
Functions
Function declaration
Lambda function declaration
inline specifier
Dynamic exception specifications(until C++20)
noexcept specifier(C++11)
Exceptions
Namespaces
Types
Fundamental types
Enumeration types
Function types
Specifiers
decltype(C++11)
auto(C++11)
alignas(C++11)
Storage duration specifiers
Initialization
Default initialization
Value initialization
Zero initialization
Copy initialization
Direct initialization
Aggregate initialization
List initialization(C++11)
Constant initialization
Reference initialization
Expressions
Operators
Operator precedence
Alternative representations
Literals
Boolean -Integer -Floating-point
Character -String - nullptr(C++11)
User-defined(C++11)
Utilities
Attributes(C++11)
Types
typedef declaration
Type alias declaration(C++11)
Casts
Implicit conversions -Explicit conversions
static_cast - dynamic_cast
const_cast - reinterpret_cast
Memory allocation
Classes
Access specifiers
friend specifier
Class-specific function properties
Virtual function
override specifier(C++11)
final specifier(C++11)
Special member functions
Default constructor
Copy constructor
Move constructor(C++11)
Copy assignment
Move assignment(C++11)
Destructor
Templates
Template specialization
Parameter packs(C++11)
Miscellaneous
Expressions
General
value categories (lvalue, rvalue, xvalue)
order of evaluation (sequence points)
constant expressions
unevaluated expressions
primary expressions
lambda-expression(C++11)
Literals
integer literals
floating-point literals
boolean literals
character literals including escape sequences
string literals
null pointer literal(C++11)
user-defined literal(C++11)
Operators
Assignment operators: a=b, a+=b, a-=b, a*=b, a/=b, a%=b, a&=b, a|=b, a^=b, a<<=b, a>>=b
Increment and decrement: ++a, --a, a++, a--
Arithmetic operators:+a, -a, a+b, a-b, a*b, a/b, a%b, ~a, a&b, a|b, a^b, a<, a>>b
Logical operators: a||b, a&&b, !a
Comparison operators: ab, a!=b, a, a>b, a<=b, a>=b, a<=>b(C++20)
Member access operators: a[b], *a, &a, a->b, a.b, a->*b, a.*b
Other operators: a(..), a,b, a?b:c
new-expression
delete-expression
throw-expression
alignof
sizeof
sizeof..(C++11)
typeid
noexcept(C++11)
Fold expression(C++17)
Alternative representations of operators
Precedence and associativity
Operator overloading
Default comparisons(C++20)
Conversions
Implicit conversions
const_cast
static_cast
reinterpret_cast
dynamic_cast
Explicit conversions(T)a, T(a)
User-defined conversion

An expression is a sequence of operators and their operands, that specifies a computation.

Expression evaluation may produce a result (e.g., evaluation of 2+2 produces the result 4) and may generate side-effects (e.g. evaluation of std::printf('%d',4) prints the character '4' on the standard output).

Each C++ expression is characterized by two independent properties: A type and a value category.

  • 2Operators
  • 3Primary expressions

[edit]General

  • value categories (lvalue, rvalue, glvalue, prvalue, xvalue) classify expressions by their values
  • order of evaluation of arguments and subexpressions specify the order in which intermediate results are obtained

[edit]Operators

Common operators
assignment increment
decrement
arithmetic logical comparison member
access
other

a = b
a += b
a -= b
a *= b
a /= b
a %= b
a &= b
a |= b
a ^= b
a <<= b
a >>= b
Garagetunes 1 2b2 – collaborative music player.

++a
--a
a++
a--

+a
-a
a + b
a - b
a * b
a / b
a % b
~a
a & b
a | b
a ^ b
a << b
a >> b

!a
a && b
a || b

a b
a != b
a < b
a > b
a <= b
a >= b
a <=> b

a[b]
*a
&a
a->b
a.b
a->*b
a.*b

a(..)
a, b
?:

Special operators

static_cast converts one type to another related type
dynamic_cast converts within inheritance hierarchies
const_cast adds or removes cv qualifiers
reinterpret_cast converts type to unrelated type
C-style cast converts one type to another by a mix of static_cast, const_cast, and reinterpret_cast
new creates objects with dynamic storage duration
delete destructs objects previously created by the new expression and releases obtained memory area
sizeof queries the size of a type
sizeof.. queries the size of a parameter pack(since C++11)
typeid queries the type information of a type
noexcept checks if an expression can throw an exception (since C++11)
alignof queries alignment requirements of a type (since C++11)

  • operator precedence defines the order in which operators are bound to their arguments
  • alternative representations are alternative spellings for some operators
  • operator overloading makes it possible to specify the behavior of the operators with user-defined classes.

[edit]Conversions

  • standard conversions implicit conversions from one type to another
  • explicit cast conversion using C-style cast notation and functional notation
  • user-defined conversion makes it possible to specify conversion from user-defined classes

[edit]Memory allocation

  • new expression allocates memory dynamically
  • delete expression deallocates memory dynamically

[edit]Other

  • constant expressions can be evaluated at compile time and used in compile-time context (template arguments, array sizes, etc)

[edit]Primary expressions

The operands of any operator may be other expressions or primary expressions (e.g. in 1+2*3, the operands of operator+ are the subexpression 2*3 and the primary expression 1).

Primary expressions are any of the following:

  • Literals (e.g. 2 or 'Hello, world')
  • Id-expressions, including
    • suitably declared unqualified identifiers (e.g. n or cout), and
    • suitably declared qualified identifiers (e.g. std::string::npos)
  • Lambda-expressions(since C++11)
  • Fold-expressions(since C++17)
  • Requires-expressions(since C++20)

Any expression in parentheses is also classified as a primary expression: this guarantees that the parentheses have higher precedence than any operator. Parentheses preserve value, type, and value category.

[edit]Literals

Literals are the tokens of a C++ program that represent constant values embedded in the source code.

  • integer literals are decimal, octal, hexadecimal or binary numbers of integer type.
  • character literals are individual characters of type
  • char or wchar_t
  • char16_t or char32_t(since C++11)
  • char8_t(since C++20)
  • floating-point literals are values of type float, double, or longdouble
  • string literals are sequences of characters of type
  • constchar[] or constwchar_t[]
  • constchar16_t[] or constchar32_t[](since C++11)
  • const char8_t[](since C++20)
  • boolean literals are values of type bool, that is true and false
  • nullptr is the pointer literal which specifies a null pointer value (since C++11)
  • user-defined literals are constant values of user-specified type (since C++11)

[edit]Unevaluated expressions

Expressions

The operands of the operators typeid, sizeof, noexcept, and decltype(since C++11) are expressions that are not evaluated (unless they are polymorphic glvalues and are the operands of typeid), since these operators only query the compile-time properties of their operands. Thus, std::size_t n = sizeof(std::cout<<42); does not perform console output.

The unevaluated operands are considered to be full expressions even though they are syntactically operands in a larger expression (for example, this means that sizeof(T()) requires an accessible T::~T).

(since C++14)

The requires-expressions are also unevaluated expressions.

(since C++20)

[edit]Discarded-value expressions

A discarded-value expression is an expression that is used for its side-effects only. The value calculated from such expression is discarded. Such expressions include the full expression of any expression statement, the left-hand operand of the built-in comma operator, or the operand of a cast-expression that casts to the type void.

Array-to-pointer and function-to-pointer conversions are never applied to the value calculated by a discarded-value expression. The lvalue-to-rvalue conversion is applied if and only if the expression is a volatile-qualified glvalue and has one of the following forms (built-in meaning required, possibly parenthesized):

  • id-expression,
  • array subscript expression,
  • class member access expression,
  • indirection,
  • pointer-to-member operation,
  • conditional expression where both the second and the third operands are one of these expressions,
  • comma expression where the right operand is one of these expressions.

In addition, if the lvalue is of volatile-qualified class type, a volatile copy-constructor is required to initialize the resulting rvalue temporary.

If the expression is a non-void prvalue (after any lvalue-to-rvalue conversion that might have taken place), temporary materialization occurs.

Compilers may issue warnings when an expression other than cast to void discards a value declared [[nodiscard]].

(since C++17)

[edit]See also

C documentation for Expressions
Retrieved from 'https://en.cppreference.com/mwiki/index.php?title=cpp/language/expressions&oldid=133677'

Boolean variables or expressions can only have true or false values.

3.1.1. Testing Equality ()¶

The operatorsand != (not equal) can be used to compare values. They return true or false boolean values.

Note

One = sign changes the value of a variable. Twoequal signs are used to test if a variable holds a certain value, without changing its value!

Watch the following video which shows what happens in memory as primitive types like int and reference types like Dog are compared within a physical model of Java memory.

The following code shows howis used with primitive types like int.

What will the code below print out? Try to guess before you run it! Note that 1 equal sign (=) is used for assigning a value and 2 equal signs () for testing values.

public class BoolTest1{ public static void main(String[] args) { int age = 15; int year = 14; // Will this print true or false? System.out.println( ageyear ); year = 15; // Will this print true or false? System.out.println( ageyear ); // Will this print true or false? System.out.println( age != year ); }}// should pass if/when they run code import static org.junit.Assert.*; import org.junit.*;; import java.io.*; public class RunestoneTests extends CodeTestHelper { @Test public void testMain() throws IOException { String output = getMethodOutput('main'); String expect = 'falsentruenfalsen'; boolean passed = getResults(expect, output, 'Expected output from main', true); assertTrue(passed); } }

We can also useor != to test if two reference values, like Turtle and String objects, refer to the same object. In the figure below, we are creating two separate Turtle objects called juan and mia. They do not refer to same object or turtle. Then, we create a reference variable called friend that is set to mia. The turtle mia will have two ways (references or aliases) to name her – she's both mia and friend, and these variables refer to the same object (same Turtle) in memory. If two reference variables refer to the same object like the turtle on the right in the image below, the test withwill return true which you can see in the code below.

Coding Exercise

Expressions 1 3 12

What will the code below print out? Try to guess before you run it!

import java.util.*;import java.awt.*;public class BoolTestRef{ public static void main(String[] args) { World world = new World(300,300); Turtle juan = new Turtle(world); Turtle mia = new Turtle(world); // Will these print true or false? System.out.println(juanmia); Turtle friend = mia; // set friend to be an alias for mia System.out.println(friendmia); } }import static org.junit.Assert.*; import org.junit.*;; import java.io.*; public class RunestoneTests extends CodeTestHelper { public RunestoneTests() { super('BoolTestRef'); } @Test public void test1() { boolean passed = getResults('true', 'true', 'main()'); assertTrue(passed); } }

3.1.2. Relational Operators (<, >)¶

The Relational Operators below in Java are used to compare numeric values or arithmetic expressions. Although some programming languages allow using relational operators like < to compare strings, Java only uses these operators for numbers, and uses the string methods compareTo() and equals() for comparing String values.

  • < Less Than

  • > Greater Than

  • <= Less than or equal to

  • >= Greater than or equal to

  • Equals

  • != Does not equal

If you have trouble telling < and > apart, think of a number line and think of < and > as arrows; < (less than) points towards 0 and smaller numbers on the number line and > (greater than) points towards the larger numbers on the number line. Or remember that < starts with the smaller (less) point and > starts with the open wide (greater) side. With <= and >=, remember to write the two symbols in the order that you would say them 'less than' followed by 'or equal to'.

Coding Exercise

Try to guess what the code below will print out before you run it.

Expressions 1 3 1 2 Equals

public class BoolTest2{ public static void main(String[] args) { int age = 15; int year = 14; // Will these print true or false? System.out.println( age < year ); System.out.println( age > year ); System.out.println( age <= year+1 ); System.out.println( age-1 >= year ); }}import static org.junit.Assert.*; import org.junit.*;; import java.io.*; public class RunestoneTests extends CodeTestHelper { @Test public void testMain() throws IOException { String output = getMethodOutput('main'); String expect = 'falsentruentruentruen'; boolean passed = getResults(expect, output, 'Expected output from main', true); assertTrue(passed); } }

Check your understanding

    3-1-5: Drag the boolean expression from the left and drop it on what it is testing on the right. Click the 'Check Me' button to see if you are correct.Review the relational operators above.
  • x > 0
  • x is positive
  • xy
  • x equals y
  • x < 0
  • x is negative
  • x != y
  • x does not equal y
  • x < y
  • x is less than y
  • x > y
  • x is greater than y
  • x >= y
  • x is greater than or equal to y

3.1.3. Testing with mod (%)¶

Here are some boolean expressions that are very useful in coding and mod is used in many of them:

Try the expressions containing the % operator below to see how they can be used to check for even or odd numbers. All even numbers are divisible (with no remainder) by 2.

public class BoolMod{ public static void main(String[] args) { int age1 = 15; int age2 = 16; int divisor = 2; System.out.println('Remainder of ' + age1 + '/' + divisor + ' is ' + (age1 % divisor) ); System.out.println('Remainder of ' + age2 + '/' + divisor + ' is ' + (age2 % divisor) ); System.out.println('Is ' + age1 + ' even? ' + (age1 % 20) ); System.out.println('Is ' + age2 + ' even? ' + (age2 % 20) ); }}import static org.junit.Assert.*; import org.junit.*;; import java.io.*; public class RunestoneTests extends CodeTestHelper { @Test public void testMain() throws IOException { String output = getMethodOutput('main'); String expect = 'Remainder of 15/2 is 1nRemainder of 16/2 is 0nIs 15 even? false nIs 16 even? truen'; boolean passed = getResults(expect, output, 'Expected output from main', true); assertTrue(passed); } }

The modulo operator has been used quite a bit on the AP CS A exam, so you should be familiar with it.

  • Use it to check for odd or even numbers (num%21)isodd and (num%20)iseven. Actually, you can use it to check if any number is evenly divisible by another (num1%num20)

  • Use it to get the last digit from an integer number (num%10=lastdigitonright).

  • Use it to get the number of minutes left when you convert to hours (num%60).

  • Use it whenever you have limit in the value, and you need to wrap around to the front if the value goes over the limit (num%limit).

3.1.4. Programming Challenge : Prime Numbers POGIL¶

We encourage you to do this activity as a POGIL (Process Oriented Guided Inquiry Learning) group activity or using Think-Pair-Share collaboration. POGIL groups are self-managed teams of 4 students where everyone has a POGIL role and works together to solve the problems, making sure that everyone in the team participates and learns.

In this activity, you will use boolean expressions to explore prime numbers. A prime number is an integer number that is only divisible by 1 and itself. For example, 3 is a prime number because it's only divisible by 1 and 3 and no other numbers, but 4 is not a prime number because it's divisible by 2 as well as 1 and 4.

Prime numbers are very useful in encryption algorithms because they can be used as keys for encoding and decoding. If you have the key, you can use it to divide a large number that represents something encrypted to decode it, but if you don't have the key, it's very hard to guess the factors of a large number to decode it. If you're curious about this, watch this Numberphile video.

The following program checks if 5 is a prime number by seeing if it is divisible by the numbers 1 - 5. Run the code, and then answer the following questions.

  1. Is 5 a prime number?

  2. What boolean tests determine that a number is prime?

  3. Change the number to 6 and add more boolean expressions to determine if 6 is prime. Is 6 prime?

  4. Change the number to 7 and add more boolean expressions to determine if 7 is prime. Is 7 prime?

  5. If you changed the boolean expressions to use <= instead of , would the code still help you to find prime numbers? Why or why not? Experiment and find out.

  6. If you changed the boolean expressions to use >= instead of , would the code still help you to find prime numbers? Why or why not? Experiment and find out.

  7. Are all odd numbers prime? Can you find one that is not by using boolean expressions in the code below?

  8. Are all even numbers not prime? Hazel 4 0 1 download free. Can you find an even prime number?

1/3 - 1 As A Fraction

Experiment with the code below changing the value of number and adding more print statements with boolean expressions to determine if the numbers 5, 6, and 7 are prime. Are all odd numbers prime? Are all even numbers not prime?

public class PrimeNumbers{ public static void main(String[] args) { int number = 5; System.out.println('A prime number is only divisible by 1 and itself.'); System.out.println('Is ' + number + ' divisible by 1 up to ' + number + '?'); System.out.println('Divisible by 1? ' + (number % 10)); System.out.println('Divisible by 2? ' + (number % 20)); System.out.println('Divisible by 3? ' + (number % 30)); System.out.println('Divisible by 4? ' + (number % 40)); System.out.println('Divisible by 5? ' + (number % 50)); }}import static org.junit.Assert.*; import org.junit.*;; import java.io.*; public class RunestoneTests extends CodeTestHelper { @Test public void testChangedCode() { String origCode = 'public class PrimeNumbers{public static void main(String[] args){int number = 5; System.out.println('A prime number is only divisible by 1 and itself.'); System.out.println('Is ' + number + ' divisible by 1 up to ' + number + '?'); System.out.println('Divisible by 1? ' + (number % 10)); System.out.println('Divisible by 2? ' + (number % 20)); System.out.println('Divisible by 3? ' + (number % 30)); System.out.println('Divisible by 4? ' + (number % 40)); System.out.println('Divisible by 5? ' + (number % 50));}}'; boolean changed = codeChanged(origCode); assertTrue(changed); } @Test public void testBool6() throws IOException { String target = 'number % 60'; boolean passed = checkCodeContains('boolean check for divisibility by 6', target); assertTrue(passed); } @Test public void testBool7() throws IOException { String target = 'number % 70'; boolean passed = checkCodeContains('boolean check for divisibility by 7', target); assertTrue(passed); } }

3.1.5. Summary¶

  • Primitive values and reference values can be compared using relational operators (i.e.,and !=) in Java.

  • Arithmetic expression values can be compared using relational operators (i.e., <, >, <=, >=) in Java.

  • An expression involving relational operators evaluates to a Boolean value of true or false.

3.1.6. Relational Operators Practice Game¶

Try the game below to practice. Click on Relationals, evaluate the relational expression and click on None, All, or the numbers that make the expression true. Check on Compound for an added challenge. We encourage you to work in pairs and see how high a score you can get.





broken image