ENSC 151 - Week 2 (Complete) PDF

Document Details

ExcellentErudition5150

Uploaded by ExcellentErudition5150

Seattle Pacific University

Yuri Rodrigues, PhD

Tags

C++ programming programming concepts data types computer science

Summary

This document is a lecture presentation on C++ programming concepts, covering data types, variables, arithmetic expressions, and input/output streams, intended for an undergraduate-level computer science course.

Full Transcript

ENSC 151 – Week 2 Professor: Yuri Rodrigues, PhD Based on material from Dr. Maira Monteiro of the Seattle Pacific University, used here with permission Objectives We will learn general concepts of programming in C++. For this, the following key concepts are covered: Become...

ENSC 151 – Week 2 Professor: Yuri Rodrigues, PhD Based on material from Dr. Maira Monteiro of the Seattle Pacific University, used here with permission Objectives We will learn general concepts of programming in C++. For this, the following key concepts are covered: Become familiar with the basic components of a C++ program, including special symbols, and identifiers Explore simple data types Discover how to use arithmetic operators Examine how a program evaluates arithmetic expressions Become familiar with the string data type Learn what an assignment statement is and what it does Learn what a stream is and examine input and output streams Learn how to use predefined functions in a program I/O Streams and Standard I/O Devices (1 of 3) I/O: sequence of bytes (stream of bytes) from source to destination Bytes are usually characters unless the program requires other types of information Stream: sequence of characters from the source to the destination Input stream: sequence of characters from an input device to the computer Output stream: sequence of characters from the computer to an output device 3 I/O Streams and Standard I/O Devices (2 of 3) Use iostream header file to receive data from the keyboard and send output to the screen This header contains definitions of two data types: istream: input stream >> (extraction operator) ENSC 151 ostream: output stream executing ENSC 151 > variable >> variable … ;) 20 Assignment Statement (1 of 2) Example illustrates a walk-through (tracing values through a sequence) Example: int num1, num2, num3; num1 = 18; num1 = num1 + 27; num2= num1; num3 = num2/5; num3 = num3/4; Commas separate items in a list Declaring more than one variable following a data type Assignment Statement (2 of 2) Given int variables x, y, and z. How is this legal C++ statement evaluated? x = y = z The assignment operator is evaluated from right to left The associativity of the assignment operator is from right to left 23 Quick question Question: What are the values of A and B after this code snippet? int A, B; A = 2; B = 4; A = B + B / A; B = A * 5 + 3 * 2; A) A = 6, B = 36 B) A = 4, B = 26 C) A = 6, B = 66 Declaring and Initializing Variables Not all types of variables are initialized automatically Variables can be initialized when declared: int first = 13, second = 10; char ch = ' '; double x = 12.6; All variables must be initialized before they are used But not necessarily during declaration 25 Saving and Using the Value of an Expression Declare a variable of the appropriate data type Assign the value of the expression to the variable that was declared Use the assignment statement Wherever the value of the expression is needed, use the variable holding the value 26 Form and Style Consider two ways of declaring variables: Method 1 int feet, inches; double x, y; Method 2 int feet,inches; double x,y; Both are correct; however, the second is harder to read 27 Variables, Assignment Statements, and Input Statements Data must be loaded into main memory before it can be manipulated Storing data in memory is a two-step process: 1. Instruct the computer to allocate memory 2. Include statements in the program to put data into the allocated memory 28 Allocating Memory with Constants and Variables (1 of 2) Named constant: memory location whose content cannot change during execution Syntax to declare a named constant Advantages: Variables that don’t change but are used many times can be re-defined once at the start of the program if needed Compiler will give an error if you mistype name of a variable, not the value Useful to use constant instead of writing value over and over again Allocating Memory with Constants and Variables (2 of 2) Variable: memory location whose content may change during execution Syntax to declare one or multiple variables 30 Quick question Question: Which of the following statements is correct? A) The location of a variable may change during the program. B) The name of a variable may change during the program. C) The value of a variable may change during the program. More on Assignment Statements Two forms of assignment Simple and compound Compound operators provide more concise notation Compound operators: +=, -=, *=, /=, %= Simple assignment statement example x = x * y; Compound assignment statement example x *= y; 32 Special Symbols A token is the smallest individual unit of a program written in any language C++ tokens include special symbols, word symbols, and identifiers Special symbols in C++ include: + - * /. ; ? , = 33 Reserved Words (Keywords) Reserved word symbols (or keywords): Cannot be redefined within a program Cannot be used for anything other than their intended use Examples include: int float double char const void return bool true false 34 Identifiers Identifiers (1 of 2) An identifier is the name of something that appears in a program Consists of letters (a-z, A-Z), digits (0-9), and the underscore character (_) Must begin with a letter or underscore C++ is case sensitive NUMBER is not the same as number Reserved words: A programmer cannot use a reserved word as an identifier int, float, double, char, const, return Always lower case, treated as one symbol, cannot be redefined (Usually) shown in blue in zyBooks 36 Identifiers (2 of 2) Legal identifiers in C++ first conversion payRate Illegal Identifier Reason A Correct Identifier There can be no space between employee Salary employeeSalary employee and Salary. The exclamation mark cannot be Hello! Hello used in an identifier. The symbol + cannot be used in one+two onePlusTwo an identifier. An identifier cannot begin with a 2nd second digit. 37 In-class activity Check if the following identifiers are valid: 1) c  2) cat  3) n1m1  4) short1  5) _hello  6) 42c x _42c or a42c 7) hi there x hi_there or hiThere 8) cat! x cat Style guidelines Now that we are declaring/assigning variables, we need to know some rules There are rules in C++, and rules for this course There will likely be rules (or guidelines) in your future careers Two common conventions for naming variables are: camelCase: capitalize each word except the first, e.g., numApples, peopleOnBus Underscore separated: lowercase words and separate using underscore, e.g., num_apples, people_on_bus The key is to be consistent, so code is easier to read and maintain. Good practice Create meaningful identifier names that self-describe an item's purpose. Minimize use of abbreviations in identifiers except for well-known ones. num numPassengers. Abbreviations x Long variable names Programmers must strive to find a balance. Abbreviations make programs harder to read and can lead to confusion. Long variable names may be meaningful but can make subsequent statements too long and thus hard to read. averageAgeOfUclaGraduateStudent Good practice ENSC 151 rules: camelCase for variable names numCars Constants will be all caps and in snake case, MAX_TEMP No single characters except in certain cases (e.g., loops) No meaningless variable names (e.g., blah is not good) Valid…but style matters VALID – Will compile Valid and follows CS1230 STYLE age_of_dog ageOfDog PrintHeading printHeading _employee_num employeeNum Change_Rate (constant) CHANGE_RATE VALID but use only in special ways (e.g., loops) x y i j Arithmetic Expressions Arithmetic Overview (1 of 2) Arithmetic expressions contain values and arithmetic operators Operands are the numbers appearing in the expressions Operators can be: unary (one operand) E.g., in expression -5, the symbol - specifies that the number 5 is negative. In this expression, - has only one operand. binary (two operands) E.g., in expression 8 -7, the symbol - is used to subtract 7 from 8. In this expression, - has two operands, 8 and 7. 45 Arithmetic Overview (2 of 2) Name Meaning Example Result + Addition 34 + 1 35 - Subtraction 34.0 – 0.1 33.9 - Negation 12 + (–3) 9 * Multiplication 300 * 30 9000 / Division 1.0 / 2.0 0.5 % Remainder 20 % 3 2 +, -, *, and / can be used with integral and floating-point data types Remainder or Modulus (%) can only be used with integral data types Integer division and modulo When both operands of a division operation are integers, the result is truncated to an integer. The modulus operator yields the remainder of integer division. 12/3 = 4 12%3 = 0 14/3 = 4 14%3 = 2 3/14 = 0 3%14 = 3 quotient quotient quotient 4 4 0 3 12 3 14 14 3 -12 -12 -0 0 2 3 remainder remainder remainder If at least one operand of division is a floating-point type, then floating-point division occurs. From Math to Code double radius, area; 𝐴𝐴 = 𝜋𝜋𝑟𝑟 2 area = M_PI * radius * radius; // M_PI * pow(radius,2); 𝑐𝑐 + 4𝑥𝑥 𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟 = 5 result = (c + 4 * x) / 5; ≠c+4*x/5 4 9 + 𝑥𝑥 𝑎𝑎𝑎𝑎𝑎𝑎 = 9( + ) ans = 9 * (4 / x + (9 + x) / y); 𝑥𝑥 𝑦𝑦 (9 + x) / y ≠ 9 + x / y *Parentheses cannot be used to indicate multiplication in programming. It is ALWAYS okay to split it up 3 + 4 x 10( y − 5)( a + b + c ) 4 9+ x − + 9( + ) 5 x x y Either way is OK: result = (3 + 4 * x) / 5 – 10 * (y - 5)*(a + b + c)/ x + 9 * (4 / x + (9 + x) / y); OR ans1 = (3 + 4 * x) / 5; ans2 = (10 * (y - 5)*(a + b + c)/ x); ans3 = (9 * (4 / x + (9 + x) / y)); Result = ans1 – ans2 + ans3; Examples Evaluation of expressions 2 * (x + 1) 2 * -x x + 1 * y/2 y=3+2*x y=x*2/3 *If parentheses are omitted, a different order of evaluation than desired occurs, leading to a bug, e.g., Assume x = 1; 2 * (x + 1) = 2 * ( 1 + 1) = 2 * 2 = 4 Otherwise: 2*x+1=2*1+1=2+1=3 Good practice Use parentheses to make order of evaluation explicit, rather than relying on precedence rules, as in: y = (m * x) + b Include a single blank space around operators for readability. numItems + 2 (rather than numItems+2) Exception for minus used as negative. xCoord = -yCoord Example 1) Evaluate the Expression: 7 * 10 - 8 / 3 * 4 + 9 = means (7 * 10) - 8 / 3 * 4 + 9 = 70 - (8 / 3) * 4 + 9 = 70 - ( 2 * 4) + 9 = ( 70 - 8 ) + 9 = What is operator 62 + 9 = precedence? 71 Quick question 2) Evaluate the Expression: 7 * (((10 - 5) / 3) * 4 + 9) = 7 * (((10 - 5) / 3) * 4 + 9) = 7 * (( 5 / 3 ) * 4 + 9) = 7 * (( 1 * 4) + 9) = 7 * ( 4 + 9) = 7 * 13 = 91 Type and numeric conversions Evaluating the Expression If all operands are integers It is an integral expression An integral expression yields an integral result Example: 2 + 3 * 5 = 17 If all operands are floating-point It is a floating-point expression A floating-point expression yields a floating-point result Example: 12.8 * 17.5 - 34.50 224.0 – 34.50 = 189.5 Mixed Expressions (1 of 2) Mixed expression Has operands of different data types Contains integers and floating-point Examples of mixed expressions (implicit type conversion) 4 + 3.5 = 7.5 5 / 4 + 1.7 = 2.7 Evaluation rules If the operator has same types of operands The operator is evaluated according to the type of the operands If the operator has both types of operands Integer is changed to floating-point Operator is evaluated Result is floating-point Entire expression is evaluated according to precedence rules60 Mixed-Mode Assignment If variable and expression are of the same data type. No problem If variable and expression are of different types. 1) expression is evaluated THEN 2) the result is converted into the data type of the variable THEN 3) converted value is stored in variable Quick question Evaluate Mixed Expressions: 1) 2 + 3.5 = 5.5 2) 6 / 4 + 3.9 = 1 + 3.9 = 4.9 3) 5.4 * 2 – 13.6 + 19 / 2 = 10.8 – 13.6 + 19 / 2 = 10.8 – 13.6 + 9 = 6.2 4) 5.4 * 2 – 13.6 + 19 / 2.0 = 10.8 – 13.6 + 19 / 2.0 = 10.8 – 13.6 + 9.5 = 6.7 Type Conversion (Casting) (1 of 2) Cast operator (also called type conversion or type casting): provides explicit type conversion static_cast(expression) Common errors: 1) Forgetting cast results in integer division Type Conversion (Casting) (2 of 2) Cast operator (also called type conversion or type casting): provides explicit type conversion static_cast(expression) 2) Casting final result instead of operands Numeric Conversion binary to decimal: Conversion 𝟏𝟏 𝟏𝟏 𝟎𝟎 𝟏𝟏 Bits is typically represented as 1s and 0s. = 𝟏𝟏 23 + 𝟏𝟏 22 + 𝟎𝟎 21 + 𝟏𝟏 20 Byte is composed of 8 bits. = 𝟏𝟏 8 + 𝟏𝟏 4 + 𝟎𝟎 2 + 𝟏𝟏 1 = 8 + 4 + 0 + 1 = 13 Binary (base 2) is a number system with only two digits: 0 and 1 Conversion decimal to binary: e.g.,10 In contrast, decimal number Remainder (base 10) has ten: 2 10 0 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 1010 2 5 1 The compiler translates decimal numbers into binary numbers 2 2 0 before storing the number into a memory location. 2 1 1 The binary number will be exactly the number from bottom to top Math Functions Using Predefined A function (subprogram) is a set of instructions Functions in a Program When activated, it accomplishes a task main executes when a program is run Other functions execute only when called C++ includes a wealth of functions Predefined functions are organized as a collection of libraries called header files Header file may contain several functions To use a predefined function, you need the name of the appropriate header file You also need to know: Function name Number of parameters required Type of each parameter What the function is going to do Calling Mathematical Library Functions function’s name ( arguments ) To make cmath available to your Any function arguments appear within ( ), separated program: by commas if more than one. #include Ex: sqrt() Each argument can be a single variable, a constant, or an expression (as long as it evaluates to the To make cstdlib available to your correct data type). program: #include To evaluate an expression, functions are at the top of the priority list. Ex: abs() These libraries includes functions For example: and definitions that make semi- complex calculations easy. Example Quick questions Write the ending value of z. 1) z = pow(2.0, pow(2.0, 3.0)); pow(2.0, 8.0) = 256.0 2) x = 9.0; z = pow(sqrt(x) + sqrt(x), 2.0); pow(3.0 + 3.0, 2.0) = 36.0 3) x = -9.0; z = sqrt(fabs(x)); sqrt(9.0) = 3.0 Conclusion We learned the basics of the C++ language to communicate instructions to the computer including: data types declaring and using variables initialization and assignment of values to variables expressions type and numeric conversions math functions Summary List and define the key programming concepts covered. Explain the difference between the data types. Remember the rules for identifiers. Know how to declare and initialize variables Understand and explain the assignment operator. Define: operator, operand, unary, binary Remember operator precedence for expressions. Understand how to evaluate and write mixed expressions. Apply type and numeric conversions Know how to evaluate and translate mathematical expressions to C++ program.

Use Quizgecko on...
Browser
Browser